Exemplo n.º 1
0
    def test_liking_image(self):
        """
        admin creates a sharedfile.  Joe (authenticated) likes it.
        
        Response should be successful and include following fields:
        
            {
             'response' : 'ok',
             'count' : 1,
             'share_key', 1
            }
        
        A new entry should be present in favorites table.  like_count on the sharedfile
        should be incremented.
        """
        sharedfile = self._create_sharedfile(self.admin)
        self.sign_in('joe', 'asdfasdf')
        favorite = Favorite.get('user_id = %s and sharedfile_id = %s' %
                                (self.joe.id, sharedfile.id))
        self.assertEqual(None, favorite)
        self.assertEqual(0, sharedfile.like_count)

        response = self.post_url('/p/%s/like?json=1' % sharedfile.share_key)
        json_response = json.loads(response.body)
        self.assertEqual(json_response['response'], 'ok')
        self.assertEqual(json_response['count'], 1)
        self.assertEqual(json_response['share_key'], sharedfile.share_key)
        favorite = Favorite.get('user_id = %s and sharedfile_id = %s' %
                                (self.joe.id, sharedfile.id))
        self.assertTrue(favorite)
        sharedfile_fetched = Sharedfile.get("id = %s", sharedfile.id)
        self.assertEqual(1, sharedfile_fetched.like_count)
Exemplo n.º 2
0
    def test_unliking_image(self):
        """
        admin creates a sharedfile. Joe likes it. Then, joe decides to unlike it.

        Unliking an already liked image, should result in following response:

            {
             'response' : 'ok',
             'count' : 0,
             'share_key', 1
            }

        An entry should still be present in Favorites table, with deleted = 1.
        Like count should be reset on the sharedfile.
        """
        sharedfile = self._create_sharedfile(self.admin)
        self.joe.add_favorite(sharedfile)
        sharedfile_fetched = Sharedfile.get("id = %s", sharedfile.id)
        self.assertEqual(1, sharedfile_fetched.like_count)

        self.sign_in('joe', 'asdfasdf')
        response = self.post_url('/p/%s/unlike?json=1' % sharedfile.share_key)
        json_response = json.loads(response.body)
        self.assertEqual(json_response['response'], 'ok')
        self.assertEqual(json_response['count'], 0)
        self.assertEqual(json_response['share_key'], sharedfile.share_key)

        favorite = Favorite.get('user_id= %s and sharedfile_id = 1' %
                                self.joe.id)
        self.assertTrue(favorite)
        self.assertTrue(favorite.deleted)
        sharedfile_fetched = Sharedfile.get("id = %s", sharedfile.id)
        self.assertEqual(0, sharedfile_fetched.like_count)
Exemplo n.º 3
0
    def delete(self, favorite_id):
        user = auth.current_user
        try:
            favorite = Favorite.get(Favorite.uuid == favorite_id)
        except Favorite.DoesNotExist:
            return {"message": "Favorite {} doesn't exist.".format(favorite_id)}, NOT_FOUND

        if favorite.user != auth.current_user:
            return {'message': 'Favorite `{}` not found'.format(favorite_id)}, NOT_FOUND

        user.delete_favorite(favorite)

        return {'message': 'Favorite `{}` deleted.'.format(favorite_id)}, OK
Exemplo n.º 4
0
    def test_cannot_like_own(self):
        """
        Liking own image should return a 200 response with an 'error' as one
        of the response keys.
        """
        sharedfile = self._create_sharedfile(self.admin)
        self.sign_in('admin', 'asdfasdf')
        response = self.post_url('/p/%s/like?json=1' % sharedfile.share_key)
        json_response = json.loads(response.body)

        self.assertEqual(response.code, 200)
        self.assertTrue(json_response.has_key('error'))
        favorite = Favorite.get('user_id= %s and sharedfile_id = %s',
                                self.admin.id, sharedfile.id)
        self.assertFalse(favorite)
Exemplo n.º 5
0
    def test_add_favorite(self):
        """
        A user should be able to favorite a sharedfile if:
         - it belongs to another user
         - it's not already favorited
         - if it's been favorited, but favorite was "deleted"

        A user shouldn't be able to favorite a sharedfile if they own it.
        """
        # Create new user with their own sharedfile.
        new_user = User(name='newuser',email='*****@*****.**', \
            verify_email_token = 'created', password='******', email_confirmed=1, is_paid=1)
        new_user.save()
        new_sharedfile = Sharedfile(source_id=self.sourcefile.id, name="my shared file", \
            user_id=new_user.id, content_type="image/png", share_key="ok")
        new_sharedfile.save()

        # One should be able to favorite another user's sharedfile
        self.assertTrue(self.user.add_favorite(new_sharedfile))
        favorites = Favorite.all("where user_id = %s and sharedfile_id = %s and deleted = 0", \
            self.user.id, new_sharedfile.id)
        self.assertEqual(1, len(favorites))

        # Can't favorite an already favorited sharedfile.
        self.assertFalse(self.user.add_favorite(new_sharedfile))
        favorites = Favorite.all("where user_id = %s and sharedfile_id = %s and deleted = 0", \
            self.user.id, new_sharedfile.id)
        self.assertEqual(1, len(favorites))

        # A favorite with "deleted" flag set, should have flag unset and
        # return True when add_favorite called
        favorite = Favorite.get("user_id = %s and sharedfile_id = %s and deleted = 0", \
            self.user.id, new_sharedfile.id)
        favorite.deleted = True
        favorite.save()
        self.assertTrue(self.user.add_favorite(new_sharedfile))
        favorites = Favorite.all("where user_id = %s and sharedfile_id = %s and deleted = 0", \
            self.user.id, new_sharedfile.id)
        self.assertEqual(1, len(favorites))

        # Can't favorite one's own sharedfile.
        self.assertTrue(self.sharedfile.user_id, self.user.id)
        self.assertFalse(self.user.add_favorite(self.sharedfile))
        favorites = Favorite.all("where user_id = %s and sharedfile_id = %s and deleted = 0", \
            self.user.id, self.sharedfile.id)
        self.assertEqual(0, len(favorites))
Exemplo n.º 6
0
    def test_has_favorite(self):
        """
        User.has_favorite should return True if a user has favorited a file.  Should return
        False if no entry exists, or if entry is marked as "deleted"
        """
        # Create new user with their own sharedfile.
        new_user = User(name='newuser',email='*****@*****.**', \
            verify_email_token = 'created', password='******', email_confirmed=1, is_paid=1)
        new_user.save()
        new_sharedfile = Sharedfile(source_id=self.sourcefile.id, name="my shared file", \
            user_id=new_user.id, content_type="image/png", share_key="ok")
        new_sharedfile.save()

        self.assertFalse(self.user.has_favorite(new_sharedfile))
        self.user.add_favorite(new_sharedfile)
        self.assertTrue(self.user.has_favorite(new_sharedfile))

        favorite = Favorite.get("user_id = %s and sharedfile_id = %s and deleted = 0", \
            self.user.id, new_sharedfile.id)
        favorite.deleted = True
        favorite.save()
        self.assertFalse(self.user.has_favorite(new_sharedfile))
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
Exemplo n.º 8
0
def callback_router(bot, update, chat_data, user_data, job_queue):
    obj = json.loads(str(update.callback_query.data))
    user = User.from_update(update)

    try:
        if "a" in obj:
            action = obj["a"]

            # BOTLISTCHAT
            if action == CallbackActions.DELETE_CONVERSATION:
                botlistchat.delete_conversation(bot, update, chat_data)
            # HELP
            elif action == CallbackActions.HELP:
                help.help(bot, update)
            elif action == CallbackActions.CONTRIBUTING:
                help.contributing(bot, update)
            elif action == CallbackActions.EXAMPLES:
                help.examples(bot, update)
            # BASIC QUERYING
            elif action == CallbackActions.SELECT_CATEGORY:
                select_category(bot, update, chat_data)
            elif action == CallbackActions.SELECT_BOT_FROM_CATEGORY:
                category = Category.get(id=obj["id"])
                send_category(bot, update, chat_data, category)
            elif action == CallbackActions.SEND_BOT_DETAILS:
                item = Bot.get(id=obj["id"])
                send_bot_details(bot, update, chat_data, item)
            # FAVORITES
            elif action == CallbackActions.TOGGLE_FAVORITES_LAYOUT:
                value = obj["v"]
                favorites.toggle_favorites_layout(bot, update, value)
            elif action == CallbackActions.ADD_FAVORITE:
                favorites.add_favorite_handler(bot, update)
            elif action == CallbackActions.REMOVE_FAVORITE_MENU:
                favorites.remove_favorite_menu(bot, update)
            elif action == CallbackActions.REMOVE_FAVORITE:
                to_remove = Favorite.get(id=obj["id"])
                bot_details = to_remove.bot
                to_remove.delete_instance()
                if obj.get("details"):
                    send_bot_details(bot, update, chat_data, bot_details)
                else:
                    favorites.remove_favorite_menu(bot, update)
            elif action == CallbackActions.SEND_FAVORITES_LIST:
                favorites.send_favorites_list(bot, update)
            elif action == CallbackActions.ADD_ANYWAY:
                favorites.add_custom(bot, update, obj["u"])
            elif action == CallbackActions.ADD_TO_FAVORITES:
                details = obj.get("details")
                discreet = obj.get("discreet", False) or details
                item = Bot.get(id=obj["id"])
                favorites.add_favorite(bot,
                                       update,
                                       item,
                                       callback_alert=discreet)
                if details:
                    send_bot_details(bot, update, chat_data, item)
            # ACCEPT/REJECT BOT SUBMISSIONS
            elif action == CallbackActions.APPROVE_REJECT_BOTS:
                custom_approve_list = [Bot.get(id=obj["id"])]
                admin.approve_bots(bot,
                                   update,
                                   override_list=custom_approve_list)
            elif action == CallbackActions.ACCEPT_BOT:
                to_accept = Bot.get(id=obj["id"])
                admin.edit_bot_category(bot, update, to_accept,
                                        CallbackActions.BOT_ACCEPTED)
                # Run in x minutes, giving the moderator enough time to edit bot details
                job_queue.run_once(
                    lambda b, job: botlistchat.
                    notify_group_submission_accepted(b, job, to_accept),
                    settings.BOT_ACCEPTED_IDLE_TIME * 60,
                )
            elif action == CallbackActions.RECOMMEND_MODERATOR:
                bot_in_question = Bot.get(id=obj["id"])
                admin.recommend_moderator(bot, update, bot_in_question,
                                          obj["page"])
            elif action == CallbackActions.SELECT_MODERATOR:
                bot_in_question = Bot.get(id=obj["bot_id"])
                moderator = User.get(id=obj["uid"])
                admin.share_with_moderator(bot, update, bot_in_question,
                                           moderator)
                admin.approve_bots(bot, update, obj["page"])
            elif action == CallbackActions.REJECT_BOT:
                to_reject = Bot.get(id=obj["id"])
                notification = obj.get("ntfc", True)
                admin.reject_bot_submission(
                    bot,
                    update,
                    None,
                    to_reject,
                    verbose=False,
                    notify_submittant=notification,
                )
                admin.approve_bots(bot, update, obj["page"])
            elif action == CallbackActions.BOT_ACCEPTED:
                to_accept = Bot.get(id=obj["bid"])
                category = Category.get(id=obj["cid"])
                admin.accept_bot_submission(bot, update, to_accept, category)
            elif action == CallbackActions.COUNT_THANK_YOU:
                new_count = obj.get("count", 1)
                basic.count_thank_you(bot, update, new_count)
            # ADD BOT
            # elif action == CallbackActions.ADD_BOT_SELECT_CAT:
            #     category = Category.get(id=obj['id'])
            #     admin.add_bot(bot, update, chat_data, category)
            # EDIT BOT
            elif action == CallbackActions.EDIT_BOT:
                to_edit = Bot.get(id=obj["id"])
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_SELECT_CAT:
                to_edit = Bot.get(id=obj["id"])
                admin.edit_bot_category(bot, update, to_edit)
            elif action == CallbackActions.EDIT_BOT_CAT_SELECTED:
                to_edit = Bot.get(id=obj["bid"])
                cat = Category.get(id=obj["cid"])
                botproperties.change_category(bot, update, to_edit, cat)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_COUNTRY:
                to_edit = Bot.get(id=obj["id"])
                botproperties.set_country_menu(bot, update, to_edit)
            elif action == CallbackActions.SET_COUNTRY:
                to_edit = Bot.get(id=obj["bid"])
                if obj["cid"] == "None":
                    country = None
                else:
                    country = Country.get(id=obj["cid"])
                botproperties.set_country(bot, update, to_edit, country)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_DESCRIPTION:
                to_edit = Bot.get(id=obj["id"])
                botproperties.set_text_property(bot, update, chat_data,
                                                "description", to_edit)
            elif action == CallbackActions.EDIT_BOT_EXTRA:
                to_edit = Bot.get(id=obj["id"])
                # SAME IS DONE HERE, but manually
                botproperties.set_text_property(bot, update, chat_data,
                                                "extra", to_edit)
            elif action == CallbackActions.EDIT_BOT_NAME:
                to_edit = Bot.get(id=obj["id"])
                botproperties.set_text_property(bot, update, chat_data, "name",
                                                to_edit)
            elif action == CallbackActions.EDIT_BOT_USERNAME:
                to_edit = Bot.get(id=obj["id"])
                botproperties.set_text_property(bot, update, chat_data,
                                                "username", to_edit)
            # elif action == CallbackActions.EDIT_BOT_KEYWORDS:
            #     to_edit = Bot.get(id=obj['id'])
            #     botproperties.set_keywords_init(bot, update, chat_data, to_edit)
            elif action == CallbackActions.APPLY_ALL_CHANGES:
                to_edit = Bot.get(id=obj["id"])
                admin.apply_all_changes(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_INLINEQUERIES:
                to_edit = Bot.get(id=obj["id"])
                value = bool(obj["value"])
                botproperties.toggle_value(bot, update, "inlinequeries",
                                           to_edit, value)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_OFFICIAL:
                to_edit = Bot.get(id=obj["id"])
                value = bool(obj["value"])
                botproperties.toggle_value(bot, update, "official", to_edit,
                                           value)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_OFFLINE:
                to_edit = Bot.get(id=obj["id"])
                value = bool(obj["value"])
                botproperties.toggle_value(bot, update, "offline", to_edit,
                                           value)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.EDIT_BOT_SPAM:
                to_edit = Bot.get(id=obj["id"])
                value = bool(obj["value"])
                botproperties.toggle_value(bot, update, "spam", to_edit, value)
                admin.edit_bot(bot, update, chat_data, to_edit)
            elif action == CallbackActions.CONFIRM_DELETE_BOT:
                to_delete = Bot.get(id=obj["id"])
                botproperties.delete_bot_confirm(bot, update, to_delete)
            elif action == CallbackActions.DELETE_BOT:
                to_edit = Bot.get(id=obj["id"])
                botproperties.delete_bot(bot, update, to_edit)
                # send_category(bot, update, chat_data, to_edit.category)
            elif action == CallbackActions.ACCEPT_SUGGESTION:
                suggestion = Suggestion.get(id=obj["id"])
                components.botproperties.accept_suggestion(
                    bot, update, suggestion)
                admin.approve_suggestions(bot, update, page=obj["page"])
            elif action == CallbackActions.REJECT_SUGGESTION:
                suggestion = Suggestion.get(id=obj["id"])
                suggestion.delete_instance()
                admin.approve_suggestions(bot, update, page=obj["page"])
            elif action == CallbackActions.CHANGE_SUGGESTION:
                suggestion = Suggestion.get(id=obj["id"])
                botproperties.change_suggestion(bot,
                                                update,
                                                suggestion,
                                                page_handover=obj["page"])
            elif action == CallbackActions.SWITCH_SUGGESTIONS_PAGE:
                page = obj["page"]
                admin.approve_suggestions(bot, update, page)
            elif action == CallbackActions.SWITCH_APPROVALS_PAGE:
                admin.approve_bots(bot, update, page=obj["page"])
            elif action == CallbackActions.SET_NOTIFICATIONS:
                set_notifications(bot, update, obj["value"])
            elif action == CallbackActions.NEW_BOTS_SELECTED:
                show_new_bots(bot, update, chat_data, back_button=True)
            elif action == CallbackActions.ABORT_SETTING_KEYWORDS:
                to_edit = Bot.get(id=obj["id"])
                admin.edit_bot(bot, update, chat_data, to_edit)
            # SENDING BOTLIST
            elif action == CallbackActions.SEND_BOTLIST:
                silent = obj.get("silent", False)
                re_send = obj.get("re", False)
                botlist.send_botlist(bot,
                                     update,
                                     resend=re_send,
                                     silent=silent)
            elif action == CallbackActions.RESEND_BOTLIST:
                botlist.send_botlist(bot, update, resend=True)
            # BROADCASTING
            elif action == "send_broadcast":
                broadcasts.send_broadcast(bot, update, user_data)
            elif action == "pin_message":
                broadcasts.pin_message(bot, update, obj["mid"])
            elif action == "add_thank_you":
                basic.add_thank_you_button(bot, update, obj["cid"], obj["mid"])
            # EXPLORING
            elif action == CallbackActions.EXPLORE_NEXT:
                explore.explore(bot, update, chat_data)
    except Exception as e:
        traceback.print_exc()

        # get the callback action in plaintext
        actions = dict(CallbackActions.__dict__)
        a = next(k for k, v in actions.items() if v == obj.get("a"))
        util.send_md_message(
            bot,
            settings.DEVELOPER_ID,
            "Exception in callback query for {}:\n{}\n\nWith CallbackAction {}\n\nWith data:\n{}"
            .format(
                user.markdown_short,
                util.escape_markdown(e),
                util.escape_markdown(a),
                util.escape_markdown(str(obj)),
            ),
        )
    finally:
        bot.answerCallbackQuery(update.callback_query.id)
        return ConversationHandler.END