예제 #1
0
파일: app.py 프로젝트: S-bite/marathon_web
def submit():
    if current_user.is_authenticated == False:
        return render_template("submit.html")
    if request.method == 'POST':
        """
        ↓は本当に最悪です 本当は "file" in request.filesみたいな感じで判定をしたかったのですが、
        たとえファイルが選択されていない状態であってもImmutableMultiDict([('file', <FileStorage: '' ('application/octet-stream')>)])
        がrequest.filesとして送られてくるのを直せませんでした…(解決方法を知っている方がいれば教えてください…)
        """
        if request.files["file"].filename == "":
            flash('ファイルが選択されていません', category='alert alert-danger')
            return redirect("/submit")
        answer = ""
        try:
            answer = request.files["file"].read().decode("UTF-8")
        except:
            flash('不正なファイルです。ファイルのエンコードはUTF-8である必要があります',
                  category='alert alert-danger')
            return redirect("/submit")
        sub = Submission()
        sub.username = current_user.username
        sub.move = answer
        sub.submitdate = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        db.session.add(sub)
        db.session.commit()
        flash("提出しました。少し時間をおいてリロードしてください", category='alert alert-success')
        return redirect("/submissions/me")
    else:
        return render_template("submit.html")
예제 #2
0
    def fetch_submission(self, slug):
        print(f"🤖 Fetching submission for problem: {slug}")
        query_params = {
            'operationName': "Submissions",
            'variables': {"offset": 0, "limit": 20, "lastKey": '', "questionSlug": slug},
            'query': '''query Submissions($offset: Int!, $limit: Int!, $lastKey: String, $questionSlug: String!) {
                                        submissionList(offset: $offset, limit: $limit, lastKey: $lastKey, questionSlug: $questionSlug) {
                                        lastKey
                                        hasNext
                                        submissions {
                                            id
                                            statusDisplay
                                            lang
                                            runtime
                                            timestamp
                                            url
                                            isPending
                                            __typename
                                        }
                                        __typename
                                    }
                                }'''
        }

        resp = self.session.post("https://leetcode.com/graphql",
                                 data=json.dumps(query_params).encode('utf8'),
                                 headers={
                                     "content-type": "application/json",
                                 })
        body = json.loads(resp.content)

        # parse data
        submissions = get(body, "data.submissionList.submissions")
        if len(submissions) > 0:
            for sub in submissions:
                if Submission.get_or_none(Submission.id == sub['id']) is not None:
                    continue

                if sub['statusDisplay'] == 'Accepted':
                    url = sub['url']
                    html = self.session.get(f'https://leetcode.com{url}').text

                    pattern = re.compile(
                        r'submissionCode: \'(?P<code>.*)\',\n  editCodeUrl', re.S
                    )

                    matched = pattern.search(html)
                    code = matched.groupdict().get('code') if matched else None
                    if code:
                        Submission.insert(
                            id=sub['id'],
                            slug=slug,
                            language=sub['lang'],
                            created=sub['timestamp'],
                            source=code.encode('utf-8')
                        ).execute()
                    else:
                        raise Exception(f"Cannot get submission code for problem: {slug}")
        random_wait(10, 15)
예제 #3
0
def add_submission(subreddit, database, db_submission, reddit_submission):
	flair_restricted = subreddit.flair_restricted(reddit_submission.link_flair_text)
	reprocess_submission = False
	if db_submission is None:
		db_submission = Submission(
			submission_id=reddit_submission.id,
			created=datetime.utcfromtimestamp(reddit_submission.created_utc),
			is_restricted=flair_restricted
		)
		database.session.add(db_submission)
		reprocess_submission = flair_restricted

	elif db_submission.is_restricted is not flair_restricted:
		db_submission.is_restricted = flair_restricted
		reprocess_submission = flair_restricted

	if reprocess_submission:
		log.info(f"Marking submission {reddit_submission.id} as restricted")
		if subreddit.restricted['action'] == "remove":
			bot_comment = reddit_submission.reply(
				"Due to the topic, enhanced moderation has been turned on for this thread. Comments from users new "
				"to r/bayarea will be automatically removed. See [this thread](https://www.reddit.com/r/bayarea/comments/p8hnzl/automatically_removing_comments_from_new_users_in/) for more details.")
			try:
				bot_comment.mod.approve()
			except prawcore.exceptions.Forbidden:
				log.warning(f"Failed to approve comment, forbidden")
				if subreddit.backup_reddit is not None:
					try:
						subreddit.backup_reddit.comment(id=bot_comment.id).mod.approve()
						log.warning(f"Approved comment with backup reddit")
					except Exception as e:
						log.warning(f"Failed to approve comment with backup reddit, {e}")

			bot_comment.mod.distinguish(how="yes", sticky=True)

		good_comments, bad_comments = get_comments_for_thread(subreddit, database, reddit_submission.id)
		if len(bad_comments) + len(good_comments) > 0:
			log.info(f"Reprocessing submission {reddit_submission.id} with {len(good_comments) + len(bad_comments)} comments")
			for comment, author_result in bad_comments:
				action_comment(subreddit, comment, author_result)
			log.warning(f"Finished submission <https://www.reddit.com{reddit_submission.permalink}>, removed {len(bad_comments)}/{len(good_comments) + len(bad_comments)} comments")

	return db_submission
예제 #4
0
 def post(self, course_id, assignment_id):
     "Submit a copy of an assignment (students+instructors)"
     course = self.find_course(course_id)
     self.check_course_user(course)
     assignment = self.find_assignment(course, assignment_id)
     submission = Submission(self.user, assignment)
     files = self.get_body_argument("files", None)
     self.json_files_unpack(files, submission.files)
     self.db.commit()
     self.json_success(timestamp=self.strftime(submission.timestamp))
예제 #5
0
    database_prod = Database("database_prod.db")

    comments = database_new.session.query(Comment).all()
    count = 0
    total_comments = len(comments)
    new_submissions = 0
    new_users = 0
    log.info(f"{count}/{total_comments}: {new_submissions}|{new_users}")

    for comment in comments:
        db_submission = database_prod.session.query(Submission).filter_by(
            submission_id=comment.submission_id).first()
        if db_submission is None:
            new_submissions += 1
            db_submission = Submission(submission_id=comment.submission_id,
                                       created=comment.created,
                                       is_restricted=False)
            database_prod.session.add(db_submission)

        comment_author_name = comment.author.name
        db_user = database_prod.session.query(User).filter_by(
            name=comment_author_name).first()
        if db_user is None:
            new_users += 1
            db_user = database_prod.session.merge(
                User(name=comment_author_name))
        database_prod.session.merge(
            Comment(comment_id=comment.comment_id,
                    author=db_user,
                    submission=db_submission,
                    created=comment.created,
예제 #6
0
from database import db, Submission
from genMove import genMove
db.create_all()

for i in range(1000):
    sub = Submission()
    sub.username = '******' + str((i % 100))
    sub.move = genMove()
    db.session.add(sub)
    db.session.commit()
예제 #7
0
def add_submission(subreddit, database, db_submission, reddit_submission):
    flair_restricted = subreddit.flair_restricted(
        reddit_submission.link_flair_text)
    reprocess_submission = False
    if db_submission is None:
        db_submission = Submission(submission_id=reddit_submission.id,
                                   created=datetime.utcfromtimestamp(
                                       reddit_submission.created_utc),
                                   is_restricted=flair_restricted)
        database.session.add(db_submission)
        reprocess_submission = flair_restricted

    elif db_submission.is_restricted is not flair_restricted:
        db_submission.is_restricted = flair_restricted
        reprocess_submission = flair_restricted

    if reprocess_submission:
        log.info(f"Marking submission {reddit_submission.id} as restricted")
        bot_comment = reddit_submission.reply(
            "Due to the topic, enhanced moderation has been turned on for this thread. Comments from users new "
            "to r/bayarea will be automatically removed. See [this thread](https://www.reddit.com/r/bayarea/comments/p8hnzl/automatically_removing_comments_from_new_users_in/) for more details."
        )
        try:
            bot_comment.mod.approve()
        except prawcore.exceptions.Forbidden:
            log.warning(f"Failed to approve comment, forbidden")
            if subreddit.backup_reddit is not None:
                try:
                    subreddit.backup_reddit.comment(
                        id=bot_comment.id).mod.approve()
                    log.warning(f"Approved comment with backup reddit")
                except Exception as e:
                    log.warning(
                        f"Failed to approve comment with backup reddit, {e}")

        bot_comment.mod.distinguish(how="yes", sticky=True)

        comments = database.session.query(Comment)\
         .join(Submission)\
         .filter(Submission.submission_id == reddit_submission.id)\
         .all()
        if len(comments) > 0:
            log.info(
                f"Reprocessing submission {reddit_submission.id} with {len(comments)} comments"
            )
            author_dict = {}
            count_removed = 0
            for comment in comments:
                if comment.author.name in author_dict:
                    author_result = author_dict[comment.author.name]
                else:
                    author_result = author_restricted(subreddit, database,
                                                      comment.author)
                    author_dict[comment.author.name] = author_result

                if author_result is None or comment.author.name == "CustomModBot":
                    continue
                else:
                    subreddit.reddit.comment(comment.comment_id).mod.remove(
                        mod_note=f"filtered: {author_result}")
                    comment.is_removed = True
                    count_removed += 1
                    log.info(
                        f"Comment {comment.comment_id} by u/{comment.author.name} removed: {author_result}"
                    )
            log.warning(
                f"Finished submission <https://www.reddit.com{reddit_submission.permalink}>, removed {count_removed}/{len(comments)} comments"
            )

    return db_submission