Beispiel #1
0
    def test_magicfiles_resource(self):
        # Set up some more files.
        testfile = Sharedfile.get("id = %s", 1)

        response = self.upload_file(file_path=self.test_file1_path, sha1=self.test_file1_sha1,
            content_type=self.test_file1_content_type, user_id=1, sid=self.sid, xsrf=self.xsrf)
        testfile_2 = Sharedfile.get("id = %s", 2)
        testfile_2.name = "test file 2"
        testfile_2.save()

        testfile_in_user2_shake = testfile_2.save_to_shake(self.user_b)
        testfile_in_another_group = testfile_2.save_to_shake(self.user_a, self.group_shake_2)

        sid_b = self.sign_in('user2', 'asdfasdf')
        xsrf_b = self.get_xsrf()
        response = self.upload_file(file_path=self.test_file1_path, sha1=self.test_file1_sha1,
            content_type=self.test_file1_content_type, user_id=2, sid=sid_b, xsrf=xsrf_b,
            shake_id=self.group_shake.id)
        testfile_3 = Sharedfile.get("id = %s", 5)
        testfile_3.name = "test file 5"
        testfile_3.save()

        with test_option('likes_to_magic', 5):
            # Set up their favorites.
            for sf, likes in zip((testfile, testfile_2, testfile_in_user2_shake, testfile_3), (0, 7, 3, 5)):
                for i in range(likes):
                    f = Favorite()
                    f.user_id = i
                    f.sharedfile_id = sf.id
                    f.save()
                    calculate_likes(sf.id)

        # What's best?
        request = signed_request(self.access_token, self.get_url('/api/magicfiles'), 'GET')
        self.http_client.fetch(request, self.stop)
        response = self.wait()
        j_response = json_decode(response.body)

        magicfiles = j_response['magicfiles']
        pivot_ids = [sf['pivot_id'] for sf in magicfiles]
        share_keys = [sf['sharekey'] for sf in magicfiles]
        self.assertEqual(share_keys, ['5', '2'])
        self.assertEqual(pivot_ids, ['2', '1'])

        # Pagination check.
        request = signed_request(self.access_token, self.get_url('/api/magicfiles/before/2'), 'GET')
        self.http_client.fetch(request, self.stop)
        response = self.wait()
        j_response = json_decode(response.body)
        self.assertEqual('1', j_response['magicfiles'][0]['pivot_id'])

        request = signed_request(self.access_token, self.get_url('/api/magicfiles/after/1'), 'GET')
        self.http_client.fetch(request, self.stop)
        response = self.wait()
        j_response = json_decode(response.body)
        self.assertEqual('2', j_response['magicfiles'][0]['pivot_id'])
Beispiel #2
0
def post_favorite():
    if not request.json or not 'user_id' in request.json or not 'article_id' in request.json:
        abort(400)
    user_id = request.json['user_id']
    article_id = request.json['article_id']
    from models import Favorite
    obj = Favorite.objects(user_id=user_id)
    if obj:
        favorite = obj.get()
    else:
        favorite = Favorite(user_id=user_id)
    favorite.article_list.append(article_id)
    favorite.article_list.sort(reverse=True)
    favorite.save()
    return jsonify({"response_msg": "success", "response_code": 201}), 201
Beispiel #3
0
    def test_query_favorites(self):
        # Set up a favorite.
        f = Favorite()
        f.user_id = self.user_b.id
        f.sharedfile_id = 1
        f.save()

        request = signed_request(self.access_token, self.get_url('/api/favorites'))
        self.http_client.fetch(request, self.stop)
        response = self.wait()
        j_response = json_decode(response.body)

        self.assertTrue('favorites' in j_response)
        favs = j_response['favorites']
        fav_ids = (fav['permalink_page'].rsplit('/', 1)[-1] for fav in favs)
        self.assertEqual(list(fav_ids), ['1'])
Beispiel #4
0
def favorites(user_id=None):
    if request.method == 'GET':
        if user_id is not None:
            users = User.query.all()
            if user_id > len(users):
                return jsonify({ "fail": "user does not exist" }), 404
            user = User.query.get(user_id)
            if not user.favorites:
                return jsonify({ "fail": "user does not have favorites" }), 404
            
            return jsonify({
                "success": "Favorites found",
                "favorites": user.favorites.serialize()
                }),200
        else:
            users= User.query.all()
            users = list(
                map(lambda user_favs: user.serialize(), users)
            )

    if request.method == 'POST':
      
        id_vehicle = request.json.get('id_vehicle',)
        id_character = request.json.get('id_character')
        id_planet = request.json.get('id_planet')

        user = User.query.filter_by(id = user_id).first()
        if not user:
            return jsonify({"fail": "the indicated user does not exist"})
            
        vehicle = Vehicle.query.filter_by(id= id_vehicle).first()
        character = Character.query.filter_by(id=id_character).first()
        planet = Planet.query.filter_by(id=id_planet).first()

        favorite = Favorite()
        user.favorites = favorite
        favorite.vehicles.append(vehicle)
        favorite.characters.append(character)
        favorite.planets.append(planet)

        favorite.save()
        user.update()

        return jsonify({
            "success": "favorites added",
            "favorites": favorite.serialize()
        })
Beispiel #5
0
def favorite_applicant(request, event_name, name):
  try:
    applicant = Applicant.objects.get(norm_name=normalize_name(name), event__name=event_name)
  except Applicant.DoesNotExist:
    raise Http404('Applicant does not exist.')
  if request.method == 'POST':
    try:
      fav = Favorite.objects.get(applicant=applicant, scholar=request.user.mcuser)
      fav.delete()
      return JsonResponse({'msg': 'unstarred'})
    except Favorite.DoesNotExist:
      favs = Favorite.objects.filter(scholar=request.user.mcuser, applicant__event__name=event_name)
      if favs.count() < 5:
        fav = Favorite(applicant=applicant, scholar=request.user.mcuser)
        fav.save()
        return JsonResponse({'msg': 'starred'})
      return JsonResponse({'msg': 'max stars given'})
  return HttpResponse('Please POST')
Beispiel #6
0
def favorite_action(request,vidnum):
	try:
		venue = Venue.objects.get(id=vidnum)
		old_favorite = get_or_none(Favorite,venue=venue, user=request.user)
		status = 0
		if old_favorite:
			old_favorite.delete()
			status = 0
		else:
			fav = Favorite()
			fav.user = request.user
			fav.venue = venue
			fav.save()
			status = 1
		return HttpResponse(json.dumps({"is_fav": status}) ,content_type="applcation/json")
	except Exception, e:
		print e
		res = HttpResponse()
		res.status_code = 404
		return res
Beispiel #7
0
def favorite_applicant(request, event_name, name):
    try:
        applicant = Applicant.objects.get(norm_name=normalize_name(name),
                                          event__name=event_name)
    except Applicant.DoesNotExist:
        raise Http404('Applicant does not exist.')
    if request.method == 'POST':
        try:
            fav = Favorite.objects.get(applicant=applicant,
                                       scholar=request.user.mcuser)
            fav.delete()
            return JsonResponse({'msg': 'unstarred'})
        except Favorite.DoesNotExist:
            favs = Favorite.objects.filter(scholar=request.user.mcuser,
                                           applicant__event__name=event_name)
            if favs.count() < 5:
                fav = Favorite(applicant=applicant,
                               scholar=request.user.mcuser)
                fav.save()
                return JsonResponse({'msg': 'starred'})
            return JsonResponse({'msg': 'max stars given'})
    return HttpResponse('Please POST')
def add_custom(bot, update, username):
    uid = util.uid_from_update(update)
    user = User.from_update(update)
    mid = util.mid_from_update(update)
    from components.basic import main_menu_buttons
    main_menu_markup = ReplyKeyboardMarkup(main_menu_buttons(uid in settings.MODERATORS))

    try:
        fav = Favorite.get(custom_bot=username)
        util.send_or_edit_md_message(
            bot, uid, mdformat.none_action(
                "{} is already a favorite of yours. /favorites".format(fav.custom_bot)),
            to_edit=mid,
            reply_markup=main_menu_markup)
    except Favorite.DoesNotExist:
        fav = Favorite(user=user, custom_bot=username, date_added=datetime.date.today())
        fav.save()
        msg = bot.formatter.send_or_edit(uid,
                                           mdformat.love("{} added to your /favorites.".format(fav.custom_bot)),
                                           to_edit=mid)
        mid = msg.message_id
        util.wait(bot, update)
        send_favorites_list(bot, update, to_edit=mid)
    return ConversationHandler.END
Beispiel #9
0
def favorites(request):
    """
    Method which handles favorites request
    """
    if request.GET:
        g = request.GET
        action = g.get('a', None)
        fromS = g.get('fromS', None)
        viaS = g.get('viaS', None)
        ftype = g.get('type', DEPARTURES)
        
        # Check if we are trying to delete an existing favorite
        if action == 'd':
            id = g.get('id', None)
            if not id:
                return _redirect_home_with_msg(request, "ID missing. Cannot delete favorite.")
            try:
                fav = Favorite.objects.get(id=id, user=request.user)
                fav.delete()
                return _redirect_home_with_msg(request, "Favorite removed successfully.")
            except Favorite.DoesNotExist:
                return _redirect_home_with_msg(request, "Invalid favorite id.")
        
        if not fromS:
            return _redirect_home_with_msg(request, "location missing. cannot save favorite!")
        
        crslist = _getCRS(fromS)
        filterCrslist = _getCRS(viaS)
        if not crslist:
            return _redirect_home_with_msg(request, "Invalid station name")
        if len(crslist) > 1 or (filterCrslist and len(filterCrslist) > 1):
            return _redirect_home_with_msg(request, "Multiple station names retrieved.")
        
        fsn, crs = crslist[0]
        vsn = filterCrs = None
        if filterCrslist:
            vsn, filterCrs = filterCrslist[0]
        
        # Construct a good favorite name
        fname = fsn + ' ' + ftype
        desc = ''
        if vsn:
            desc = 'Via ' + vsn
        
        # See if the user is logged in.
        loggedIn = _checkLoggedIn(request)
        return render_to_response('fav.html', {'fname' : fname,
                                'fromS' : fromS,
                                'viaS' : viaS,
                                'ftype' : ftype,
                                'desc' : desc,
                                'loggedIn' : loggedIn,
                                },
                                context_instance=RequestContext(request))
    
    if request.POST:
        p = request.POST
        fromS = p.get('fromS', None)
        viaS = p.get('viaS', None)
        ftype = p.get('type', 'Departures')
        fname = p.get('fname', None)
        desc = p.get('desc', '')
        if not fname or not fromS:
            return _redirect_home_with_msg(request, "Missing values. Favorite not saved.")
        
        # Retrieve or create the user.
        username = p.get('username', None)
        password = p.get('password', None)
        loggedIn = _checkLoggedIn(request)
        
        if not loggedIn:
            if not username or not password or username.strip() == '' or password.strip() == '':
                return _redirect_home_with_msg(request, "Cannot save favorite without registering.")
        
        user = None
        if getattr(request, 'user'):
            user = request.user
        if not user or user.is_anonymous():
            try:
                user = User.objects.get(username=username, password=password)
            except User.DoesNotExist:
                # Create the user and login
                user = create_user(request, username, password)
                user = authenticate(username=username, password=password)
                login(request, user)
        
        # Go ahead and save the favorite
        fav = Favorite(user=user, fname=fname, desc=desc,
                       ftype=ftype, fromS=fromS, viaS=viaS)
        fav.save()
        return _redirect_home_with_msg(request, "Favorite saved.")