예제 #1
0
    def get_sites(self, limit):
        yield Site('/', datetime.date.today(), 'daily')
        url = self.reverse_url
        latest_date = datetime.date.today()
        for play_point in (self.db.PlayPoints.collection
                          .find().sort('modify_date', -1)
                          .limit(1)):
            latest_date = play_point['modify_date']
        yield Site(url('play_highscore'), latest_date, 'hourly')
        yield Site(url('stats_numbers'), changefreq='weekly')
        yield Site(url('stats_times_played'), changefreq='weekly')
        # help pages
        for see_also in HelpHandler.SEE_ALSO:
            try:
                url, __ = see_also
            except ValueError:
                url = '/%s' % see_also
            url = '/help' + url
            yield Site(url, changefreq='monthly')

        question_ids_with_images = [x['question'].id for x in
                                    self.db.QuestionImage.collection.find()]
        for question in self.db.Question.collection.find({'state': PUBLISHED}).sort('publish_date', -1).limit(limit - 10):
            image = None
            if question['_id'] in question_ids_with_images:
                image = (self.db.QuestionImage.collection
                       .one({'question.$id': question['_id']})
                       ['render_attributes']['src'])
            yield Site(get_question_slug_url(question),
                       question['publish_date'],
                       'monthly',
                       image=image)
예제 #2
0
    def test_viewing_public_question(self):
        user = self.db.User()
        user.username = u'peterbe'
        user.save()

        maths = self.db.Genre()
        maths.name = u'Celebs'
        maths.approved = True
        maths.save()

        question = self.db.Question()
        question.author = user
        question.text = u"How many (number) 'apple' are there?"
        question.answer = u'yes'
        question.alternatives = [u'yes', u'no', u'maybe', u'ok']
        question.genre = maths
        question.publish_date = (datetime.datetime.now() -
                                 datetime.timedelta(days=1))
        question.save()

        url = get_question_slug_url(question)
        response = self.client.get(url)
        self.assertEqual(response.code, 404)  # not published

        question.publish_date = (datetime.datetime.now() -
                                 datetime.timedelta(days=1))
        question.state = PUBLISHED
        question.save()

        response = self.client.get(url)
        self.assertEqual(response.code, 200)
        self.assertTrue(question.text in response.body)
예제 #3
0
    def test_viewing_public_question(self):
        user = self.db.User()
        user.username = u'peterbe'
        user.save()

        maths = self.db.Genre()
        maths.name = u'Celebs'
        maths.approved = True
        maths.save()

        question = self.db.Question()
        question.author = user
        question.text = u"How many (number) 'apple' are there?"
        question.answer = u'yes'
        question.alternatives = [u'yes', u'no', u'maybe', u'ok']
        question.genre = maths
        question.publish_date = (datetime.datetime.now() -
                                 datetime.timedelta(days=1))
        question.save()

        url = get_question_slug_url(question)
        response = self.client.get(url)
        self.assertEqual(response.code, 404)  # not published

        question.publish_date = (datetime.datetime.now() -
                                 datetime.timedelta(days=1))
        question.state = PUBLISHED
        question.save()

        response = self.client.get(url)
        self.assertEqual(response.code, 200)
        self.assertTrue(question.text in response.body)
예제 #4
0
    def get_sites(self, limit):
        yield Site('/', datetime.date.today(), 'daily')
        url = self.reverse_url
        latest_date = datetime.date.today()
        for play_point in (self.db.PlayPoints.collection.find().sort(
                'modify_date', -1).limit(1)):
            latest_date = play_point['modify_date']
        yield Site(url('play_highscore'), latest_date, 'hourly')
        yield Site(url('stats_numbers'), changefreq='weekly')
        yield Site(url('stats_times_played'), changefreq='weekly')
        # help pages
        for see_also in HelpHandler.SEE_ALSO:
            try:
                url, __ = see_also
            except ValueError:
                url = '/%s' % see_also
            url = '/help' + url
            yield Site(url, changefreq='monthly')

        question_ids_with_images = [
            x['question'].id for x in self.db.QuestionImage.collection.find()
        ]
        for question in self.db.Question.collection.find({
                'state': PUBLISHED
        }).sort('publish_date', -1).limit(limit - 10):
            image = None
            if question['_id'] in question_ids_with_images:
                image = (self.db.QuestionImage.collection.one(
                    {'question.$id':
                     question['_id']})['render_attributes']['src'])
            yield Site(get_question_slug_url(question),
                       question['publish_date'],
                       'monthly',
                       image=image)
예제 #5
0
    def test_page_not_found_raised_in_handler(self):
        # if a handler raises an 404 it should show the 404.html template
        q = self._create_question(text="Peter's name?")
        url = get_question_slug_url(q)
        url = url.replace('Peter', 'Chris')

        from apps.main.handlers import BaseHandler
        response = self.client.get(url)
        self.assertEqual(response.code, 404)
        self.assertTrue(BaseHandler.page_not_found_page_title
                        in response.body)
예제 #6
0
    def _create_message(self, _id, use_url_shortener=False):
        question = self.db.Question.one({'_id': ObjectId(_id)})
        url = get_question_slug_url(question)
        url = 'http://%s%s' % (self.request.host, url)
        if use_url_shortener:

            url = url_shorten(url)
        message = "New question: %s\n%s" % (question.text, url)
        if question.genre and question.genre.approved:
            message += '\n#%s' % question.genre.name
        user_settings = self.get_user_settings(question.author)
        if user_settings and user_settings['twitter']:
            message += '\nThanks @%s' % user_settings['twitter']['screen_name']

        return message
예제 #7
0
    def _create_message(self, _id, use_url_shortener=False):
        question = self.db.Question.one({'_id': ObjectId(_id)})
        url = get_question_slug_url(question)
        url = 'http://%s%s' % (self.request.host, url)
        if use_url_shortener:

            url = url_shorten(url)
        message = "New question: %s\n%s" % (question.text, url)
        if question.genre and question.genre.approved:
            message += '\n#%s' % question.genre.name
        user_settings = self.get_user_settings(question.author)
        if user_settings and user_settings['twitter']:
            message += '\nThanks @%s' % user_settings['twitter']['screen_name']

        return message
예제 #8
0
 def test_sitemap_xml(self):
     # create a question
     q1 = self._create_question()
     q2 = self._create_question()
     image = self._attach_image(q2)
     url = self.reverse_url('sitemap_xml')
     response = self.client.get(url)
     self.assertEqual(response.code, 200)
     self.assertEqual(response.headers['content-type'], 'application/xml')
     self.assertTrue(get_question_slug_url(q1) in response.body)
     self.assertTrue(image.render_attributes['src'] in response.body)
     url_regex = re.compile('<loc>(.*?)</loc>')
     for full_url in url_regex.findall(response.body):
         url = full_url.replace('http://', '')
         url = '/' + url.split('/', 1)[1]
         r = self.client.get(url)
         self.assertEqual(r.code, 200)
예제 #9
0
 def test_no_questions_point_json(self):
     url = self.reverse_url('stats_no_questions_point_json')
     self._login()
     q1 = self._create_question()
     assert q1.state == 'PUBLISHED', q1.state
     date = q1.publish_date + datetime.timedelta(days=2)
     assert date
     data = {
       'what': 'Questions',
       'timestamp': int(time.mktime(date.timetuple()))
     }
     response = self.client.get(url, data)
     self.assertEqual(response.code, 200)
     self.assertTrue(response.headers['content-type']
                     .startswith('application/json'))
     struct = json.loads(response.body)
     self.assertTrue(struct['items'])
     self.assertEqual(len(struct['items']), 1)
     item = struct['items'][0]
     self.assertEqual(item['text'], q1.text)
     self.assertEqual(item['url'],
                      get_question_slug_url(q1))
예제 #10
0
    def get(self):
        what = self.get_argument('what')
        timestamp = self.get_argument('timestamp')
        items = []
        _days = lambda x: datetime.timedelta(days=x)
        if what == 'Questions':
            when = parse_datetime(timestamp)
            search = {'state': 'PUBLISHED',
                      'publish_date': {'$gte': when - _days(7),
                                       '$lt': when - _days(0)}}
            questions = (self.db.Question.collection
                         .find(search))
            for question in questions:
                url = get_question_slug_url(question)
                items.append({'url': url,
                              'text': question['text']})

        elif what == 'Contributors':
            when = parse_datetime(timestamp)
            search = {'state': 'PUBLISHED',
                      'publish_date': {'$gte': when - _days(7),
                                       '$lt': when - _days(0)}}
            questions = (self.db.Question.collection
                         .find(search))
            users = defaultdict(int)
            for question in questions:
                users[question['author'].id] += 1
            as_list = [(c, i) for i, c in users.items()]
            as_list.sort()
            as_list.reverse()
            for count, _id in as_list:
                user = self.db.User.one({'_id': _id})
                text = "%s (%s)" % (user.username, count)
                items.append({'text': text})
        else:
            raise HTTPError(404, "Invalid argument %r" % what)
        self.write_json(dict(items=items))