예제 #1
0
    def import_profile(self):
        # Does NOT delete user profiles but simply overwrites values in
        # existing ones that were created by import_user previously.
        """
        --- profile -----------------------------------------------------------
        {"user_id":"1","nick":"admin","name":"Graniteland","contact":
        "xxxxxxx","contact_position":"","slogan":"","street":"","city":"",
        "zip":"","country_sub_id":"0","country_id":"0","country_sub_name":"",
        "country_name":"","postal":"","email":"*****@*****.**","fax":"",
        "tel":"","mobile":"","web":"","about":"","title_foto":"0",
        "title_foto_ext":""}
        """
        i = 0
        count = User.objects.all().count()
        print('Update user profiles for {} users.'.format(count))

        for row in self.walkjsondata('user_profiles'):
            i += 1
            pk = force_int(row['user_id'])
            try:
                profile = UserProfile.objects.get(user_id=pk)
            except UserProfile.DoesNotExist:
                print('No profile: {} {}'.format(pk, row['name']))
                continue

            print('{}/{} - Updating profile {}'
                  .format(i, count, row['name']), end=' ')

            # Figure out the country
            country_id = force_int(row['country_id'])
            country = Companydb_Country.objects.filter(pk=country_id).first()
            if country:
                print(' country {}'.format(country.name), end=' ')
                profile.country = country
            else:
                print(' no country!'.format(profile.name), end=' ')

            profile.contact = row['contact']
            profile.contact_position = row['contact_position']
            profile.slogan = row['slogan']
            profile.street = row['street']
            profile.city = row['city']
            profile.zip = row['zip']
            profile.country_sub_id = row['country_sub_id']
            profile.country_sub_name = row['country_sub_name']
            profile.country_name = row['country_name']
            profile.postal = row['postal']
            profile.email = row['email']
            profile.fax = row['fax']
            profile.tel = row['tel']
            profile.mobile = row['mobile']
            profile.web = row['web']
            profile.about = row['about']
            profile.save()
            print('.', end='', flush=True)
            print(' done!')
예제 #2
0
파일: views_me.py 프로젝트: C14L/dtr5
def me_update_view(request):
    """
    Update the user profile with fresh data from user's Reddit account,
    then simply redirect to user's "me" page and add message to confirm
    the success or report failure.
    """
    # Reload user's subreddit list from reddit.
    subscribed = api.get_sr_subscriber(request, settings.SR_FETCH_LIMIT)
    if subscribed:
        update_list_of_subscribed_subreddits(request.user, subscribed)

        if len(subscribed) > settings.USER_MIN_SUBSCRIBED_SUBREDDITS:
            pass
            # messages.success(request, 'Subreddit list updated with {} items.'
            #                  .format(len(subscribed)))
        else:
            messages.success(request, 'Subreddit list updated, but you are '
                             'only subscribed to {} subreddits. Find some '
                             'more that interest you for better results '
                             'here :)'.format(len(subscribed)))
    else:
        messages.warning(request, 'Could not find any subscribed subreddits. '
                         'Most likely, because you are still only subscribed '
                         'to the default subs and have not yet picked your '
                         'own selection.')

    # Reload user profile data from Reddit.
    reddit_user = api.get_user(request)
    if settings.DEBUG:
        print('--> reddit_user: '******'created_utc']

        p = request.user.profile
        p.name = reddit_user['name']
        p.created = datetime.utcfromtimestamp(t).replace(tzinfo=pytz.utc)
        p.updated = datetime.now().replace(tzinfo=pytz.utc)
        p.link_karma = force_int(reddit_user['link_karma'])
        p.comment_karma = force_int(reddit_user['comment_karma'])
        p.over_18 = bool(reddit_user['over_18'])
        p.hide_from_robots = bool(reddit_user['hide_from_robots'])
        p.has_verified_email = bool(reddit_user['has_verified_email'])
        p.gold_creddits = bool(reddit_user['gold_creddits'])
        p.save()
        # messages.success(request, 'Profile data updated.')
    else:
        messages.warning(request, 'Could not find any user profile data.')

    # Go back to user's "me" page, the updated data should show up there.
    if request.is_ajax():
        return HttpResponse()  # HTTP 200

    return redirect(reverse('me_page') + '#id_srlist')
예제 #3
0
def me_update_view(request):
    """
    Update the user profile with fresh data from user's Reddit account,
    then simply redirect to user's "me" page and add message to confirm
    the success or report failure.
    """
    # Reload user's subreddit list from reddit.
    subscribed = api.get_sr_subscriber(request)
    if subscribed:
        update_list_of_subscribed_subreddits(request.user, subscribed)

        if len(subscribed) > settings.USER_MIN_SUBSCRIBED_SUBREDDITS:
            messages.success(request, 'Subreddit list updated.')
        else:
            messages.success(request, 'Subreddit list updated, but you are '
                             'only subscribed to {} subreddits. Find some '
                             'more that interest you for better results '
                             'here :)'.format(len(subscribed)))
    else:
        messages.warning(request, 'Could not find any subscribed subreddits. '
                         'Most likely, because you are still only subscribed '
                         'to the default subs and have not yet picked your '
                         'own selection.')

    # Reload user profile data from Reddit.
    reddit_user = api.get_user(request)
    if settings.DEBUG:
        print('--> reddit_user: '******'created_utc'])

        p = request.user.profile
        p.name = reddit_user['name']
        p.created = datetime.utcfromtimestamp(t).replace(tzinfo=pytz.utc)
        p.updated = datetime.now().replace(tzinfo=pytz.utc)
        p.link_karma = force_int(reddit_user['link_karma'])
        p.comment_karma = force_int(reddit_user['comment_karma'])
        p.over_18 = bool(reddit_user['over_18'])
        p.hide_from_robots = bool(reddit_user['hide_from_robots'])
        p.has_verified_email = bool(reddit_user['has_verified_email'])
        p.gold_creddits = bool(reddit_user['gold_creddits'])
        p.save()

        messages.success(request, 'Profile data updated.')
    else:
        messages.warning(request, 'Could not find any user profile data.')
    # Go back to user's "me" page, the updated data should show up there.
    return redirect(reverse('me_page') + '#id_srlist')
예제 #4
0
파일: views.py 프로젝트: C14L/gl4
def redir_search_php(request):
    # /stone/redir_search.php?p=1&color=&country=&classification=13&pseu=
    #  -->
    # /stone/france/coarse-grained/blue/sandstone
    p = force_int(request.GET.get('p', 1))
    color = force_int(request.GET.get('color', 0))
    country = force_int(request.GET.get('country', 0))
    texture = force_int(request.GET.get('texture', 0))
    classification = force_int(request.GET.get('type', 0))

    if color:
        color = get_object_or_404(Color, pk=color)
    if country:
        country = get_object_or_404(Country, pk=country)
    if texture:
        texture = get_object_or_404(Texture, pk=texture)
    if classification:
        classification = get_object_or_404(Classification, pk=classification)

    # Now redirect depending on what values we received.
    if not (color or country or texture or classification):
        # no vals at all?!
        url = reverse('stonedb_home')
    elif color and not (country or texture or classification):
        # only color
        url = reverse('stonedb_simple_filter',
                      kwargs={'f': settings.TR_COLOR, 'q': color.slug})
    elif country and not (color or texture or classification):
        # only country
        url = reverse('stonedb_simple_filter',
                      kwargs={'f': settings.TR_COUNTRY, 'q': country.slug})
    elif texture and not (color or country or classification):
        # only texture
        url = reverse('stonedb_simple_filter',
                      kwargs={'f': settings.TR_TEXTURE, 'q': texture.slug})
    elif classification and not (color or country or texture):
        # only classification
        url = reverse('stonedb_simple_filter',
                      kwargs={'f': settings.TR_TYPE, 'q': classification.slug})
    else:
        # if there are at least two properties defined, then show filter page.
        url = reverse('stonedb_filter', kwargs={
            'color': getattr(color, 'slug', FILTER_URL_NO_VALUE),
            'country': getattr(country, 'slug', FILTER_URL_NO_VALUE),
            'texture': getattr(texture, 'slug', FILTER_URL_NO_VALUE),
            'classif': getattr(classification, 'slug', FILTER_URL_NO_VALUE)})
        if p > 1:
            url['p'] = p

    return HttpResponsePermanentRedirect(url)
예제 #5
0
파일: utils.py 프로젝트: C14L/dtr5
def assert_pic_accessible(pic_url):
    # Check for HTTP 200 response on that URL, load time,
    # file size, file type, etc.
    try:
        r = requests.head(pic_url, timeout=5)
    except:
        raise PictureInaccessibleError(
            'The image {} is loading very slowly.'.format(pic_url))

    if r.status_code == 302 and 'imgur.com' in pic_url:
        return PictureInaccessibleError(
            'The image at "{}" can not be accessed, it was <b>probably '
            'deleted on Imgur</b>.'.format(pic_url))

    if r.status_code != 200:
        return PictureInaccessibleError(
            'The image "{}"" can not be accessed, it returned HTTP status '
            'code "{}".'.format(pic_url, r.status_code))

    if r.headers.get('content-type', None) not in settings.PIC_CONTENT_TYPES:
        return PictureInaccessibleError(
            'Not recognized as an image file. Please only use jpg, gif, '
            'png, or webp images. Recognized content type was "{}".'.
            format(r.headers.get('content-type', '')))

    if force_int(r.headers.get('content-length')) > (1024 * 512):
        x = int(int(r.headers.get('content-length')) / 1024)
        return PictureInaccessibleError(
            'The image file size ({} kiB) is too large. Please use a '
            'smaller size (max. 500 kiB) to ensure that your profile '
            'page loads fast for your visitors.'.format(x))

    return True
예제 #6
0
def assert_pic_accessible(pic_url):
    # Check for HTTP 200 response on that URL, load time,
    # file size, file type, etc.
    try:
        r = requests.head(pic_url, timeout=5)
    except:
        raise PictureInaccessibleError(
            'The image {} is loading very slowly.'.format(pic_url))

    if r.status_code == 302 and 'imgur.com' in pic_url:
        return PictureInaccessibleError(
            'The image at "{}" can not be accessed, it was <b>probably '
            'deleted on Imgur</b>.'.format(pic_url))

    if r.status_code != 200:
        return PictureInaccessibleError(
            'The image "{}"" can not be accessed, it returned HTTP status '
            'code "{}".'.format(pic_url, r.status_code))

    if r.headers.get('content-type', None) not in settings.PIC_CONTENT_TYPES:
        return PictureInaccessibleError(
            'Not recognized as an image file. Please only use jpg, gif, '
            'png, or webp images. Recognized content type was "{}".'.format(
                r.headers.get('content-type', '')))

    if force_int(r.headers.get('content-length')) > (1024 * 512):
        x = int(int(r.headers.get('content-length')) / 1024)
        return PictureInaccessibleError(
            'The image file size ({} kiB) is too large. Please use a '
            'smaller size (max. 500 kiB) to ensure that your profile '
            'page loads fast for your visitors.'.format(x))

    return True
예제 #7
0
파일: views.py 프로젝트: C14L/dtr5
def usermap_view(request, template_name='dtr5app/usermap.html'):
    if request.is_ajax():
        west = request.GET.get('west', None)
        south = request.GET.get('south', None)
        east = request.GET.get('east', None)
        north = request.GET.get('north', None)
        t = force_int(request.GET.get('t', 0))

        if settings.DEBUG:
            print(west, north, east, south, t)

        users = User.objects.exclude(
            profile__lat__gte=-0.1, profile__lng__gte=-0.1,
            profile__lat__lte=1.1, profile__lng__lte=1.1
            ).filter(
            profile__lat__gte=south, profile__lng__gte=west,
            profile__lat__lte=north, profile__lng__lte=east,
            is_active=True, last_login__isnull=False)

        if t > 0:
            tmin = datetime.now().replace(tzinfo=pytz.utc)-timedelta(minutes=t)
            users = users.filter(profile__accessed__gte=tmin)

        users = [[u.username, u.profile.lat, u.profile.lng]
                 for u in users.prefetch_related('profile')[:250]]

        return JsonResponse({'users': users})

    ctx = {}
    kwargs = {'context_instance': RequestContext(request)}
    return render_to_response(template_name, ctx, **kwargs)
예제 #8
0
파일: initial_data.py 프로젝트: C14L/gl4
def import_company_countries(force=False, silent=False):
    if force:
        Country.objects.all().delete()

    header = ['iso', 'iso3', 'iso_numeric', 'fips', 'country', 'capital',
              'area', 'population', 'continent', 'tld', 'currency_code',
              'currency_name', 'phone', 'postal_code_format',
              'postal_code_regex', 'languages', 'geonameid', 'neighbours',
              'equivalent_fips_code']
    filename = 'countryInfo_{}.txt'.format(settings.LANGUAGE_SHORT)
    filename = join(settings.BASE_DIR, '..', 'fixtures', filename)

    with open(filename, newline='') as fh:
        reader = csv.DictReader(filter(lambda row: row[0] != '#', fh),
                                fieldnames=header, delimiter='\t',
                                quoting=csv.QUOTE_NONE, lineterminator='\n')

        for raw in reader:
            pk = force_int(raw['iso_numeric'])
            geonameid = force_int(raw['geonameid'])
            if raw['country'] == 'Democratic Republic of the Congo':
                raw['country'] = 'D.R.Congo'
            if raw['country'] == 'United States':
                raw['country'] = 'U.S.A.'

            if int(raw['population']) < 50000:
                continue
            if not (geonameid and pk):
                continue
            if raw['country'] in (
                    'Saint Vincent and the Grenadines', 'Reunion',
                    'Netherlands Antilles', 'Isle of Man',
                    'Serbia and Montenegro', 'U.S. Virgin Islands',
                    'Northern Mariana Islands', 'Jersey', ):
                continue
            if Country.objects.filter(pk=pk).first():
                continue

            if not silent:
                print('{}'.format(raw['iso']), end=' ', flush=True)

            Country.objects.create(
                id=pk, name=raw['country'], geonameid=geonameid,
                cc=raw['iso'][:2], phone=raw['phone'][:10])

    if not silent:
        print('ok.')
예제 #9
0
def me_manual_view(request):
    """
    Save profile data manually input by auth user: birthdate, sex, etc.
    """
    if request.POST.get("dob", None):
        try:
            dob = dateutil.parser.parse(request.POST.get("dob", None)).date()
            request.user.profile.dob = dob
        except:
            # messages.error('')
            # Older browsers may submit a completely malformated dob. Ignore it
            # and carry on, no good to bother the user with this during the
            # signup flow.
            dob = datetime(year=1990, month=1, day=1).date()

        if get_age(dob) < 18:
            messages.warning(
                request, "sorry, you need to be 18 or older " "to sign up on this site."
            )
            return redirect(reverse("me_page") + "#id_profile")

    if request.POST.get("sex", None):
        request.user.profile.sex = force_int(request.POST.get("sex"))
    if request.POST.get("about", None):
        request.user.profile.about = request.POST.get("about")
    if request.POST.getlist("lookingfor", None):
        request.user.profile.lookingfor = request.POST.getlist("lookingfor")

    if request.POST.get("pref_distance_unit", None):
        request.user.profile.pref_distance_unit = request.POST.get("pref_distance_unit")

    if request.POST.get("herefor", None):
        request.user.profile.herefor = request.POST.get("herefor")

    if request.POST.get("tagline", None):  # unused
        request.user.profile.tagline = request.POST.get("tagline")
    if request.POST.get("relstatus", None):  # unused
        request.user.profile.relstatus = request.POST.get("relstatus")
    if request.POST.get("education", None):  # unused
        request.user.profile.education = request.POST.get("education")
    if request.POST.get("height", None):  # unused
        request.user.profile.height = request.POST.get("height")
    if request.POST.get("weight", None):  # unused
        request.user.profile.weight = request.POST.get("weight")
    if request.POST.get("fitness", None):  # unused
        request.user.profile.fitness = request.POST.get("fitness")

    request.user.profile.save()
    # messages.success(request, 'Profile data updated.')

    if request.is_ajax():
        return HttpResponse()  # HTTP 200

    _next = request.POST.get("next", "#id_profile")
    if _next.startswith("#"):
        _next = reverse("me_page") + _next
    return redirect(_next)
예제 #10
0
파일: views_me.py 프로젝트: C14L/dtr5
def me_manual_view(request):
    """
    Save profile data manually input by auth user: birthdate, sex, etc.
    """
    if request.POST.get('dob', None):
        try:
            dob = dateutil.parser.parse(request.POST.get('dob', None)).date()
            request.user.profile.dob = dob
        except:
            # messages.error('')
            # Older browsers may submit a completely malformated dob. Ignore it
            # and carry on, no good to bother the user with this during the
            # signup flow.
            dob = datetime(year=1990, month=1, day=1).date()

        if get_age(dob) < 18:
            messages.warning(request, 'sorry, you need to be 18 or older '
                                      'to sign up on this site.')
            return redirect(reverse('me_page') + '#id_profile')

    if request.POST.get('sex', None):
        request.user.profile.sex = force_int(request.POST.get('sex'))
    if request.POST.get('about', None):
        request.user.profile.about = request.POST.get('about')
    if request.POST.getlist('lookingfor', None):
        request.user.profile.lookingfor = request.POST.getlist('lookingfor')

    if request.POST.get('pref_distance_unit', None):
        request.user.profile.pref_distance_unit = \
            request.POST.get('pref_distance_unit')

    if request.POST.get('herefor', None):
        request.user.profile.herefor = request.POST.get('herefor')

    if request.POST.get('tagline', None):  # unused
        request.user.profile.tagline = request.POST.get('tagline')
    if request.POST.get('relstatus', None):  # unused
        request.user.profile.relstatus = request.POST.get('relstatus')
    if request.POST.get('education', None):  # unused
        request.user.profile.education = request.POST.get('education')
    if request.POST.get('height', None):  # unused
        request.user.profile.height = request.POST.get('height')
    if request.POST.get('weight', None):  # unused
        request.user.profile.weight = request.POST.get('weight')
    if request.POST.get('fitness', None):  # unused
        request.user.profile.fitness = request.POST.get('fitness')

    request.user.profile.save()
    # messages.success(request, 'Profile data updated.')

    if request.is_ajax():
        return HttpResponse()  # HTTP 200

    _next = request.POST.get('next', '#id_profile')
    if _next.startswith('#'):
        _next = reverse('me_page') + _next
    return redirect(_next)
예제 #11
0
파일: views.py 프로젝트: C14L/gl4
def item(request, y, slug):
    this_year = date.today().year
    year = force_int(y)
    tradeshow = Tradeshow.objects.filter(begins__year=year, url=slug).first()
    if not tradeshow:
        raise Http404()
    return render(request, 'tradeshowdb/item.html', {
        'years': range((this_year-1), (this_year+4)), 'tradeshow': tradeshow,
        'canonical': reverse('tradeshowdb_item', args=[year, tradeshow.slug]),
        'view_year': year, 'tpl_search_form': 'tradeshows'})
예제 #12
0
파일: views.py 프로젝트: jkoelker/dtr5
def me_picture_view(request):
    """
    Save the URL of a picture.
    """
    allowed_content_types = ['image/jpeg', 'image/gif', 'image/webp',
                             'image/png']
    pic_url = request.POST.get('pic_url', '')
    if not pic_url:
        return HttpResponse('Please add the URL for a picture.')

    # TODO: check for valid URL schema.

    # If imgur.com picture, set to "medium" size.
    pic_url = set_imgur_url(pic_url, size='m')
    # Check for HTTP 200 response on that URL, load time,
    # file size, file type, etc.
    try:
        r = requests.head(pic_url, timeout=5)  # ? sec timeout
    except:
        return HttpResponse(
            'The image {} is loading too slowly.'.format(pic_url))

    if r.status_code == 302 and 'imgur.com' in pic_url:
        return HttpResponse('The image at "{}" can not be accessed, it was '
                            '<b>probably deleted on Imgur</b>.'.
                            format(pic_url))
    if r.status_code != 200:
        return HttpResponse('The image "{}"" can not be accessed, it returned '
                            'HTTP status code "{}".'.
                            format(pic_url, r.status_code))
    if r.headers.get('content-type', None) not in allowed_content_types:
        return HttpResponse('Not recognized as an image file. Please only '
                            'use jpg, gif, png, or webp images. Recognized '
                            'mime type was "{}".'.
                            format(r.headers.get('content-type', '')))
    if force_int(r.headers.get('content-length')) > (1024 * 512):
        x = int(int(r.headers.get('content-length')) / 1024)
        return HttpResponse('The image file size ({} kiB) is too large. '
                            'Please use a smaller size (max. 500 kiB).'.
                            format(x))
    if pic_url in [x['url'] for x in request.user.profile.pics]:
        return HttpResponse('That picture already exists in your profile.')

    if len(request.user.profile.pics) >= settings.USER_MAX_PICS_COUNT:
        messages.info(request, 'oldest picture was deleted to make room for '
                               'the picture you added.')

    # prepend the new pic to make it the new "profile pic"
    request.user.profile.pics = [{'url': pic_url}] + request.user.profile.pics
    request.user.profile.save()

    return redirect(reverse('me_page') + '#id_pics')
예제 #13
0
    def import_projects(self):
        i = 0
        print('Import project', end='', flush=True)
        Project.objects.all().delete()
        for row in self.walkjsondata('stones_projects'):
            try:
                stone = Stone.objects.get(pk=row['stone_id'])
            except Stone.DoesNotExist:
                # print('Stone not found for proj. {}'.format(row['stone_id']))
                print('SE', end='', flush=True)
                continue
            try:
                user = User.objects.get(pk=row['user_id'])
            except User.DoesNotExist:
                # print('User not found for project {}'.format(row['user_id']))
                print('UE', end='', flush=True)
                continue
            item = Project(id=row['id'])
            item.user = user
            item.created = parse_iso_datetime(row['time'])
            if not item.created:  # skip if no created time
                continue
            item.description = row['description']
            item.is_blocked = bool(force_int(row['is_blocked']))
            item.is_deleted = bool(force_int(row['is_deleted']))
            if item.is_blocked or item.is_deleted:  # skip deleted items
                continue
            item.is_recommended = bool(force_int(row['is_recommended']))
            item.count_views = force_int(row['count_views'])
            item.save()

            item.stones.add(stone)
            item.save()

            i += 1
            print('.', end='', flush=True)
            if (i % 1000) == 0:
                print(i, end='', flush=True)
        print('done. {} project items imported.'.format(i))
예제 #14
0
def sr_view(request, sr, template_name="dtr5app/sr.html"):
    """
    Display a list of users who are subscribed to a subreddit.
    """
    pg = int(request.GET.get("page", 1))
    view_sr = get_object_or_404(Sr, display_name__iexact=sr)

    if request.user.is_anonymous and not view_sr.display_name.lower() in [
        x.lower() for x in settings.SR_ANON_ACCESS_ALLOWED
    ]:
        params = ""  # urlencode({'next': request.get_full_path()})
        return HttpResponseRedirect("{}?{}".format(settings.LOGIN_URL, params))

    params = dict()
    params["order"] = request.GET.get("order", "-last_login")
    params["has_verified_email"] = bool(
        force_int(request.GET.get("has_verified_email", 0))
    )
    params["hide_no_pic"] = bool(force_int(request.GET.get("hide_no_pic", 1)))
    params["sex"] = force_int(request.GET.get("s", 0))
    params["distance"] = force_int(request.GET.get("dist", 1))

    params["minage"] = force_int(request.GET.get("minage", 18))
    if params["minage"] not in range(18, 100):
        params["minage"] = 18
    params["maxage"] = force_int(request.GET.get("maxage", 100))
    if params["maxage"] not in range(params["minage"], 101):
        params["maxage"] = 100

    if request.user.is_authenticated:
        params["user_id"] = request.user.id
        params["lat"] = request.user.profile.lat
        params["lng"] = request.user.profile.lng

    ul = search_subreddit_users(params, view_sr)

    if params["order"] == "-accessed":  # most recently accessed first
        ul = ul.order_by("-profile__accessed")
    elif params["order"] == "-date_joined":  # most recent redddate acccount
        ul = ul.order_by("-date_joined")
    elif params["order"] == "-views_count":  # most views first
        ul = ul.order_by("-profile__views_count")

    # Paginate and add "is_like_recv" and "is_like"sent"
    ul = get_paginated_user_list(ul, pg, request.user)
    ul.object_list = add_likes_sent(ul.object_list, request.user)
    ul.object_list = add_likes_recv(ul.object_list, request.user)
    ul.object_list = add_matches_to_user_list(ul.object_list, request.user)

    ctx = {
        "view_sr": view_sr,
        "user_list": ul,
        "params": params,
        "user_subs_all": get_subs_for_user(request.user),
    }

    return render(request, template_name, ctx)
예제 #15
0
def me_picture_view(request):
    """
    Save the URL of a picture.
    """
    allowed_content_types = ['image/jpeg', 'image/gif', 'image/webp',
                             'image/png']
    pic_url = request.POST.get('pic_url', '')
    if not pic_url:
        return HttpResponse('Please add the URL for a picture.')

    # TODO: check for valid URL schema.

    # If imgur.com picture, set to "medium" size.
    pic_url = set_imgur_url(pic_url, size='m')
    # Check for HTTP 200 response on that URL, load time,
    # file size, file type, etc.
    try:
        r = requests.head(pic_url, timeout=5)  # ? sec timeout
    except:
        return HttpResponse(
            'The image {} is loading too slowly.'.format(pic_url))

    if r.status_code != 200:
        return HttpResponse('The image "{}"" can not be accessed, it returned '
                            'HTTP status code "{}".'.
                            format(pic_url, r.status_code))
    if r.headers.get('content-type', None) not in allowed_content_types:
        return HttpResponse('Not recognized as an image file. Please only '
                            'use jpg, gif, png, or webp images. Recognized '
                            'mime type was "{}".'.
                            format(r.headers.get('content-type', '')))
    if force_int(r.headers.get('content-length')) > (1024 * 512):
        x = int(int(r.headers.get('content-length')) / 1024)
        return HttpResponse('The image file size ({} kiB) is too large. '
                            'Please use a smaller size (max. 500 kiB).'.
                            format(x))
    if pic_url in [x['url'] for x in request.user.profile.pics]:
        return HttpResponse('That picture already exists in your profile.')

    if len(request.user.profile.pics) >= settings.USER_MAX_PICS_COUNT:
        messages.info(request, 'oldest picture was deleted to make room for '
                               'the picture you added.')

    # prepend the new pic to make it the new "profile pic"
    request.user.profile.pics = [{'url': pic_url}] + request.user.profile.pics
    request.user.profile.save()

    return redirect(reverse('me_page') + '#id_pics')
예제 #16
0
파일: views.py 프로젝트: jkoelker/dtr5
def me_manual_view(request):
    """
    Save profile data manually input by auth user: birthdate, sex, etc.
    """
    if request.POST.get('dob', None):
        try:
            dob = dateutil.parser.parse(request.POST.get('dob', None)).date()
            request.user.profile.dob = dob
        except:
            dob = 0
        if get_age(dob) < 18:
            messages.warning(request, 'sorry, you need to be 18 or older '
                                      'to sign up on this site.')
            return redirect(reverse('me_page') + '#id_profile')

    if request.POST.get('sex', None):
        request.user.profile.sex = force_int(request.POST.get('sex'))
    if request.POST.get('about', None):
        request.user.profile.about = request.POST.get('about')
    if request.POST.getlist('lookingfor', None):
        request.user.profile.lookingfor = request.POST.getlist('lookingfor')

    if request.POST.get('pref_distance_unit', None):
        request.user.profile.pref_distance_unit = \
            request.POST.get('pref_distance_unit')

    if request.POST.get('tagline', None):  # unused
        request.user.profile.tagline = request.POST.get('tagline')
    if request.POST.get('relstatus', None):  # unused
        request.user.profile.relstatus = request.POST.get('relstatus')
    if request.POST.get('education', None):  # unused
        request.user.profile.education = request.POST.get('education')
    if request.POST.get('height', None):  # unused
        request.user.profile.height = request.POST.get('height')
    if request.POST.get('weight', None):  # unused
        request.user.profile.weight = request.POST.get('weight')
    if request.POST.get('fitness', None):  # unused
        request.user.profile.fitness = request.POST.get('fitness')

    request.user.profile.save()
    messages.success(request, 'Profile data updated.')
    _next = request.POST.get('next', '#id_profile')
    if _next.startswith('#'):
        _next = reverse('me_page') + _next

    return redirect(_next)
예제 #17
0
파일: views.py 프로젝트: C14L/dtr5
def sr_view(request, sr, template_name='dtr5app/sr.html'):
    """
    Display a list of users who are subscribed to a subreddit.
    """
    pg = int(request.GET.get('page', 1))
    view_sr = get_object_or_404(Sr, display_name__iexact=sr)

    if request.user.is_anonymous() and not view_sr.display_name.lower() in \
            [x.lower() for x in settings.SR_ANON_ACCESS_ALLOWED]:
        params = ''  # urlencode({'next': request.get_full_path()})
        return HttpResponseRedirect('{}?{}'.format(settings.LOGIN_URL, params))

    params = dict()
    params['order'] = request.GET.get('order', '-last_login')
    params['has_verified_email'] = \
        bool(force_int(request.GET.get('has_verified_email', 0)))
    params['hide_no_pic'] = bool(force_int(request.GET.get('hide_no_pic', 1)))
    params['sex'] = force_int(request.GET.get('s', 0))
    params['distance'] = force_int(request.GET.get('dist', 1))

    params['minage'] = force_int(request.GET.get('minage', 18))
    if params['minage'] not in range(18, 100):
        params['minage'] = 18
    params['maxage'] = force_int(request.GET.get('maxage', 100))
    if params['maxage'] not in range(params['minage'], 101):
        params['maxage'] = 100

    if request.user.is_authenticated():
        params['user_id'] = request.user.id
        params['lat'] = request.user.profile.lat
        params['lng'] = request.user.profile.lng

    ul = search_subreddit_users(params, view_sr)

    if params['order'] == '-accessed':  # most recently accessed first
        ul = ul.order_by('-profile__accessed')
    elif params['order'] == '-date_joined':  # most recent redddate acccount
        ul = ul.order_by('-date_joined')
    elif params['order'] == '-views_count':  # most views first
        ul = ul.order_by('-profile__views_count')

    # Paginate and add "is_like_recv" and "is_like"sent"
    ul = get_paginated_user_list(ul, pg, request.user)
    ul.object_list = add_likes_sent(ul.object_list, request.user)
    ul.object_list = add_likes_recv(ul.object_list, request.user)
    ul.object_list = add_matches_to_user_list(ul.object_list, request.user)

    ctx = {'view_sr': view_sr, 'user_list': ul, 'params': params,
           'user_subs_all': get_subs_for_user(request.user)}
    kwargs = {'context_instance': RequestContext(request)}
    return render_to_response(template_name, ctx, **kwargs)
예제 #18
0
def sr_user_list(request, sr, format=None):
    """Return a list of users who are member of a subreddit."""
    pg = int(request.GET.get("page", 1))
    view_sr = get_object_or_404(Sr, display_name__iexact=sr)

    # Only allow a selected number of Subreddits to be views publicly.
    if request.user.is_anonymous and not view_sr.display_name.lower() in [
            x.lower() for x in settings.SR_ANON_ACCESS_ALLOWED
    ]:
        return Response(status.HTTP_401_UNAUTHORIZED)

    # Filter displayed members: normalize search options.
    params = dict()
    params["order"] = request.GET.get("order", "-last_login")
    params["has_verified_email"] = bool(
        force_int(request.GET.get("has_verified_email", 0)))
    params["hide_no_pic"] = bool(force_int(request.GET.get("hide_no_pic", 1)))
    params["sex"] = force_int(request.GET.get("s", 0))
    params["distance"] = force_int(request.GET.get("dist", 1))
    params["minage"] = force_int(request.GET.get("minage", 18))
    if params["minage"] not in range(18, 100):
        params["minage"] = 18
    params["maxage"] = force_int(request.GET.get("maxage", 100))
    if params["maxage"] not in range(params["minage"], 101):
        params["maxage"] = 100
    if request.user.is_authenticated:
        params["user_id"] = request.user.id
        params["lat"] = request.user.profile.lat
        params["lng"] = request.user.profile.lng

    # Fetch users and order them.
    ul = search_subreddit_users(params, view_sr)
    if params["order"] == "-accessed":  # most recently accessed first
        ul = ul.order_by("-profile__accessed")
    elif params["order"] == "-date_joined":  # most recent redddate acccount
        ul = ul.order_by("-date_joined")
    elif params["order"] == "-views_count":  # most views first
        ul = ul.order_by("-profile__views_count")

    # Paginate and add "is_like_recv" and "is_like"sent"
    ul = get_paginated_user_list(ul, pg, request.user)
    ul.object_list = add_likes_sent(ul.object_list, request.user)
    ul.object_list = add_likes_recv(ul.object_list, request.user)
    ul.object_list = add_matches_to_user_list(ul.object_list, request.user)

    return Response(
        data={
            "user_list": BasicUserSerializer(ul.object_list, many=True).data,
            "view_sr": ViewSrSerializer(view_sr, many=False).data,
        })
예제 #19
0
def me_manual_view(request):
    """
    Save profile data manually input by auth user: birthdate, sex, etc.
    """
    if request.POST.get('dob', None):
        try:
            dob = dateutil.parser.parse(request.POST.get('dob', None)).date()
            request.user.profile.dob = dob
        except:
            dob = 0
        if get_age(dob) < 18:
            messages.warning(request, 'sorry, you need to be 18 or older '
                                      'to sign up on this site.')
            return redirect(reverse('me_page') + '#id_profile')

    if request.POST.get('sex', None):
        request.user.profile.sex = force_int(request.POST.get('sex'))
    if request.POST.get('about', None):
        request.user.profile.about = request.POST.get('about')
    if request.POST.getlist('lookingfor', None):
        request.user.profile.lookingfor = request.POST.getlist('lookingfor')

    if request.POST.get('tagline', None):  # unused
        request.user.profile.tagline = request.POST.get('tagline')
    if request.POST.get('relstatus', None):  # unused
        request.user.profile.relstatus = request.POST.get('relstatus')
    if request.POST.get('education', None):  # unused
        request.user.profile.education = request.POST.get('education')
    if request.POST.get('height', None):  # unused
        request.user.profile.height = request.POST.get('height')
    if request.POST.get('weight', None):  # unused
        request.user.profile.weight = request.POST.get('weight')
    if request.POST.get('fitness', None):  # unused
        request.user.profile.fitness = request.POST.get('fitness')

    request.user.profile.save()
    messages.success(request, 'Profile data updated.')
    return redirect(reverse('me_page') + '#id_profile')
예제 #20
0
파일: views.py 프로젝트: C14L/gl4
def home(request, y=None):
    this_year = date.today().year
    view_year = force_int(y)
    months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
              'August', 'September', 'October', 'November', 'December']

    if y is None:
        url = reverse('tradeshowdb_by_year', kwargs={'y': this_year})
        return HttpResponsePermanentRedirect(url)

    tradeshows = Tradeshow.objects.filter(begins__year=view_year)
    ts_total = len(tradeshows)
    li = []  # sort them into per-month lists.
    for a in months:
        idx = months.index(a) + 1
        tss = [b for b in tradeshows if b.begins.month == idx]
        li.append({'idx': idx, 'name': a, 'tradeshows': tss})

    return render(request, 'tradeshowdb/home.html', {
        'years': range((this_year-1), (this_year+4)), 'view_year': view_year,
        'tradeshows': li, 'ts_total': ts_total,
        'canonical': reverse('tradeshowdb_by_year', args=[view_year]),
        'tpl_search_form': 'tradeshows'})
예제 #21
0
def usermap_view(request, template_name="dtr5app/usermap.html"):
    if request.is_ajax():
        west = request.GET.get("west", None)
        south = request.GET.get("south", None)
        east = request.GET.get("east", None)
        north = request.GET.get("north", None)
        t = force_int(request.GET.get("t", 0))

        if settings.DEBUG:
            print(west, north, east, south, t)

        users = User.objects.exclude(
            profile__lat__gte=-0.1,
            profile__lng__gte=-0.1,
            profile__lat__lte=1.1,
            profile__lng__lte=1.1,
        ).filter(
            profile__lat__gte=south,
            profile__lng__gte=west,
            profile__lat__lte=north,
            profile__lng__lte=east,
            is_active=True,
            last_login__isnull=False,
        )

        if t > 0:
            tmin = datetime.now().replace(tzinfo=pytz.utc) - timedelta(minutes=t)
            users = users.filter(profile__accessed__gte=tmin)

        users = [
            [u.username, u.profile.lat, u.profile.lng]
            for u in users.prefetch_related("profile")[:250]
        ]

        return JsonResponse({"users": users})

    return render(request, template_name)
예제 #22
0
파일: views.py 프로젝트: C14L/gl4
def filter(request, color, country, texture, classif, p=1):
    """Return a list of stones for a specific color+type+origin.

    Exampe: /stone/sandstone/blue/veined/france/
    :param request:
    :param color:
    :param country:
    :param texture:
    :param classif:
    :param p:
    """
    __t = [time.time()]
    if p == '1':
        # Don't show page 1 number in URL.
        # Example: /stone/sandstone/blue/veined/france/1
        return HttpResponsePermanentRedirect(request.path[:-2])

    p = force_int(p) or 1
    url = ''
    color = _filter_cleanup_val(color)
    country = _filter_cleanup_val(country)
    texture = _filter_cleanup_val(texture)
    classif = _filter_cleanup_val(classif)
    __t.append(time.time())
    # Now redirect depending on what values we received.
    if not (color or country or texture or classif):
        # no vals at all is not possible, go to redir_search page.
        url = reverse('stonedb_home')
    elif color and not (country or texture or classif):
        # only color, go to old color page
        url = reverse('stonedb_simple_filter',
                      kwargs={'f': settings.TR_COLOR, 'q': color.slug})
    elif country and not (color or texture or classif):
        # only country, go to old country page.
        url = reverse('stonedb_simple_filter',
                      kwargs={'f': settings.TR_COUNTRY, 'q': country.slug})
    elif texture and not (color or country or classif):
        # only texture, there is NO old texture page, so that's okay.
        pass
    elif classif and not (color or country or texture):
        # only classification, go to old "type" page.
        url = reverse('stonedb_simple_filter',
                      kwargs={'f': 'classif', 'q': classif.slug})
    if url:
        return HttpResponsePermanentRedirect(url)
    __t.append(time.time())

    # Still here? Then display the filtered results.
    stones_qs = Stone.objects.all().prefetch_related(
        'color', 'classification', 'country', 'texture', 'pseu')

    if color:
        color = get_object_or_404(Color, slug=color)
        stones_qs = stones_qs.filter(color=color)
    if country:
        country = get_object_or_404(Country, slug=country)
        stones_qs = stones_qs.filter(country=country)
    if texture:
        texture = get_object_or_404(Texture, slug=texture)
        stones_qs = stones_qs.filter(texture=texture)
    if classif:
        classif = get_object_or_404(Classification, slug=classif)
        stones_qs = stones_qs.filter(classification=classif)
    __t.append(time.time())

    # Canonical is the URI with NO page number
    stones = _get_page(stones_qs, p, 60)
    canonical = reverse('stonedb_filter', args=[
                        country and country.slug or 'all',
                        texture and texture.slug or 'all',
                        color and color.slug or 'all',
                        classif and classif.slug or 'all'])
    __t.append(time.time())

    titlestone = '/stonesbrowse/{}.jpg'.format('-'.join([x for x in [
        country and country.slug, texture and texture.slug,
        color and color.slug, classif and classif.slug] if x]))

    ret = render(request, 'stonedb/filter.html', _ctx({
        'range_pages': range(1, stones.paginator.num_pages + 1),
        'canonical': canonical,
        'titlestone': titlestone,
        'stones': stones,
        'classification': classif,
        'color': color,
        'country': country,
        'texture': texture,
        'selected_classification': getattr(classif, 'id', ''),
        'selected_color': getattr(color, 'id', ''),
        'selected_country': getattr(country, 'id', ''),
        'selected_texture': getattr(texture, 'id', '')}))
    __t.append(time.time())

    __diff = [__t[i] - __t[i - 1] for i in range(1, len(__t))]

    if 'timer' in request.GET:
        x = [str(int(x * 100) / 100) for x in __diff]
        return HttpResponse(' # '.join(x))
    else:
        return ret
예제 #23
0
파일: utils_search.py 프로젝트: C14L/dtr5
def update_search_settings(request):
    """Update all posted search uptions in authuser's Profile."""
    p = request.user.profile

    if 'order_by' in request.POST:
        request.session['search_results_order'] = request.POST['order_by']

    if 'f_sex' in request.POST:
        p.f_sex = force_int(request.POST['f_sex'])

    if 'f_distance' in request.POST:
        p.f_distance = force_int(request.POST['f_distance'], min=0, max=21000)

    if 'f_minage' in request.POST:
        p.f_minage = force_int(request.POST['f_minage'], min=18, max=99)

    if 'f_maxage' in request.POST:
        p.f_maxage = force_int(request.POST['f_maxage'], min=19, max=100)

    if 'f_hide_no_pic' in request.POST:
        j = force_int(request.POST['f_hide_no_pic'])
        p.f_hide_no_pic = bool(j)

    if 'f_has_verified_email' in request.POST:
        j = force_int(request.POST['f_has_verified_email'])
        p.f_has_verified_email = bool(j)

    # TODO: needs Profile model update!
    # if 'f_is_stable' in request.POST:
    #     j = force_int(request.POST['f_is_stable'])
    #     p.f_is_stable = bool(j)

    if 'f_over_18' in request.POST:  # unused
        p.f_over_18 = bool(request.POST['f_over_18'])

    # List of subreddit names. This needs to be cleaned for appropriate
    # letter case, so its useful in raw SQL search. Since Django has no
    # case insensivity support :( we look up the correctly cased subreddit
    # names here once, and store those as the user's search settings.
    # --> REMOVE from search, use "fav subreddits" list instead.
    if 'f_ignore_sr_li' in request.POST:
        try:
            li = sr_str_to_list(request.POST['f_ignore_sr_li'])
            p.f_ignore_sr_li = normalize_sr_names(li)
        except MultiValueDictKeyError:
            pass  # don't change the search value if not POSTed.

    # --> REMOVE from search, use "fav subreddits" list instead.
    if 'f_ignore_sr_max' in request.POST:
        try:
            p.f_ignore_sr_max = force_int(request.POST['f_ignore_sr_max'],
                                          min=100,
                                          max=123456789)
        except MultiValueDictKeyError:
            pass  # don't change the search vaue if not POSTed.

    # Currently unused.
    if 'f_exclude_sr_li' in request.POST:
        try:
            li = sr_str_to_list(request.POST['f_exclude_sr_li'])
            p.f_exclude_sr_li = normalize_sr_names(li)
        except MultiValueDictKeyError:
            pass  # don't change the search value if not POSTed.

    # Find active subreddits: loop through user's subs and those that are in
    # the POST are active, all others are not.
    if 'sr-fav' in request.POST:
        posted = request.POST.getlist('sr-fav')
        li = request.user.subs.filter(sr__display_name__in=posted)
        if li:  # ignore empty fav list!
            with transaction.atomic():
                request.user.subs.all().update(is_favorite=False)
                li.update(is_favorite=True)
        else:
            messages.warning(request, 'no subreddits selected for search!')

    request.user.profile = p
    request.user.profile.save()
    return request
예제 #24
0
    def import_pics(self):
        """
        {"id":"1","user_id":"4","module":"profile","module_id":"4","folder":"0","time":"2005-06-12 08:48:06","ip":"0.0.0.0","size":"26860","width":"397","height":"297","ext":"jpg","title":"","caption":"","is_blocked":"0","is_deleted":"0","is_sticky":"0","is_comments":"0","is_approved":"1","is_title":"0"},

        companydb.modules.Pic.MODULE_CHOICES = (
            ('profile', 'Profile'), ('projects', 'Projects'),
            ('stones', 'Stones'), ('stock', 'Stock'), ('groups', 'Groups'),
            ('pages', 'Pages'))

        {'groups': 17, 'stock': 11754, 'stones': 2450,
         'projects': 1770, 'pages': 29, 'profile': 11006}
        """
        """
        print('Count pic modules:')
        m = dict()
        for row in self.walkjsondata('fotos'):
            if row['module'] in m.keys():
                m[row['module']] += 1
            else:
                m[row['module']] = 0
        print('done counting:')
        print(m)
        input('Press ENTER to continue with pics import...')
        """
        print('Import pics', end='', flush=True)
        Pic.objects.all().delete()
        i = 0
        for row in self.walkjsondata('fotos'):
            try:
                user = User.objects.get(pk=row['user_id'])
            except User.DoesNotExist:
                print('U', end='', flush=True)
                continue
            pic = Pic(id=row['id'])
            pic.user = user
            # check integrity: find the object in the referenced model
            pic.module = row['module']  # related model
            pic.module_id = row['module_id']  # object id within related model

            if pic.module == 'profile':
                try:
                    User.objects.get(pk=pic.module_id)
                except UserProfile.DoesNotExist:
                    print('U', end='', flush=True)
                    continue  # user not found!
            elif pic.module == 'projects':
                try:
                    Project.objects.get(pk=pic.module_id)
                except Project.DoesNotExist:
                    print('P', end='', flush=True)
                    continue  # project item not found!
            elif pic.module == 'stock':
                try:
                    Stock.objects.get(pk=pic.module_id)
                except Stock.DoesNotExist:
                    print('K', end='', flush=True)
                    continue  # stock item not found!
            elif pic.module == 'stones':
                try:
                    Stone.objects.get(pk=pic.module_id)
                except Stone.DoesNotExist:
                    print('S', end='', flush=True)
                    continue  # stone item not found!
            elif pic.module == 'pages':
                try:
                    Article.objects.get(pk=pic.module_id)
                except Article.DoesNotExist:
                    print('A', end='', flush=True)
                    continue  # article item not found!
            elif pic.module == 'groups':
                try:
                    Group.objects.get(pk=pic.module_id)
                except Group.DoesNotExist:
                    print('G', end='', flush=True)
                    continue  # group item not found!
            else:
                continue  # not a valid module

            pic.created = parse_iso_datetime(row['time'])
            if not pic.created:  # skip if no timestamp
                continue
            pic.size = force_int(row['size'])
            pic.width = force_int(row['width'])
            pic.height = force_int(row['height'])
            pic.ext = row['ext']
            pic.title = row['title']
            pic.caption = row['caption']
            pic.is_blocked = bool(force_int(row['is_blocked']))
            pic.is_deleted = bool(force_int(row['is_deleted']))
            if pic.is_blocked or pic.is_deleted:  # skip if deleted
                continue
            pic.is_sticky = bool(force_int(row['is_sticky']))
            pic.is_comments = bool(force_int(row['is_comments']))
            pic.is_approved = bool(force_int(row['is_approved']))
            pic.is_title = bool(force_int(row['is_title']))
            pic.save()
            i += 1
            print('.', end='', flush=True)
            if (i % 1000) == 0:
                print(i, end='', flush=True)
        print('done. {} pics imported.'.format(i))
예제 #25
0
def update_search_if_changed(opts, user, session_obj=None):
    """Update all posted search uptions in authuser's Profile."""
    changed = False

    if "order_by" in opts and session_obj is not None:
        if session_obj.get("search_results_order", None) != opts["order_by"]:
            changed = True
        session_obj["search_results_order"] = opts["order_by"]

    if "f_sex" in opts:
        f_sex = force_int(opts["f_sex"])
        if user.profile.f_sex != f_sex:
            changed = True
        user.profile.f_sex = f_sex

    if "f_distance" in opts:
        f_distance = force_int(opts["f_distance"], min=0, max=21000)
        if user.profile.f_distance != f_distance:
            changed = True
        user.profile.f_distance = f_distance

    f_minage, f_maxage = None, None

    if "f_minage" in opts:
        f_minage = force_int(opts["f_minage"], min=18, max=99)
    if "f_maxage" in opts:
        f_maxage = force_int(opts["f_maxage"], min=19, max=100)
    if "f_age" in opts:
        f_minage, f_maxage = opts["f_age"].split("-", 1)
        f_minage = force_int(f_minage, min=18, max=99)
        f_maxage = force_int(f_maxage, min=19, max=100)

    if f_minage:
        if user.profile.f_minage != f_minage:
            changed = True
        user.profile.f_minage = f_minage

    if f_maxage:
        if user.profile.f_maxage != f_maxage:
            changed = True
        user.profile.f_maxage = f_maxage

    if "f_hide_no_pic" in opts:
        f_hide_no_pic = bool(force_int(opts["f_hide_no_pic"]))
        if user.profile.f_hide_no_pic != f_hide_no_pic:
            changed = True
        user.profile.f_hide_no_pic = f_hide_no_pic

    if "f_has_verified_email" in opts:
        f_has_verified_email = bool(force_int(opts["f_has_verified_email"]))
        if user.profile.f_has_verified_email != f_has_verified_email:
            changed = True
        user.profile.f_has_verified_email = f_has_verified_email

    if "f_over_18" in opts:  # unused
        f_over_18 = bool(opts["f_over_18"])
        if user.profile.f_over_18 != f_over_18:
            changed = True
        user.profile.f_over_18 = f_over_18

    if settings.DEBUG:
        print("# search_results_order == {}".format(
            session_obj["search_results_order"]))
        print("# f_sex == {}".format(user.profile.f_sex))
        print("# f_distance == {}".format(user.profile.f_distance))

    user.profile.save(update_fields=[
        "f_sex",
        "f_minage",
        "f_maxage",
        "f_hide_no_pic",
        "f_has_verified_email",
        "f_over_18",
    ])

    return changed
예제 #26
0
파일: utils_search.py 프로젝트: C14L/dtr5
def update_search_settings(request):
    """Update all posted search uptions in authuser's Profile."""
    p = request.user.profile

    if 'order_by' in request.POST:
        request.session['search_results_order'] = request.POST['order_by']

    if 'f_sex' in request.POST:
        p.f_sex = force_int(request.POST['f_sex'])

    if 'f_distance' in request.POST:
        p.f_distance = force_int(request.POST['f_distance'], min=0, max=21000)

    if 'f_minage' in request.POST:
        p.f_minage = force_int(request.POST['f_minage'], min=18, max=99)

    if 'f_maxage' in request.POST:
        p.f_maxage = force_int(request.POST['f_maxage'], min=19, max=100)

    if 'f_hide_no_pic' in request.POST:
        j = force_int(request.POST['f_hide_no_pic'])
        p.f_hide_no_pic = bool(j)

    if 'f_has_verified_email' in request.POST:
        j = force_int(request.POST['f_has_verified_email'])
        p.f_has_verified_email = bool(j)

    # TODO: needs Profile model update!
    # if 'f_is_stable' in request.POST:
    #     j = force_int(request.POST['f_is_stable'])
    #     p.f_is_stable = bool(j)

    if 'f_over_18' in request.POST:  # unused
        p.f_over_18 = bool(request.POST['f_over_18'])

    # List of subreddit names. This needs to be cleaned for appropriate
    # letter case, so its useful in raw SQL search. Since Django has no
    # case insensivity support :( we look up the correctly cased subreddit
    # names here once, and store those as the user's search settings.
    # --> REMOVE from search, use "fav subreddits" list instead.
    if 'f_ignore_sr_li' in request.POST:
        try:
            li = sr_str_to_list(request.POST['f_ignore_sr_li'])
            p.f_ignore_sr_li = normalize_sr_names(li)
        except MultiValueDictKeyError:
            pass  # don't change the search value if not POSTed.

    # --> REMOVE from search, use "fav subreddits" list instead.
    if 'f_ignore_sr_max' in request.POST:
        try:
            p.f_ignore_sr_max = force_int(request.POST['f_ignore_sr_max'],
                                          min=100, max=123456789)
        except MultiValueDictKeyError:
            pass  # don't change the search vaue if not POSTed.

    # Currently unused.
    if 'f_exclude_sr_li' in request.POST:
        try:
            li = sr_str_to_list(request.POST['f_exclude_sr_li'])
            p.f_exclude_sr_li = normalize_sr_names(li)
        except MultiValueDictKeyError:
            pass  # don't change the search value if not POSTed.

    # Find active subreddits: loop through user's subs and those that are in
    # the POST are active, all others are not.
    if 'sr-fav' in request.POST:
        posted = request.POST.getlist('sr-fav')
        li = request.user.subs.filter(sr__display_name__in=posted)
        if li:  # ignore empty fav list!
            with transaction.atomic():
                request.user.subs.all().update(is_favorite=False)
                li.update(is_favorite=True)
        else:
            messages.warning(request, 'no subreddits selected for search!')

    request.user.profile = p
    request.user.profile.save()
    return request
예제 #27
0
        def _create(row):
            try:
                category = [x['slug'] for x in settings.ANUNCIOS['CATEGORIES']
                            if x['parent'] and x['old'] == row['subt']][0]
            except IndexError:
                print('Skip because: no category')
                return False

            # Try to find the attached user in the user id map.
            user = None
            try:
                new_user_id = [x[1] for x in self.user_tr
                               if str(x[0]) == str(row['user_id'])][0]
                user = User.objects.get(pk=new_user_id)
            except IndexError:
                pass
            except User.DoesNotExist:
                pass

            row['email'] = row['email'].strip().lower()

            if not user:
                # If not found by id, try to find user by email
                try:
                    user = User.objects.get(email=row['email'])
                except User.DoesNotExist:
                    pass

            post, created = Post.objects.get_or_create(pk=row['id'])
            if not created:
                print('Skip because: already exists pk='+row['id'])
                return True  # already previously imported


            post.user = user
            post.pin = row['passwd'][:5]
            post.title = row['title'][:200]
            post.text = row['text'] or ''
            post.category = category
            post.city_name = row['ciudad']
            post.region_name = row['estado']
            post.country_name = row['pais']

            try:
                t = parse(row['time']).replace(microsecond=0).replace(tzinfo=utc)
            except AttributeError:
                t = None
            except ValueError:
                t = None
            post.created, post.updated, post.publish = t, t, t

            post.count_views = force_int(row['count_views'], 0, 0)
            post.expires_days = force_int(row['valid_for'], 90, 30, 365)
            post.created_ip = (row['ip'] or '')[:30]
            post.updated_ip = (row['ip'] or '')[:30]

            post.is_nsfw = (row['is_adult'] == '1')
            post.is_public = (row['is_published'] == '1')
            post.is_delete = (row['is_blocked'] == '1' or
                              row['is_deleted'] == '1')
            post.save()
            return True
예제 #28
0
def me_search_view(request):
    """
    Save the user search settings and redirect to search results page.
    """
    txt_not_found = 'No redditors found for the search options.'

    if request.method in ["GET", "HEAD"]:
        # Find the next profile to show and redirect.
        search_results_buffer(request)

        if len(request.session['search_results_buffer']) < 1:
            messages.warning(request, txt_not_found)
            return redirect(request.POST.get('next', reverse('me_page')))

        x = {'username': request.session['search_results_buffer'][0]}
        _next = request.POST.get('next', reverse('profile_page', kwargs=x))

        return redirect(_next)

    p = request.user.profile
    p.f_sex = force_int(request.POST.get('f_sex', ''))

    if request.POST.get('f_distance', None):
        p.f_distance = force_int(request.POST.get('f_distance'), max=21000)
    if request.POST.get('f_minage', None):
        p.f_minage = force_int(request.POST.get('f_minage'), min=18)
    if request.POST.get('f_maxage', None):
        p.f_maxage = force_int(request.POST.get('f_maxage'), max=100)
    if request.POST.get('f_over_18', None):
        p.f_over_18 = bool(request.POST.get('f_over_18'))
    if request.POST.get('f_has_verified_email', None):
        p.f_has_verified_email = bool(request.POST.get('f_has_verified_email'))

    # List of subreddit names. This needs to be cleaned for appropriate
    # letter case, so its useful in raw SQL search. Since Django has no
    # case insensivity support :( we look up the correctly cased subreddit
    # names here once, and store those as the user's search settings.
    try:
        li = sr_str_to_list(request.POST['f_ignore_sr_li'])
        p.f_ignore_sr_li = normalize_sr_names(li)
    except MultiValueDictKeyError:
        pass  # don't change the search vaue if not POSTed.
    try:
        p.f_ignore_sr_max = force_int(request.POST['f_ignore_sr_max'])
    except MultiValueDictKeyError:
        pass  # don't change the search vaue if not POSTed.
    try:
        li = sr_str_to_list(request.POST['f_exclude_sr_li'])
        p.f_exclude_sr_li = normalize_sr_names(li)
    except MultiValueDictKeyError:
        pass  # don't change the search vaue if not POSTed.

    request.user.profile = p
    #
    # TODO: check if model is dirty and only force a search results
    # buffer refresh if the search parameters actually changed. To
    # avoid too many searches.
    #
    request.user.profile.save()
    search_results_buffer(request, force=True)

    if len(request.session['search_results_buffer']) < 1:
        messages.warning(request, txt_not_found)
        return redirect(request.POST.get('next', reverse('me_page')))

    # messages.success(request, 'Search options updated.')
    if (request.session.get('view_post_signup', False)):
        return redirect(request.POST.get('next', reverse('me_page')))
    else:
        # x = {'username': request.session['search_results_buffer'][0]}
        # return redirect(reverse('profile_page', kwargs=x))
        return redirect(reverse('me_results_page'))
예제 #29
0
파일: views.py 프로젝트: M108/dtr5
def me_search_view(request):
    """
    Save the user search settings and redirect to search results page.
    """
    txt_not_found = 'No redditors found for the search options.'

    if request.method in ["GET", "HEAD"]:
        # Find the next profile to show and redirect.
        search_results_buffer(request)
        if len(request.session['search_results_buffer']) < 1:
            messages.warning(request, txt_not_found)
            return redirect(request.POST.get('next', reverse('me_page')))
        x = {'username': request.session['search_results_buffer'][0]}
        _next = request.POST.get('next', reverse('profile_page', kwargs=x))
        return redirect(_next)

    p = request.user.profile
    p.f_sex = force_int(request.POST.get('f_sex', ''))

    if request.POST.get('f_distance', None):
        p.f_distance = force_int(request.POST.get('f_distance'), max=20000)
    if request.POST.get('f_minage', None):
        p.f_minage = force_int(request.POST.get('f_minage'), min=18)
    if request.POST.get('f_maxage', None):
        p.f_maxage = force_int(request.POST.get('f_maxage'), max=100)
    if request.POST.get('f_over_18', None):
        p.f_over_18 = bool(request.POST.get('f_over_18'))
    if request.POST.get('f_has_verified_email', None):
        p.f_has_verified_email = bool(request.POST.get('f_has_verified_email'))

    try:
        p.f_ignore_sr_li = sr_str_to_list(request.POST['f_ignore_sr_li'])
    except MultiValueDictKeyError:
        pass  # don't change the search vaue if not POSTed.
    try:
        p.f_ignore_sr_max = force_int(request.POST['f_ignore_sr_max'])
    except MultiValueDictKeyError:
        pass  # don't change the search vaue if not POSTed.
    try:
        p.f_exclude_sr_li = sr_str_to_list(request.POST['f_exclude_sr_li'])
    except MultiValueDictKeyError:
        pass  # don't change the search vaue if not POSTed.

    request.user.profile = p
    #
    # TODO: check if model is dirty and only force a search results
    # buffer refresh if the search parameters actually changed. To
    # avoid too many searches.
    #
    request.user.profile.save()
    search_results_buffer(request, force=True)
    #
    if len(request.session['search_results_buffer']) < 1:
        messages.warning(request, txt_not_found)
        return redirect(request.POST.get('next', reverse('me_page')))
    # messages.success(request, 'Search options updated.')
    if (request.session.get('view_post_signup', False)):
        return redirect(request.POST.get('next', reverse('me_page')))
    else:
        x = {'username': request.session['search_results_buffer'][0]}
        return redirect(reverse('profile_page', kwargs=x))
예제 #30
0
def me_update_view(request):
    """
    Update the user profile with fresh data from user's Reddit account,
    then simply redirect to user's "me" page and add message to confirm
    the success or report failure.
    """
    # Reload user's subreddit list from reddit.
    subscribed = api.get_sr_subscriber(request, settings.SR_FETCH_LIMIT)
    if subscribed:
        update_list_of_subscribed_subreddits(request.user, subscribed)

        if len(subscribed) > settings.USER_MIN_SUBSCRIBED_SUBREDDITS:
            pass
            # messages.success(request, 'Subreddit list updated with {} items.'
            #                  .format(len(subscribed)))
        else:
            messages.success(
                request,
                "Subreddit list updated, but you are "
                "only subscribed to {} subreddits. Find some "
                "more that interest you for better results "
                "here :)".format(len(subscribed)),
            )
    else:
        messages.warning(
            request,
            "Could not find any subscribed subreddits. "
            "Most likely, because you are still only subscribed "
            "to the default subs and have not yet picked your "
            "own selection.",
        )

    # Reload user profile data from Reddit.
    reddit_user = api.get_user(request)
    if settings.DEBUG:
        print("--> reddit_user: "******"created_utc"]

        p = request.user.profile
        p.name = reddit_user["name"]
        p.created = datetime.utcfromtimestamp(t).replace(tzinfo=pytz.utc)
        p.updated = datetime.now().replace(tzinfo=pytz.utc)
        p.link_karma = force_int(reddit_user["link_karma"])
        p.comment_karma = force_int(reddit_user["comment_karma"])
        p.over_18 = bool(reddit_user["over_18"])
        p.hide_from_robots = bool(reddit_user["hide_from_robots"])
        p.has_verified_email = bool(reddit_user["has_verified_email"])
        p.gold_creddits = bool(reddit_user["gold_creddits"])
        p.save()
        # messages.success(request, 'Profile data updated.')
    else:
        messages.warning(request, "Could not find any user profile data.")

    # Go back to user's "me" page, the updated data should show up there.
    if request.is_ajax():
        return HttpResponse()  # HTTP 200

    return redirect(reverse("me_page") + "#id_srlist")