def postPlaylist(self, playlist):
        #print self.request.POST
        if any((k not in self.request.POST or not self.request.POST[k] for k in
                ("title", "videoID", "startTime", "endTime"))):
            return self.returnJSON(None, code=400, message="Required fields not included")

        #print models.getPopulateDictionary(models.Snippet, self.request.POST.items())

        # validate videoID
        result = urlfetch.fetch("https://www.googleapis.com/youtube/v3/videos?id=%s&key=%s&part=id" % (
            self.request.get('videoID'), credentials.API_KEY))
        if result.status_code != 200:
            return self.returnJSON(None, code=400, message="Invalid YouTube VideoID")

        videoJSON = json.loads(result.content)
        if not videoJSON['pageInfo']['totalResults']:
            return self.returnJSON(None, code=400, message="Invalid YouTube VideoID")

        # create snippet
        newSnippet = models.Snippet(parent=playlist.key, **models.getPopulateDictionary(models.Snippet, self.request.POST.items()))
        # todo validate that start/end times are 0 <= startTime < endTime <= videoLength,  youtube embedd fails gracefully for now

        # put in datastore, then add to playlist
        snptKey = newSnippet.put()
        playlist.snippetKeys.append(snptKey)
        playlist.put()

        # return json with status
        dictout = {"result":"snippet created",
                   "snippet":snptKey.get()._to_dict()}
        return self.returnJSON(json.dumps(dictout), code=201)
예제 #2
0
    def update_snippet(self, email):
        week_string = self.request.get('week')
        week = datetime.datetime.strptime(week_string, '%m-%d-%Y').date()
        assert week.weekday() == 0, 'passed-in date must be a Monday'

        text = self.request.get('snippet')

        private = self.request.get('private') == 'True'
        is_markdown = self.request.get('is_markdown') == 'True'

        # TODO(csilvers): make this get-update-put atomic.
        # (maybe make the snippet id be email + week).
        q = models.Snippet.all()
        q.filter('email = ', email)
        q.filter('week = ', week)
        snippet = q.get()

        if snippet:
            snippet.text = text   # just update the snippet text
            snippet.private = private
            snippet.is_markdown = is_markdown
        else:
            # add the snippet to the db
            snippet = models.Snippet(created=_TODAY_FN(), email=email,
                                     week=week, text=text, private=private,
                                     is_markdown=is_markdown)
        db.put(snippet)
        db.get(snippet.key())  # ensure db consistency for HRD

        # When adding a snippet, make sure we create a user record for
        # that email as well, if it doesn't already exist.
        _get_or_create_user(email)
        self.response.set_status(200)
예제 #3
0
    def get(self):
        if not users.get_current_user():
            return _login_page(self.request, self)

        week_string = self.request.get('week')
        if week_string:
            week = datetime.datetime.strptime(week_string, '%m-%d-%Y').date()
        else:
            week = util.existingsnippet_monday(_TODAY_FN())

        snippets_q = models.Snippet.all()
        snippets_q.filter('week = ', week)
        snippets = snippets_q.fetch(1000)  # good for many users...
        # TODO(csilvers): filter based on wants_to_view

        # Get all the user records so we can categorize snippets.
        user_q = models.User.all()
        results = user_q.fetch(1000)
        email_to_category = {}
        email_to_user = {}
        for result in results:
            # People aren't very good about capitalizing their
            # categories consistently, so we enforce title-case,
            # with exceptions for 'and'.
            email_to_category[result.email] = _title_case(result.category)
            email_to_user[result.email] = result

        # Collect the snippets and users by category.  As we see each email,
        # delete it from email_to_category.  At the end of this,
        # email_to_category will hold people who did not give
        # snippets this week.
        snippets_and_users_by_category = {}
        for snippet in snippets:
            # Ignore this snippet if we don't have permission to view it.
            if (snippet.private and not _can_view_private_snippets(
                    _current_user_email(), snippet.email)):
                continue
            category = email_to_category.get(snippet.email,
                                             models.NULL_CATEGORY)
            if snippet.email in email_to_user:
                snippets_and_users_by_category.setdefault(category, []).append(
                    (snippet, email_to_user[snippet.email]))
            else:
                snippets_and_users_by_category.setdefault(category, []).append(
                    (snippet, models.User(email=snippet.email)))

            if snippet.email in email_to_category:
                del email_to_category[snippet.email]

        # Add in empty snippets for the people who didn't have any --
        # unless a user is marked 'hidden'.  (That's what 'hidden'
        # means: pretend they don't exist until they have a non-empty
        # snippet again.)
        for (email, category) in email_to_category.iteritems():
            if not email_to_user[email].is_hidden:
                snippet = models.Snippet(email=email, week=week)
                snippets_and_users_by_category.setdefault(category, []).append(
                    (snippet, email_to_user[snippet.email]))

        # Now get a sorted list, categories in alphabetical order and
        # each snippet-author within the category in alphabetical
        # order.
        # The data structure is ((category, ((snippet, user), ...)), ...)
        categories_and_snippets = []
        for (category,
             snippets_and_users) in snippets_and_users_by_category.iteritems():
            snippets_and_users.sort(key=lambda (snippet, user): snippet.email)
            categories_and_snippets.append((category, snippets_and_users))
        categories_and_snippets.sort()

        template_values = {
            'logout_url': users.create_logout_url('/'),
            'message': self.request.get('msg'),
            # Used only to switch to 'username' mode and to modify settings.
            'username': _current_user_email(),
            'is_admin': users.is_current_user_admin(),
            'prev_week': week - datetime.timedelta(7),
            'view_week': week,
            'next_week': week + datetime.timedelta(7),
            'categories_and_snippets': categories_and_snippets,
        }
        self.render_response('weekly_snippets.html', template_values)
예제 #4
0
    def _mock_data(self):
        # The fictional day for these tests Wednesday, July 29, 2015
        slacklib._TODAY_FN = lambda: datetime.datetime(2015, 7, 29)

        # Stuart created his account, but has never once filled out a snippet
        db.put(models.User(email='*****@*****.**'))

        # Fleetwood has two recent snippets, and always uses markdown lists,
        # but sometimes uses different list indicators or indention.
        db.put(models.User(email='*****@*****.**'))
        db.put(
            models.Snippet(email='*****@*****.**',
                           week=datetime.date(2015, 7, 27),
                           text=textwrap.dedent("""
            *  went for a walk
            *  sniffed some things
            *  hoping to sniff more things! #yolo
            """)))
        db.put(
            models.Snippet(email='*****@*****.**',
                           week=datetime.date(2015, 7, 20),
                           text=textwrap.dedent("""
            - lots of walks this week
            - not enough sniffing, hope to remedy next week!
            """)))

        # Toby has filled out two snippets, but missed a week in-between while
        # on vacation. When he got back from vacation he was still jetlagged so
        # he wrote a longform paragraph instead of a list.
        db.put(models.User(email='*****@*****.**'))
        db.put(
            models.Snippet(email='*****@*****.**',
                           week=datetime.date(2015, 7, 13),
                           text=textwrap.dedent("""
            - going on vacation next week, so excited!


            """)))
        db.put(
            models.Snippet(email='*****@*****.**',
                           week=datetime.date(2015, 7, 27),
                           text=textwrap.dedent("""
            I JUST GOT BACK FROM VACATION IT WAS TOTALLY AWESOME AND I SNIFFED
            ALL SORTS OF THINGS.  I GUESS I NEED TO WRITE SOMETHING HERE, HUH?

            OK THEN:
            - I had fun.

            LUNCHTIME SUCKERS!
            """)))

        # Fozzie tried hard to create an entry manually in the previous week,
        # but didn't understand markdown list syntax and got discouraged (so
        # has no entry this week, and a malformed one last week).
        db.put(models.User(email='*****@*****.**'))
        db.put(
            models.Snippet(email='*****@*****.**',
                           week=datetime.date(2015, 7, 20),
                           text=textwrap.dedent("""
            -is this how I list?
            -why is it not formatting??!?
            """)))