Пример #1
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)
Пример #2
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")
Пример #3
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()
Пример #4
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
Пример #5
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
Пример #6
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
Пример #7
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()
Пример #8
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})
Пример #9
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
Пример #10
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)
Пример #11
0
def create_story(request):
	token = getToken(request.META)
	user = getUser(token)

	if(not user):
		return Response(status=status.HTTP_403_FORBIDDEN)

	serialized = StorySerializer(data=request.DATA)

	if(serialized.is_valid):
		story = Story()
		story.title = serialized.initial_data['title']
		story.content = serialized.initial_data['content']
		story.save()

		return Response(status=status.HTTP_201_CREATED)
	else:
		return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
Пример #12
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()
Пример #13
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)))
Пример #14
0
def create_post(request):
    post_id = request.POST.get('post_id')
    title = request.POST.get('title')

    desc = request.POST.get('desc')
    postTitle = request.POST.get(post_id)
    storyTitle = request.POST.get('storyTitle')
    storyDesc = request.POST.get('storyDesc')

    post = Post()
    story = Story()

    #	postTitle =

    post.title = title
    post.desc = desc
    post.save()

    story.storyTitle = storyTitle
    story.storyDesc = storyDesc
    story.save()
    return HttpResponse(title + " " + desc + " " + storyTitle + " " +
                        storyDesc)
Пример #15
0
def add_new_story():
    if request.method == 'POST':
        author_id = request.cookies.get('cookie')
        if not author_id:
            author_id = str(uuid.uuid4())
        story_uid = str(uuid.uuid4())
        story_title = request.form.get('header')
        story_signature = request.form.get('signature')
        story_body = request.form.get('body')
        story_slug = get_random_slug()
        db.session.add(
            Story(story_slug=story_slug,
                  story_title=story_title,
                  story_signature=story_signature,
                  story_body=story_body,
                  story_uid=story_uid,
                  author_id=author_id))
        db.session.commit()
        new_story = make_response(
            redirect(url_for('view_story', story_slug=story_slug)))
        new_story.set_cookie('author_id', author_id, max_age=MAX_COOKIES_AGE)
        return new_story
    else:
        return render_template('form.html')
Пример #16
0
def lease_story_for_contribution(user_id):
    """
    Either:
     1. An unexpired lease belonging to this user
     2. Find a still-in-progress story that this user
        hasn't contributed to, or
     3. Create a new story.
    Then, create a new Fragment with a null word
    'created_by' this user. This empty Fragment will
    represent the user's claim of being the next person
    to contribute to that story.
    """
    existing_lease = Fragment.query.filter(
        Fragment.created_by == user_id,
        Fragment.word == None,
        Fragment.created_at >= text("CURRENT_TIMESTAMP - interval '{} second'".
                                    format(EXPIRY_IN_SECONDS)),
    ).first()
    if existing_lease is not None:
        story = Story.query.get(existing_lease.story_id)
        return {
            'story_id':
            story.id,
            'num_words':
            story.num_words,
            'words': [f.word for f in story.fragments if f.word is not None],
            'expires_at':
            existing_lease.created_at +
            datetime.timedelta(seconds=EXPIRY_IN_SECONDS),
        }

    story_id = db.session.execute(
        """
        SELECT MIN(s.id) AS story_id
        FROM story s
        JOIN fragment f ON (f.story_id = s.id)
        GROUP BY s.id
        HAVING
          -- story is incomplete
            s.num_words > COUNT(f.id)
          -- logged in user was not most recent contributor
           AND :user_id <> (ARRAY_AGG(f.created_by))[
               array_upper(ARRAY_AGG(f.created_by), 1)
            ]
          -- no outstanding lease on this story
           AND BOOL_AND(f.word IS NOT NULL)
        """, {
            'user_id': user_id
        }).scalar()
    if story_id:
        story = Story.query.get(story_id)
    else:
        story = Story(num_words=rand_num_words())
        db.session.add(story)
    fragment = Fragment(created_by=user_id)
    story.fragments.append(fragment)
    db.session.commit()
    return {
        'story_id':
        story.id,
        'num_words':
        story.num_words,
        'words': [f.word for f in story.fragments if f.word is not None],
        'expires_at':
        fragment.created_at + datetime.timedelta(seconds=EXPIRY_IN_SECONDS),
    }
Пример #17
0
    def post(self):

        rStory = Story(title=self.request.get("adventure_name"))
        rStory.put()

        storypoint1 = StoryPoint(story_key=rStory.key,
                                 text=self.request.get("first_story_point"))
        storypoint2 = StoryPoint(story_key=rStory.key,
                                 text=self.request.get("choiceA_story_point"))
        storypoint3 = StoryPoint(story_key=rStory.key,
                                 text=self.request.get("choiceB_story_point"))
        storypoint4 = StoryPoint(story_key=rStory.key,
                                 text=self.request.get("choiceC_story_point"))
        storypoint5 = StoryPoint(story_key=rStory.key,
                                 text=self.request.get("choiceD_story_point"))
        storypoint6 = StoryPoint(story_key=rStory.key,
                                 text=self.request.get("choiceE_story_point"))
        storypoint7 = StoryPoint(story_key=rStory.key,
                                 text=self.request.get("choiceF_story_point"))
        storypoint8 = StoryPoint(story_key=rStory.key,
                                 text=self.request.get("choiceG_story_point"))
        storypoint9 = StoryPoint(story_key=rStory.key,
                                 text=self.request.get("choiceH_story_point"))
        storypoint10 = StoryPoint(story_key=rStory.key,
                                  text=self.request.get("choiceI_story_point"))
        storypoint11 = StoryPoint(story_key=rStory.key,
                                  text=self.request.get("choiceJ_story_point"))
        storypoint12 = StoryPoint(story_key=rStory.key,
                                  text=self.request.get("choiceK_story_point"))
        storypoint13 = StoryPoint(story_key=rStory.key,
                                  text=self.request.get("choiceL_story_point"))

        storypoint1.put()
        storypoint2.put()
        storypoint3.put()
        storypoint4.put()
        storypoint5.put()
        storypoint6.put()
        storypoint7.put()
        storypoint8.put()
        storypoint9.put()
        storypoint10.put()
        storypoint11.put()
        storypoint12.put()
        storypoint13.put()

        rStory.first_story_point_key = storypoint1.key

        rStory.put()

        choicepoint1 = ChoicePoint(begin_story_point_key=storypoint1.key,
                                   end_story_point_key=storypoint2.key,
                                   text=self.request.get("Choice_A"))
        choicepoint2 = ChoicePoint(begin_story_point_key=storypoint1.key,
                                   end_story_point_key=storypoint3.key,
                                   text=self.request.get("Choice_B"))
        choicepoint3 = ChoicePoint(begin_story_point_key=storypoint2.key,
                                   end_story_point_key=storypoint4.key,
                                   text=self.request.get("Choice_C"))
        choicepoint4 = ChoicePoint(begin_story_point_key=storypoint2.key,
                                   end_story_point_key=storypoint5.key,
                                   text=self.request.get("Choice_D"))
        choicepoint5 = ChoicePoint(begin_story_point_key=storypoint3.key,
                                   end_story_point_key=storypoint6.key,
                                   text=self.request.get("Choice_E"))
        choicepoint6 = ChoicePoint(begin_story_point_key=storypoint3.key,
                                   end_story_point_key=storypoint7.key,
                                   text=self.request.get("Choice_F"))
        choicepoint7 = ChoicePoint(begin_story_point_key=storypoint4.key,
                                   end_story_point_key=storypoint8.key,
                                   text=self.request.get("Choice_G"))
        choicepoint8 = ChoicePoint(begin_story_point_key=storypoint4.key,
                                   end_story_point_key=storypoint9.key,
                                   text=self.request.get("Choice_H"))
        choicepoint9 = ChoicePoint(begin_story_point_key=storypoint6.key,
                                   end_story_point_key=storypoint10.key,
                                   text=self.request.get("Choice_I"))
        choicepoint10 = ChoicePoint(begin_story_point_key=storypoint6.key,
                                    end_story_point_key=storypoint11.key,
                                    text=self.request.get("Choice_J"))
        choicepoint11 = ChoicePoint(begin_story_point_key=storypoint7.key,
                                    end_story_point_key=storypoint12.key,
                                    text=self.request.get("Choice_K"))
        choicepoint12 = ChoicePoint(begin_story_point_key=storypoint7.key,
                                    end_story_point_key=storypoint13.key,
                                    text=self.request.get("Choice_L"))

        rStory.put()

        storypoint1.put()
        storypoint2.put()
        storypoint3.put()
        storypoint4.put()
        storypoint5.put()
        storypoint6.put()
        storypoint7.put()
        storypoint8.put()
        storypoint9.put()
        storypoint10.put()
        storypoint11.put()
        storypoint12.put()
        storypoint13.put()

        choicepoint1.put()
        choicepoint2.put()
        choicepoint3.put()
        choicepoint4.put()
        choicepoint5.put()
        choicepoint6.put()
        choicepoint7.put()
        choicepoint8.put()
        choicepoint9.put()
        choicepoint10.put()
        choicepoint11.put()
        choicepoint12.put()

        display_dictionary = {
            "display_title": rStory.title,
            "display_sp_1": storypoint1.text,
            "display_sp_2": storypoint2.text,
            "display_sp_3": storypoint3.text,
            "display_sp_4": storypoint4.text,
            "display_sp_5": storypoint5.text,
            "display_sp_6": storypoint6.text,
            "display_sp_7": storypoint7.text,
            "display_sp_8": storypoint8.text,
            "display_sp_9": storypoint9.text,
            "display_sp_10": storypoint10.text,
            "display_sp_11": storypoint11.text,
            "display_sp_12": storypoint12.text,
            "display_sp_13": storypoint13.text,
            "display_cp_1": choicepoint1.text,
            "cp1_next_key": choicepoint1.end_story_point_key.id(),
            "display_cp_2": choicepoint2.text,
            "cp2_next_key": choicepoint2.end_story_point_key.id(),
            "display_cp_3": choicepoint3.text,
            "display_cp_4": choicepoint4.text,
            "display_cp_5": choicepoint5.text,
            "display_cp_6": choicepoint6.text,
            "display_cp_7": choicepoint7.text,
            "display_cp_8": choicepoint8.text,
            "display_cp_9": choicepoint9.text,
            "display_cp_10": choicepoint10.text,
            "display_cp_11": choicepoint11.text,
            "display_cp_12": choicepoint12.text,
        }

        result_template = jinjaEnv.get_template("result.html")
        #self.response.write(result_template.render())
        self.response.write(result_template.render(display_dictionary))
Пример #18
0
def newspaperize(article_url):
    """Takes a string url that contains an article. Returns a Story object from 
    models.py containing information scraped from the article located at the url."""

    article = Article(article_url)  # create Article object

    print("Downloading:", article_url)

    try:  # returns None if url fails to download
        article.download()
    except:
        print("Failed to download url:", article_url)
        return None

    try:  # returns None if url cannot be parsed
        article.parse()
    except:
        print("Failed to parse url:", article_url)
        return None

    article.nlp()

    # variables to hold values for Story attributes
    headline = article.title
    imageurl = article.top_image
    timestamp = article.publish_date
    content = article.text
    keywords = article.keywords
    summary = article.summary
    description = article.meta_description
    clickbait = -1  # placeholder for clickbait label

    # populates keyword object with article.keywords
    list_of_keyword_obj = []
    for word in keywords:
        if word not in stopword:  # prevents stopwords from being keywords
            k = Keyword()
            k.keyword = word
            list_of_keyword_obj.append(k)

    s = Story()  # create Story object

    # set attributes
    s.name = headline
    s.imageurl = imageurl
    s.url = article_url
    current_time = datetime.datetime.now()

    if timestamp is not None:
        s.timestamp = timestamp.isoformat()
    else:  # generate timestamp if none found
        s.timestamp = current_time

    s.description = description
    s.keywords = list_of_keyword_obj
    s.summary = summary
    s.content = content
    s.clickbait = clickbait
    s.createtime = current_time

    return s