Пример #1
0
async def schedule_new_post(story: Story) -> None:
    img_links = json.loads(story.img_links)
    keyboard = get_story_keyboard(story)

    if len(img_links) == 1:
        response = await bot.send_photo(ADMIN_CHANNEL,
                                        photo=img_links[0],
                                        caption=story.title,
                                        reply_markup=keyboard)
    elif len(img_links) > 1:
        media = await prepare_media(img_links)

        # text may be added to the message only by
        # adding it to the first item in MediaGroup
        media[0].caption = story.title

        response = await bot.send_media_group(ADMIN_CHANNEL, media)
        response = await bot.send_message(
            ADMIN_CHANNEL,
            story.title,
            reply_to_message_id=response[0].message_id,
            reply_markup=keyboard)
    else:
        response = await bot.send_message(ADMIN_CHANNEL,
                                          story.title,
                                          reply_markup=keyboard,
                                          parse_mode='Markdown')
    story.admin_message_id = response['message_id']
    story.save()
Пример #2
0
def story(id):
    st = Story.query.filter_by(id=id).first_or_404()
    temp_st = Story()
    temp_st.title = str(st.title)
    temp_st.slug = str(st.slug)
    print st.title
    print "is the title before POST"
    form = StoryForm(obj=st)
    form.populate_obj(st)
    if request.method == "POST":
       print temp_st.title
       print "is temp_st.title"
       st.text = form.text.data
       st.title = temp_st.title
       st.slug = temp_st.slug
       print st.title
       print "is the title after POST"
       if request.form.get('submit_button')== "Save":
           flash("Story saved.", 'success')
       if request.form.get('submit_button')== "Translate":
           flash("Story Ready To Translate.", 'success')
           st.ready_to_translate = True
       db.session.add(st)
       db.session.commit()

    return render_template("stories/story.html", story=st, form=form)
Пример #3
0
    def post(self, id):
        import os, static, hashlib
        from models import StoryAuthor, Story, StoryDocument
        from django.template.defaultfilters import slugify
        from google.appengine.runtime.apiproxy_errors import RequestTooLargeError
        
        content = self.request.get('content')
        title = self.request.get('title')
        
        story = Story.get_by_id(int(id, 10))
        story.content = content
        story.title = title
        story.put()

        try:
            request_document = self.request.get('document')
            document_file = self.request.POST['document']        
            if request_document:
                document_body = document_file.value
                document_digest = hashlib.sha1(document_body).hexdigest()
                split_name = os.path.splitext(os.path.basename(document_file.filename))
                filename = slugify(split_name[0]) or document_digest
                document_name = filename + split_name[1]
        
                document_path = '/story/%d/document/%s/%s' % (story.key().id(), document_digest, document_name)
                logging.info(document_path)
                story_document = StoryDocument(story=story, path=document_path, name=document_name)
                story_document.put()
                document = static.set(document_path, document_body, document_file.type)
            self.get(id)                
        except RequestTooLargeError, message:
            self.render_to_response("story_edit.html", 
                story=Story.get_by_id(int(id, 10)),
                request_too_large_error=True)
Пример #4
0
    def new_story(payload):
        data = request.get_json()
        if data is None:
            return abort(400)
        authors = Author.query.all()
        for author in authors:
            #Checks if the logged-in user is the one posting
            if payload['sub'].split("auth0|")[1] == author.user_id:
                if 'title' in data and 'type' in data and 'category' in data and 'content' in data:
                    story = Story(title=data['title'],
                                  type=data['type'],
                                  category=data['category'],
                                  content=data['content'],
                                  author=author.id)
                    story.insert()
                    temp_res = story.format()
                    res = {
                        'success':
                        True,
                        'code':
                        200,
                        'message':
                        'Story {} written by {} {} was successfully added'.
                        format(story.title, author.fname, author.lname)
                    }
                    return jsonify(res)
                msg = 'Some information is missing or a wrong formed request.'
                return abort(400, msg)

        return abort(401)
Пример #5
0
    def post(self):
        step_template = jinjaEnv.get_template("newStep.html")
        self.response.write(step_template.render())

        tStory = Story(title=self.request.get("adventure_name"))
        print("THE TITLE OF THE STORY IS" + tStory.title)
        tStory.put()
Пример #6
0
def api_create_game(request,*,process,stagename,story,chose,refstoryid,author):
    check_admin(request)
    #若无 stagename 则不创建stage
    tagid=next_id()
    if not story or not story.strip():
        raise APIValueError("story",'story cannot be empty.')
    if not process or not process.strip():
        raise APIValueError('process','process cannot be empty.')
    if not chose or not chose.strip():
        raise APIValueError('chose','chose cannot be empty.')
    if not refstoryid or not refstoryid.strip():
        raise APIValueError('refstoryid','refstoryid cannot be empty.')
    
    story = Story(tagid = tagid,process=process.strip(),story=story.strip(),author=author.strip())
    storyid =yield from Story.findbycolumnname("tagid",'00151272809336730536a55a20d4b01b4853c53a08639f2000')
    # print(storyid.id)
    yield from story.save()
    l_chose = chose.split("#")
    l_refstoryid = refstoryid.split("#")
    for c in l_chose:
        i=0
        tagid = next_id()
        choose = Chose(tagid=tagid,storyid=storyid.id,choose = c)
        yield from choose.save()
        chooseid= yield from Chose.findbycolumnname("tagid",tagid)
        refstory = refStory(tagid = next_id(),chooseid=chooseid.id,refstoryid=l_refstoryid[i])
        i=i+1
        yield from refstory.save()
    return story
Пример #7
0
def randomstory():
    while True:
        num = Story.count()
        id = random.choice([i for i in range(1,num+1)])
        story = Story.find(id)
        if story.islook is 1:
            continue
        content = story.content
        content.replace('<br>', '\n')
        soup = BeautifulSoup(content, 'lxml')
        story.islook = 1;
        story.update()
        return story.get('question')+'?\n'+soup.get_text()
Пример #8
0
def add(request):
    url = request.POST['url']
    parsed = urlparse(url)

    if parsed.scheme =='':
        url = 'http://' + url

    domain = urlparse(url)[1]

    soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
    title = soup.title.string

    s = Story(link=url, domain=domain, title=title, user=request.user)
    s.save()
    return redirect('/list.html')
Пример #9
0
async def schedule_trigger():
    while True:
        now = datetime.now()
        now = now.replace(second=0, microsecond=0)
        for story in Story.select().where(Story.scheduled_datetime == now,
                                          Story.prod_message_id == None):
            img_links = json.loads(story.img_links)

            if len(img_links) == 1:
                response = await bot.send_photo(MEMOTRON_CHANNEL,
                                                photo=img_links[0],
                                                caption=story.title)

            elif len(img_links) > 1:
                medias = [InputMediaPhoto(url) for url in img_links]
                if len(medias) > 10:  # TG limit
                    return

                response = await bot.send_media_group(MEMOTRON_CHANNEL, medias)
                response = response[0]
            else:
                response = await bot.send_message(MEMOTRON_CHANNEL,
                                                  text=story.text)
            logger.info(response)
            story.prod_message_id = response['message_id']
            story.save()

            await sleep(1)
        await sleep(1)
Пример #10
0
def createStory():
    story_name = request.form['story_name']
    rowcount = request.form['rowcount']

    story_obj = Story(name=story_name)
    db.session.add(story_obj)
    db.session.commit()
    story_obj_id = Story.query.filter_by(name=story_name).first().id

    for i in range(int(rowcount)):
        foo = request.form['row' + str(i)]
        if (foo.split()[0] == 'intent'):
            foobar = StoryStep(isIntent=1,
                               story_id=story_obj_id,
                               int_or_temp_id=int(foo.split()[1]))
            db.session.add(foobar)
            db.session.commit()
        elif (foo.split()[0] == 'template'):
            foobar = StoryStep(isIntent=2,
                               story_id=story_obj_id,
                               int_or_temp_id=int(foo.split()[1]))
            db.session.add(foobar)
            db.session.commit()
        else:
            foobar = StoryStep(isIntent=3,
                               story_id=story_obj_id,
                               int_or_temp_id=int(foo.split()[1]))
            db.session.add(foobar)
            db.session.commit()

    return render_template("success.html", message="Story created")
Пример #11
0
    def test_flags(self) -> None:
        """Tests Story flag getters & setters."""

        story = Story.new(self.testuser, "test")

        story.flags = 0
        self.assertFalse(story.private)
        self.assertFalse(story.can_comment)
        self.assertFalse(story.is_risque)

        story.private = True
        self.assertTrue(story.private)
        self.assertEqual(story.flags, Story.Flags.PRIVATE)

        story.can_comment = True
        self.assertTrue(story.can_comment)
        self.assertEqual(story.flags,
                         Story.Flags.PRIVATE | Story.Flags.CAN_COMMENT)

        story.can_comment = False
        story.is_risque = True
        self.assertFalse(story.can_comment)
        self.assertTrue(story.is_risque)
        self.assertEqual(story.flags,
                         Story.Flags.PRIVATE | Story.Flags.IS_RISQUE)
Пример #12
0
 def get(self):
     allStories = Story.query().fetch()
     print("***********************************")
     print(allStories[0].key.id())
     all_dict = {"theStories": allStories}
     all_stories_template = jinjaEnv.get_template("browse.html")
     self.response.write(all_stories_template.render(all_dict))
Пример #13
0
    def test_visibility(self) -> None:
        """Tests story visibility based on privacy & NSFW flags."""

        story = Story.new(self.testuser, "test")

        # private stories are visible only to the author
        self.assertTrue(story.visible(self.testuser))
        self.assertFalse(story.visible(self.testuser2))
        self.assertFalse(story.visible(self.testuser3))
        self.assertFalse(story.visible())

        # public stories are visible to all
        story.private = False
        self.assertTrue(story.visible(self.testuser))
        self.assertTrue(story.visible(self.testuser2))
        self.assertTrue(story.visible(self.testuser3))
        self.assertTrue(story.visible())

        # risque stories are visible only to those who allow themselves to view them
        story.is_risque = True
        self.assertTrue(story.visible(self.testuser))
        self.assertFalse(story.visible(self.testuser2))
        self.assertTrue(story.visible(self.testuser3))
        self.assertFalse(story.visible())

        # user should not have access to stories which are risque, even if they created them
        self.testuser.allow_risque = False
        self.assertFalse(story.visible(self.testuser))
        self.assertFalse(story.visible(self.testuser2))
        self.assertTrue(story.visible(self.testuser3))
        self.assertFalse(story.visible())
Пример #14
0
 def story(self, story_id, is_author=False):
   story = Story.get_by_id(int(story_id))
   if not story:
     self.abort(404)
   if is_author and story.author != self.user:
     self.abort(401)
   return story
Пример #15
0
 def _update_story_name(self, event):
     story = Story.get_by_story_id(event.story_id)
     if story:
         logging.info("Updating story name to: " + event.story_title)
         story.name = event.story_title
         story.put()
     else:
         logging.info("Cannot update story name (" + event.story_id + "): story does not exist")
Пример #16
0
    def create_story(payload):
        data = request.get_json()
        # DONE: get user e-mail from JWT token & allow only owner to edit post
        # https://stackoverflow.com/questions/3368969/find-string-between-two-substrings
        get_email = json.dumps(payload['https://tellatale.com/email'])
        email = (get_email.split('"')[1].split('"')[0])
        user_exists = User.query.filter_by(email=email).first()
        if not user_exists:
            temp_name = (email.split("@")[0])
            new_user = User(email=email, name=temp_name)
            new_user.insert()
            author_id = new_user.id
        else:
            author_id = user_exists.id

        title = data.get('title')
        cover_image = data.get('cover_image')
        genre = data.get('genre')
        content = data.get('content')
        release_date = data.get('release_date')
        release_status = data.get('released')
        read_time = data.get('read_time')

        if (not title or not content or not genre or not release_date
                or not release_status):
            abort(422)

        try:
            new_story = Story(title=title,
                              cover_image=cover_image,
                              genre=genre,
                              content=content,
                              release_date=release_date,
                              release_status=release_status,
                              read_time=read_time,
                              author_id=author_id)
            new_story.insert()

            return jsonify({
                'success': True,
                'message': 'Your story has been Created'
            }), 201

        except Exception:
            print(sys.exc_info())
            abort(422)
Пример #17
0
    def get(self, story_id, line_id):
        story = Story.get_by_story_id(story_id)
        story_line = StoryLine.get_by_id(int(line_id), parent=story)
        story_line.is_deleted = True
        story_line.deleted_by_user = users.get_current_user()
        story_line.put()

        self.redirect('/s/' + story_id)
Пример #18
0
 def scrape_spreadsheet(self, filename):
     stories = []
     spreadsheet = copytext.Copy(filename)
     data = spreadsheet['Form Responses 1']
     for row in data:
         story = Story(row)
         stories.append(story)
     return stories
Пример #19
0
    def create():
        """ Populates new stories from HN """
        hn = HackerNewsParser()
        posts = hn.get_hacker_json()
        data = [{key: item[key]
                 for key in ['title', 'url', 'time']} for item in posts]

        try:
            for story in data:
                model = Story(title=story['title'],
                              url=story['url'],
                              created_at=story['time'])
                model.save()
        except Exception as e:
            abort(500, str(e))

        return
def edit_story(story_id):
    if request.method == 'GET':
        story = Story.get(Story.id == story_id)
        return render_template('form.html',
                               us_story=story,
                               header="Edit Story",
                               button="Update")
    else:
        edit_story = Story.update(
            story_title=request.form['story_title'],
            user_story=request.form['user_story'],
            acceptance_criteria=request.form['acceptance_criteria'],
            business_value=request.form['business_value'],
            estimation=request.form['estimation'],
            status=request.form['status']).where(Story.id == story_id)
        edit_story.execute()
        return redirect(url_for('show_stories'))
Пример #21
0
 def decorate(self, entity_id=None):
     entity = None
     if entity_id:
         entity = Story.get_by_id(int(entity_id))
         if not entity:
             self.error(404)
         return
     fun(self, entity)
Пример #22
0
    def test_new(self) -> None:
        """Tests the Story.new class method."""

        # title must be a string with at least one non-whitespace character
        self.assertRaises(ValueError, Story.new, self.testuser, None)
        self.assertRaises(ValueError, Story.new, self.testuser, 123)
        self.assertRaises(ValueError, Story.new, self.testuser, True)
        self.assertRaises(ValueError, Story.new, self.testuser, -1.5)
        self.assertRaises(ValueError, Story.new, self.testuser, "")
        self.assertRaises(ValueError, Story.new, self.testuser, " ")

        # summary must be a string
        self.assertRaises(ValueError, Story.new, self.testuser, "test", 321)
        self.assertRaises(ValueError, Story.new, self.testuser, "test", False)
        self.assertRaises(ValueError, Story.new, self.testuser, "test", 3.2)

        story1 = Story.new(self.testuser, "test")
        self.assertEqual(story1.author, self.testuser)
        self.assertEqual(story1.flags, Story.Flags.DEFAULT)
        self.assertEqual(story1.title, "test")
        self.assertEqual(story1.summary, "")
        self.assertEqual(story1.thumbnail.url, Story.DEFAULT_THUMBNAIL_URI)
        self.assertIn(story1, self.testuser.stories)
        self.assertEqual(len(self.testuser.stories), 1)
        self.assertEqual(len(story1.tags), 0)
        self.assertEqual(len(story1.favorited_by), 0)
        self.assertEqual(len(story1.followed_by), 0)
        self.assertEqual(len(story1.reports), 0)
        self.assertEqual(story1.posted, story1.modified)

        story2summary = "This is a test from Speakonia."
        story2 = Story.new(self.testuser, "    test  2 ", story2summary)
        self.assertEqual(story2.author, self.testuser)
        self.assertEqual(story2.flags, Story.Flags.DEFAULT)
        self.assertEqual(story2.title, "test 2")
        self.assertEqual(story2.summary, story2summary)
        self.assertEqual(story2.thumbnail.url, Story.DEFAULT_THUMBNAIL_URI)
        self.assertIn(story1, self.testuser.stories)
        self.assertIn(story2, self.testuser.stories)
        self.assertEqual(len(self.testuser.stories), 2)
        self.assertEqual(len(story2.tags), 0)
        self.assertEqual(len(story2.favorited_by), 0)
        self.assertEqual(len(story2.followed_by), 0)
        self.assertEqual(len(story2.reports), 0)
        self.assertEqual(story2.posted, story2.modified)
def add_story():
    new_story = Story.create(
        story_title=request.form['story_title'],
        user_story=request.form['user_story'],
        acceptance_criteria=request.form['acceptance_criteria'],
        business_value=request.form['business_value'],
        estimation=request.form['estimation'],
        status=request.form['status'])
    return redirect(url_for('show_stories'))
Пример #24
0
def add_story():
    new_story = Story.create(story_title=request.form['story_title'],
                             user_story=request.form['user_story'],
                             criteria=request.form['criteria'],
                             business_value=request.form['business_value'],
                             estimation=request.form['estimation'],
                             status=request.form['status'])
    new_story.save()
    return redirect(url_for('display_stories'))
Пример #25
0
 def get(self, id):
     user = users.get_current_user()
     if not user:
         self.redirect(users.create_login_url(self.request.uri))
         return
     logging.warn("Logged in as %s (%s)", user.nickname(), user.user_id())
     self.render_to_response("story_edit.html", 
         story=Story.get_by_id(int(id, 10)),
         request_too_large_error=False)
Пример #26
0
    def _extract_stories(self, story_elements):
        stories = []

        for story_el in story_elements:
            story_el = PyQuery(story_el, parser='xml')
            story = Story(story_el, self.run_time)
            stories.append(story)
            logger.info('Scraped %s from Seamus API (%s)' % (story.story_id, story.title))

        return stories
Пример #27
0
def update_story(story_id):
    update = Story.update(
        story_title=request.form["story_title"],
        user_story=request.form["user_story"],
        criteria=request.form["criteria"],
        business_value=request.form["business_value"],
        estimation=request.form["estimation"],
        status=request.form["status"]).where(Story.id == story_id)
    update.execute()
    return redirect(url_for('display_stories'))
Пример #28
0
    def post(self, story_id):
        story = Story.get_by_story_id(story_id)
        story.name = self.request.get('name')
        story.java_estimate = int(self.request.get('java_estimate'))
        story.cs_estimate = int(self.request.get('cs_estimate'))

        story.user = users.get_current_user()

        story.put()
        self.redirect('/s/' + story.story_id)
Пример #29
0
    def _create_new_story(self, event):
        logging.info('Creating story')
        story = Story(story_id=event.story_id, name=event.story_title)
        story.put()

        project = Project.get()

        api_url = 'http://www.pivotaltracker.com/services/v3/projects/{PROJECT_ID}/stories/{STORY_ID}/notes'.replace('{PROJECT_ID}', project.project_id).replace('{STORY_ID}', story.story_id)
        comment_xml = '<note><text>http://{APP_ID}.appspot.com/s/{STORY_ID}</text></note>'.replace('{APP_ID}', os.environ['APPLICATION_ID']).replace('{STORY_ID}', story.story_id)

        logging.info('Api url: ' + api_url)
        logging.info('Comment xml: ' + comment_xml)

        #post a comment back to pivotal tracker
        result = urlfetch.fetch(url=api_url,
                                payload=comment_xml,
                                method=urlfetch.POST,
                                headers={'Content-Type': 'application/xml', 'X-TrackerToken': project.api_token})
        logging.info('Result of API call: ' + result.content)
Пример #30
0
    def setUp(self) -> None:
        super().setUp()

        for img in RefImage.query.filter(~RefImage.id.in_({1, 2})).all():
            db.session.delete(img)

        StoryTag.query.delete()
        Tag.query.delete()
        Story.query.delete()
        User.query.delete()

        users = [User(**data) for data in USERDATA]
        db.session.add_all(users)

        tags = (Tag.new("category", "fanfiction", commit=False),
                Tag.new("category", "original", commit=False),
                Tag.new("category", "crossover",
                        commit=False), Tag.new("genre", "action",
                                               commit=False),
                Tag.new("genre", "adventure",
                        commit=False), Tag.new("genre",
                                               "romance",
                                               commit=False),
                Tag.new("genre", "suspense", commit=False),
                Tag.new("genre", "thriller", commit=False),
                Tag.new("generic", "abcdef", commit=False))

        db.session.add_all(tags)
        db.session.commit()

        self.tags = [(tag.url_safe_query_name, tag.name, tag.type)
                     for tag in tags]
        self.user_ids = [id for id in map(lambda user: user.id, users)]

        stories = [
            Story(**STORYDATA[i], author_id=self.user_ids[i])
            for i in range(len(STORYDATA))
        ]
        db.session.add_all(stories)
        db.session.commit()
        self.story_ids = [id for id in map(lambda story: story.id, stories)]

        stories[0].tags.append(tags[0])
        stories[0].tags.append(tags[4])

        stories[1].tags.append(tags[1])
        stories[1].tags.append(tags[6])

        stories[2].tags.append(tags[2])
        stories[2].tags.append(tags[4])
        stories[2].tags.append(tags[7])
        stories[2].tags.append(tags[8])
        db.session.commit()

        self.client = app.test_client()
Пример #31
0
    def addStory():
        new_story_data = json.loads(request.data)
        new_story = Story(title=new_story_data['title'],
                          synopsis=new_story_data['synopsis'])

        # Try to add the new story
        try:
            insert(new_story)
        except:
            abort(500)

        return jsonify({'success': True})
Пример #32
0
async def watch_new_stories() -> None:
    while True:
        unpublished_stories = Story.select().where(
            Story.admin_message_id.is_null(), Story.text == "")

        for story in unpublished_stories:
            try:
                await schedule_new_post(story)
            except Exception as e:
                logger.exception(e)
            await sleep(1)
        await sleep(1)
Пример #33
0
Файл: views.py Проект: gcr/twg
def create_new_story(request):
    if request.method == "POST":
        # They attempted to create a story
        story_form = forms.NewStoryForm(request.POST)
        frag_form = forms.AddFragmentForm(request.POST)
        if story_form.is_valid() and frag_form.is_valid():
            # Store the new story and the fragment
            story = Story(
                name = story_form.cleaned_data['story_name'],
                last_update_date = datetime.datetime.now()
            )
            # Give 'er a slug!
            story.slug = slugify(story.name, instance=story)
            story.save()
            story.add_fragment(frag_form.cleaned_data['fragment_text'], request.user)
            return HttpResponseRedirect(reverse('story_detail', kwargs={'slug':story.slug}))
    else:
        # Return a blank form page
        story_form = forms.NewStoryForm()
        frag_form = forms.AddFragmentForm()
        
    return render_to_response("stories/add_new_story.html",
        RequestContext(request, {
            'story_form':story_form,
            'frag_form':frag_form,
        })
    )
Пример #34
0
def get_schedule_button_text(story: Story) -> str:
    """If story is not scheduled we offer the nearest available time,
    in other way we display scheduled time"""
    if story.scheduled_datetime:
        story_time = story.scheduled_datetime
        scheduled_flag = '✅'
    else:
        story_time = Story.get_available_time()
        scheduled_flag = ''

    schedule_button_text = f'🗓 {story_time.strftime("%H:%M")} {scheduled_flag}'

    return schedule_button_text
Пример #35
0
    def test_visible_stories(self):
        """Tests the User.visible_stories method."""

        bday = date.today() + relativedelta(years=-20, months=-3, days=-11)
        user1 = User.register("testuser", "abcdefg", "*****@*****.**", bday)
        user2 = User.register("testuser2", "abcdefg", "*****@*****.**", bday)

        user2.allow_risque = True

        story1 = Story.new(user2, "Test")
        story1.is_risque = True
        story1.private = False

        story2 = Story.new(user2, "Test")
        story2.private = False

        story3 = Story.new(user2, "Test")

        stories = user2.visible_stories().all()
        self.assertNotIn(story1, stories)
        self.assertIn(story2, stories)
        self.assertNotIn(story3, stories)

        stories = user2.visible_stories(user1).all()
        self.assertNotIn(story1, stories)
        self.assertIn(story2, stories)
        self.assertNotIn(story3, stories)

        stories = user2.visible_stories(user2).all()
        self.assertIn(story1, stories)
        self.assertIn(story2, stories)
        self.assertNotIn(story3, stories)

        stories = user1.visible_stories()
        self.assertNotIn(story1, stories)
        self.assertNotIn(story2, stories)
        self.assertNotIn(story3, stories)
Пример #36
0
async def update_keyboards() -> None:
    """Updates message keyboards in admin channel"""
    while True:
        for story in Story.select().\
                           where(Story.scheduled_datetime.is_null()).\
                           order_by(Story.post_datetime.desc()):
            keyboard = get_story_keyboard(story)
            try:
                await bot.edit_message_reply_markup(
                    ADMIN_CHANNEL,
                    message_id=story.admin_message_id,
                    reply_markup=keyboard)
            except (MessageToEditNotFound, MessageNotModified) as e:
                logger.debug(e)
            await sleep(3)
Пример #37
0
def update_story():
    id = request.form['id']
    storytitle = request.form['storytitle']
    userstory = request.form['userstory']
    criteria = request.form['criteria']
    businessvalue = request.form['businessvalue']
    estimation = request.form['estimation']
    status = request.form['status']
    user_story = Story.update(storytitle=storytitle,
                              userstory=userstory,
                              criteria=criteria,
                              businessvalue=businessvalue,
                              estimation=estimation,
                              status=status).where(Story.id == id)
    user_story.execute()
    return redirect(url_for('list'))
Пример #38
0
    def test_favorites(self) -> None:
        """Tests favoriting & following stories."""

        story = Story.new(self.testuser, "test")

        story.favorited_by.append(self.testuser2)
        self.assertEqual(len(story.favorited_by), 1)
        self.assertEqual(len(story.favorited_by), story.favorites)
        self.assertIn(story, self.testuser2.favorite_stories)
        self.assertEqual(len(self.testuser2.favorite_stories), 1)

        story.followed_by.append(self.testuser3)
        self.assertEqual(len(story.followed_by), 1)
        self.assertEqual(len(story.followed_by), story.follows)
        self.assertIn(story, self.testuser3.followed_stories)
        self.assertEqual(len(self.testuser3.followed_stories), 1)
Пример #39
0
def add_stories():
    storytitle = request.form['storytitle']
    userstory = request.form['userstory']
    criteria = request.form['criteria']
    businessvalue = request.form['businessvalue']
    estimation = request.form['estimation']
    status = request.form['status']

    new_stories = Story.create(storytitle=storytitle,
                               userstory=userstory,
                               criteria=criteria,
                               businessvalue=businessvalue,
                               estimation=estimation,
                               status=status)
    new_stories.save()
    flash('New entry was successfully posted')
    return redirect(url_for('list'))
Пример #40
0
    def post(self):
        import os, static, hashlib
        from models import StoryAuthor, Story, StoryDocument
        from django.template.defaultfilters import slugify
        from google.appengine.runtime.apiproxy_errors import RequestTooLargeError
        
        title = self.request.get('title')
        content = self.request.get('content')
        full_name = self.request.get('full_name')
        mobile_number = self.request.get('mobile_number')
        email = self.request.get('email')

        author = StoryAuthor(full_name=full_name, email=email, mobile_number=mobile_number)
        author.put()
    
        story = Story(title=title)
        if content:
            story.content = content
        story.author = author
        story.put()

        try:
            request_document = self.request.get('document')
            if request_document:
                document_file = self.request.POST['document']        
                document_body = document_file.value
                document_digest = hashlib.sha1(document_body).hexdigest()
                split_name = os.path.splitext(os.path.basename(document_file.filename))
                filename = slugify(split_name[0]) or document_digest
                document_name = filename + split_name[1]
        
                document_path = '/story/%d/document/%s/%s' % (story.key().id(), document_digest, document_name)
                logging.info(document_path)
                story_document = StoryDocument(story=story, path=document_path, name=document_name)
                story_document.put()
                document = static.set(document_path, document_body, document_file.type, name=document_name)
                self.render_to_response("thanks/story.html", document=story_document, story=story)
            else:
                self.render_to_response("thanks/story.html", story=story)
                
        except RequestTooLargeError, message:
            from api_preferences import facebook as fb_prefs, google_friend_connect as gfc
            self.render_to_response("start.html",
                                       FACEBOOK_API_KEY=fb_prefs.get('api_key'),
                                       FACEBOOK_CROSS_DOMAIN_RECEIVER_URL=fb_prefs.get('cross_domain_receiver_url'),
                                       GOOGLE_FRIEND_CONNECT_SITE_ID=gfc.get('site_id'),
                                       request_too_large_error=True,
                                       title=title,
                                       content=content,
                                       full_name=full_name,
                                       email=email,
                                       mobile_number=mobile_number)
Пример #41
0
    def setUp(self) -> None:
        super().setUp()

        for img in RefImage.query.filter(~RefImage.id.in_({1, 2})).all():
            db.session.delete(img)

        FavoriteStory.query.delete()
        FollowingStory.query.delete()
        Chapter.query.delete()
        Story.query.delete()
        User.query.delete()

        users = [User(**data) for data in USERDATA]
        db.session.add_all(users)
        db.session.commit()
        self.user_ids = [id for id in map(lambda user: user.id, users)]

        stories = [
            Story(**STORYDATA[i], author_id=self.user_ids[i])
            for i in range(len(STORYDATA))
        ]
        db.session.add_all(stories)
        db.session.commit()
        self.story_ids = [id for id in map(lambda story: story.id, stories)]

        chapters = [
            Chapter(**data, story_id=self.story_ids[0])
            for data in CHAPTERDATA1
        ]
        chapters += [
            Chapter(**data, story_id=self.story_ids[1])
            for data in CHAPTERDATA2
        ]
        chapters += [
            Chapter(**data, story_id=self.story_ids[2])
            for data in CHAPTERDATA3
        ]
        db.session.add_all(chapters)
        db.session.commit()
        self.chapter_ids = [
            id for id in map(lambda chapter: chapter.id, chapters)
        ]

        self.client = app.test_client()
Пример #42
0
def download_user_story(username):
    profile = instaloader.Profile.from_username(L.context, username)
    for story in L.get_stories(userids=[profile.userid]):
        for item in story.get_items():
            folder_name = item.date_local.strftime("%Y-%m-%d")
            preview_file_name = item.date_utc.strftime(
                "%Y-%m-%d_%H-%M-%S_UTC.jpg")
            preview_src = 'http://localhost:3000/stories/{}/{}/{}'.format(
                item.owner_username, folder_name, preview_file_name)
            if item.is_video:
                story_type = 'video'
                length = 0
                file_name = item.date_utc.strftime("%Y-%m-%d_%H-%M-%S_UTC.mp4")
                src = 'http://localhost:3000/stories/{}/{}/{}'.format(
                    item.owner_username, folder_name, file_name)
            else:
                story_type = 'photo'
                length = 3
                file_name = item.date_utc.strftime("%Y-%m-%d_%H-%M-%S_UTC.jpg")
                src = 'http://localhost:3000/stories/{}/{}/{}'.format(
                    item.owner_username, folder_name, file_name)

            try:
                story = session.query(Story).filter(
                    Story.username == item.owner_profile.username,
                    Story.time == datetime.date(item.date_local)).one()
            except NoResultFound:
                story = Story(item.owner_profile.username,
                              datetime.date(item.date_local))
                session.add(story)
                session.commit()

            story_item = StoryItem(item.owner_id,
                                   item.owner_profile.profile_pic_url,
                                   item.owner_profile.username, item.mediaid,
                                   story.id, story_type, length, src,
                                   preview_src, '', '', item.date_local, False)
            session.add(story_item)
            session.commit()
            L.download_storyitem(
                item,
                Path('stories/{}/{}'.format(item.owner_username, folder_name)))
Пример #43
0
    def get(self, story_id):

        story = Story.get_by_story_id(story_id)

        if story is None:
            logging.info('creating story ' + story_id)
            story = Story(story_id=story_id, user = users.get_current_user(), name=story_id)
            story.put()

        story_lines = story.story_lines()

        java_days = story.actual_java_days()
        cs_days = story.actual_cs_days()

        appengineutils.render_template(self.response, 'story_history.html', {'story_lines': story_lines,
                                                                'dates': last_five_days(),
                                                                'java_days': java_days,
                                                                'cs_days': cs_days,
                                                                'story': story})
Пример #44
0
    def post(self, story_id):

        story = Story.get_by_story_id(story_id)

        date_match = re.search(r'(\d\d\d\d)-(\d\d)-(\d\d)', self.request.get('date'))
        year = int(date_match.group(1))
        month = int(date_match.group(2))
        day = int(date_match.group(3))
        date = datetime.date(year, month, day)
        java_hours = int(self.request.get('java_hours'))
        cs_hours = int(self.request.get('cs_hours'))
        comment = self.request.get('comment')
        
        story_line = StoryLine(story_id=story_id,
                               comment=comment,
                               date=date,
                               user=users.get_current_user(),
                               java_hours=java_hours,
                               cs_hours=cs_hours,
                               parent=story)
        
        story_line.put()
        story.last_updated = story_line.date
        story.put()

        java_days = story.actual_java_days()
        cs_days = story.actual_cs_days()

        if story.java_estimate > 0 and story.java_estimate < java_days:
            logging.warn("Over java estimate")

        if story.cs_estimate > 0 and story.cs_estimate < cs_days:
            logging.warn("Over cs estimate")


        self.redirect('/s/' + story_id)
Пример #45
0
    def get(self, story_id):

        story = Story.get_by_story_id(story_id)

        appengineutils.render_template(self.response, 'story.html', {"story" : story,
                                                                      "estimate_options": range(0, 11)})
Пример #46
0
 def get(self):
   stories = Story.query().fetch()
   self.render_html('home.html',
                    stories=stories)
Пример #47
0
 def _accept_story(self, event):
     logging.info('Accepting story: ' + event.story_id)
     story = Story.get_by_story_id(event.story_id)
     story.date_accepted = event.accepted_date
     story.put()
Пример #48
0
 def items(self):
     return Story.objects.filter(Story.permission_to_view_Q())
Пример #49
0
 def post(self):
   if not self.user:
     self.redirect(users.create_login_url(path_for('Home')))
     return
   story = Story.create(self.user)
   self.redirect(path_for('EditPage', story.key.id(), story.page1_key.id()))