Example #1
0
def recursive_copy_topic_list_structure(parent, topic_list_part):
    delete_topics = {}
    for topic_dict in topic_list_part:
        logging.info(topic_dict["name"])
        if "playlist" in topic_dict:
            topic = Topic.get_by_title_and_parent(topic_dict["name"], parent)
            if topic:
                logging.info(topic_dict["name"] + " is already created")
            else:
                version = TopicVersion.get_edit_version()
                root = Topic.get_root(version)
                topic = Topic.get_by_title_and_parent(topic_dict["playlist"], root)
                if topic:
                    delete_topics[topic.key()] = topic
                    logging.info("copying %s to parent %s" %
                                (topic_dict["name"], parent.title))
                    topic.copy(title=topic_dict["name"], parent=parent,
                               standalone_title=topic.title)
                else:
                    logging.error("Topic not found! %s" % (topic_dict["playlist"]))
        else:
            topic = Topic.get_by_title_and_parent(topic_dict["name"], parent)
            if topic:
                logging.info(topic_dict["name"] + " is already created")
            else:
                logging.info("adding %s to parent %s" %
                             (topic_dict["name"], parent.title))
                topic = Topic.insert(title=topic_dict["name"], parent=parent)

        if "items" in topic_dict:
            delete_topics.update(
                recursive_copy_topic_list_structure(topic,
                                                    topic_dict["items"]))

    return delete_topics
Example #2
0
File: __init__.py Project: QFAPP/QF
    def store(self, topic_name, article_entry_list):
        """Stores the article entries in the database.

        :param topic_name The name of the topic
        :param article_entry_list The list of entries of this topic
        """

        try:
            # Try to retrieve the topic to see if it exists already
            topic = Topic.get(Topic.name == topic_name)
        except Topic.DoesNotExist:
            # If not, create it
            topic = Topic.create(name=topic_name)

        # Go through all the articles in this topic
        for article_entry in article_entry_list:
            article_name = article_entry.subject

            # If there is no subject, it means the article is corrupted
            # therefore we skip it
            if not article_name:
                continue

            # Create the files with the content
            # Overwrite existing files
            try:
                Article.create(topic=topic, subject=article_name,
                               body=article_entry.body)
            except Article.DoesNotExist:
                pass
Example #3
0
    def post(self):
        creator = users.get_current_user()
        title = self.request.get('title')
        descrip = self.request.get('descrip')

        start = util.convert_htmldatetime(self.request.get('start'))
        end = util.convert_htmldatetime(self.request.get('end'))
        slot_minutes = int(self.request.get('slot_minutes'))

        topic = Topic(
            creator=creator,
            title=title,
            descrip=descrip,
            start=start,
            end=end,
            slot_minutes=slot_minutes)
        topic.put()

        # Now create slots
        current_slot = start
        while (current_slot < end):
            slot = TopicSlot(start=current_slot, topic=topic)
            slot.put()
            current_slot += datetime.timedelta(minutes=slot_minutes)
        self.redirect(topic.full_link)
Example #4
0
 def save(self):
     topic_post = False
     if not self.topic:
         topic_type = self.cleaned_data['topic_type']
         if topic_type:
             topic_type = TopicType.objects.get(id=topic_type)
         else:
             topic_type = None
         topic = Topic(forum=self.forum,
                       posted_by=self.user,
                       subject=self.cleaned_data['subject'],
                       need_replay=self.cleaned_data['need_replay'],
                       need_reply_attachments=self.cleaned_data['need_reply_attachments'],
                       topic_type=topic_type,
                       )
         topic_post = True
         topic.save()
     else:
         topic = self.topic
     post = Post(topic=topic, posted_by=self.user, poster_ip=self.ip,
                 message=self.cleaned_data['message'], topic_post=topic_post)
     post.save()
     attachments = self.cleaned_data['attachments']
     post.update_attachments(attachments)
     return post
Example #5
0
 def save(self):
     topic_post = False
     if not self.topic:
         topic_type = self.cleaned_data['topic_type']
         if topic_type:
             topic_type = TopicType.objects.get(id=topic_type)
         else:
             topic_type = None
         topic = Topic(
             forum=self.forum,
             posted_by=self.user,
             subject=self.cleaned_data['subject'],
             need_replay=self.cleaned_data['need_replay'],
             need_reply_attachments=self.
             cleaned_data['need_reply_attachments'],
             topic_type=topic_type,
         )
         topic_post = True
         topic.save()
     else:
         topic = self.topic
     post = Post(topic=topic,
                 posted_by=self.user,
                 poster_ip=self.ip,
                 message=self.cleaned_data['message'],
                 topic_post=topic_post)
     post.save()
     attachments = self.cleaned_data['attachments']
     post.update_attachments(attachments)
     return post
Example #6
0
def get_topic(id, user=None):
    """Gets a single topic (formatted by json_data) from redis or postgresql
    And performs some pre-filters for the current user
    Args:
        id (int): id
        user (User): the current user
    Returns:
        None if the topic is not existed or a dict of topic data
    """
    id = int(id)
    key = Topic.cache_key(id)
    redis_client = get_client(key)

    topic = None
    if not redis_client.exists(key):
        topic = Topic.find_by_pk(id)
        if topic:
            data = topic.json_data()
            redis_client.set(key, json.dumps(data))
            topic = data
    else:
        if redis_client.type(key) == 'hash':
            print redis_client
        topic = json.loads(redis_client.get(key))

    topic['user_vote'] = Topic.check_vote(user, topic['id'])

    return topic
Example #7
0
def new_topic(request, gname):
    '''
		login user add a new topic
	'''
    vars = {}
    group = Group.objects.get(name=gname)
    vars['group'] = group
    if request.method == "POST":
        rev_title = request.POST.get("rev_title", "")
        rev_text = request.POST.get("rev_text", "")
        image_names = request.POST.get("image_names", "")
        if rev_text == "" or rev_title == '':
            vars["msg"] = "标题和内容不能不写啊"
            return render(request, 'new_topic.html', vars)
        images = image_names.split("|")[:-1]
        image_str = ""
        for im in images:
            image_str += "%s<br/>" % im
        rev_text = image_str + ">>>>||>>>>" + rev_text
        topic = Topic(name=rev_title, content=rev_text, group=group, creator=request.user)
        topic.save()
        topic_amount = Topic_reply_amount(topic=topic, amount=0)
        topic_amount.save()
        return redirect("topic", id=topic.id)
    return render(request, 'new_topic.html', vars)
Example #8
0
def new_topic(request,gname):
	'''
		login user add a new topic
	'''
	vars = {}
	group = Group.objects.get(name=gname)
	vars['group'] = group
	if request.method == "POST":
		rev_title = request.POST.get("rev_title","")
		rev_text  = request.POST.get("rev_text","")
		image_names = request.POST.get("image_names","")
		if rev_text == "" or rev_title == '':
			vars["msg"] = "标题和内容不能不写啊"
			return render(request,'new_topic.html',vars)
		images =  image_names.split("|")[:-1]
		image_str = ""
		for im in images:
			image_str += "%s<br/>"%im
		rev_text = image_str+">>>>||>>>>"+rev_text
		topic = Topic(name=rev_title,content=rev_text,group=group,creator=request.user)
		topic.save()
		topic_amount = Topic_reply_amount(topic=topic,amount=0)
		topic_amount.save()
		return redirect("topic",id=topic.id)
	return render(request,'new_topic.html',vars)
Example #9
0
def addtopic(t_id):
    form = InputOfTopic()
    if t_id != 0:
        topic = Topic.getById(t_id)
        form.content.data = topic.content
        form.title.data = topic.title
    if form.validate_on_submit():
        flag_id = request.form['radioInline']
        title = form.title.data
        content = form.content.data
        if t_id != 0:
            sess.query(Topic).filter(Topic.id == t_id).update({
                Topic.content:
                content,
                Topic.author:
                g.user.id,
                Topic.title:
                title,
                Topic.flag:
                flag_id
            })
        else:
            sess.add(
                Topic(id=0,
                      content=content,
                      author=g.user.id,
                      title=title,
                      flag=flag_id))
        sess.commit()
        return redirect('/bbslist/0')
    return render_template('add_topic.html', user=g.user, form=form)
Example #10
0
    def insert_message(self, msg, device):
        if msg["device_tag"] and msg["keys"] and msg["values"] and msg[
                "device_topic"]:
            device_tag = str(msg["device_tag"])
            device_topic = str(msg["device_topic"])
            db_t = TinyDB('device_data/' + device.tag + "/" + device_tag +
                          ".json")
            table = db_t.table(str(msg["device_topic"]))
            values = {}
            value = 0
            for key in msg["keys"]:
                values[key] = msg["values"][value]
                value += 1
            values["time"] = msg["time"]
            table.insert(values)
            topic = Topic.query.filter_by(topic=device_topic).first()
            device = Device.query.filter_by(tag=device_tag).first()
            if topic is None:
                topic = Topic(topic=device_topic, active_devices=1)
            else:
                add = True
                for top_dev in device.topics:
                    if top_dev.topic == topic.topic:
                        add = False
                if add:
                    topic.active_devices += 1
                topic.last_update = datetime.utcnow()

            device.topics.append(topic)
            db.session.add(device)
            db.session.commit()
Example #11
0
class TopicTestCase(ViewableTestCase):
    test_model = Topic

    def setUp(self):
        super(TopicTestCase, self).setUp()
        self.user = User.objects.create_user('john', '*****@*****.**', 'lennon')
        self.test_object = Topic(name='An instance', user=self.user)
        self.test_object.save()
Example #12
0
def writeTopic(request):
	topic_name = request.POST['topic']
	sender_name = request.POST['name']		
	topic_record = Topic()
	topic_record.sender_name = sender_name
	topic_record.topic_name = topic_name
	topic_record.save()
	return HttpResponse("ok");
Example #13
0
class AddTopicForm(AddPostForm):
    name = forms.CharField(label=_('Subject'), max_length=255)

    def save(self):
        self.topic = Topic(forum=self.forum,
                           user=self.user,
                           name=self.cleaned_data['name'])
        self.topic.save()
        return super(AddTopicForm, self).save()
Example #14
0
class AddTopicForm(AddPostForm):
    name = forms.CharField(label=_('Subject'), max_length=255)
    
    def save(self):
        self.topic = Topic(forum=self.forum,
                      user=self.user,
                      name=self.cleaned_data['name'])
        self.topic.save()
        return super(AddTopicForm, self).save()
Example #15
0
	def test_postSave(self):
		a = Topic(name='My special topic')
		a.save()
		# For each topic in the Topic model we need a self
		# referencing element in the closure table.
		topics = Topic.objects.all()
		for topic in topics:
			ct = Topic.index._ctModel.objects.get(ancestor=topic)
			self.assertTrue(ct.ancestor == ct.descendant and ct.path_length == 0)
Example #16
0
 def test_postSave(self):
     a = Topic(name='My special topic')
     a.save()
     # For each topic in the Topic model we need a self
     # referencing element in the closure table.
     topics = Topic.objects.all()
     for topic in topics:
         ct = Topic.index._ctModel.objects.get(ancestor=topic)
         self.assertTrue(ct.ancestor == ct.descendant
                         and ct.path_length == 0)
Example #17
0
 def saveTopic(self):
     topic = Topic()
     topic.class_type = self.class_type.data
     topic.class_id = int(self.class_id.data)
     topic.subject = self.subject.data
     topic.content = self.content.data
     topic.project_id = self.project.id
     topic.user_id = self.user.id
     current_time = int(time.time())
     topic.created_at = current_time
     topic.updated_at = current_time
     db.session.add(topic)
     db.session.commit()
     project = topic.project
     for atta_id in self.attachments:
         atta = Attachment.query.get(atta_id)
         atta.topic_id = topic.id
         atta.project_id = topic.project_id
         atta.root_class = topic.class_type
         if topic.class_id == 0:
             atta.root_id = topic.id
         else:
             atta.root_id = topic.class_id
         db.session.commit()
         project.file_count += 1
     db.session.commit()
     return topic
Example #18
0
 def pyforum_view(self):
     topics = Topic.objects
     form = Form(self.request,schema=TopicSchema())
     if form.validate():
         context = {'title' : form.data['title']}
         Topic.add(context)
         return HTTPFound(location='/list')
     return {'title': 'List View PyForum',
             'topics':topics,
             'form' : FormRenderer(form)
         }
Example #19
0
def discussion(topic_key):
    messages = None
    if topic_key:
        topic = Topic.get(topic_key)
        if not topic:
            flash('No topic found', 'error')
            return redirect(url_for('index'))
        child_topics = []
        for child_topic_key in topic.child_topics:
            child_topics.append(Topic.get(child_topic_key))
        messages = Message.all().filter('topic', topic).order('-created_at').fetch(limit=50)
    return render_template('discussion.html', messages=messages, topic=topic, child_topics=child_topics)
Example #20
0
def bbs_list(id):
    if id == 0:
        topic = Topic.getAll()
    else:
        topic = Topic.getByFlag(id)
    return render_template('bulletin_board_list.html',
                           user=g.user,
                           topic=topic,
                           NameList=NameList,
                           User=User,
                           cur_page='bbs',
                           comment_topic=Comment_Topic)
Example #21
0
def addTopic(inTitle):
    try:
        existingTopic = Topic.objects.get(title=inTitle)
        return False
    except Topic.DoesNotExist: #this is a good thing! We can create an topic now!
        newTopic = Topic()
        newTopic.title = inTitle
        newTopic.save()
        return newTopic
    
    

        
Example #22
0
def save_topic(data_dict):
    topic_list = Topic.objects.filter(title=data_dict['title'])
    
    if topic_list.count() == 0:
        t = Topic(title=data_dict['title'])
        t.image_url = data_dict['image']
        t.link = data_dict['link']
        t.desc = data_dict['desc']
        t.date = data_dict['date']
        t.user = data_dict['user']
        t.clicked=data_dict['clicked']
        t.comments = data_dict['comments']
        t.save()
Example #23
0
def publish_api(request):

    if request.method == 'POST':
        data = request.POST

       

        new_board = Board.objects.get(board_title=data['topic_board'])


        new_user = User.objects.get(email=data['topic_author'])
        new_user_profile = UserProfile.objects.get(user=new_user)

        new_tags = data['topic_tags'].split(',')



        new_topic = Topic(
                topic_status = data['topic_status'],
                topic_is_top = data['topic_is_top'],
                topic_title = data['topic_title'],
                topic_content = data['topic_content'],
                topic_board = new_board,
                topic_author =new_user_profile,
               
                topic_is_pub = data['topic_is_pub'],
                topic_final_comment_time = datetime.datetime.now(),
                topic_final_comment_user = new_user_profile,
            )

        new_topic.save()

        for tag in new_tags:
            if tag != '':
                t = Tag.objects.get(tag_name=tag)
                new_topic.topic_tag.add(t)
                new_topic.save()

        

        return HttpResponse(json.dumps({
                    'status':'success',
                    'id':new_topic.id,
                },ensure_ascii=False),content_type="application/json")

    else:
        tf = TopicForm()

    return HttpResponse(json.dumps({
                    'status':'not post',
                },ensure_ascii=False),content_type="application/json")
Example #24
0
def topic_new(request, template_name='private_messages/topic_new.html'):
    if request.method == 'POST':
        form = NewTopicForm(data=request.POST)
        if form.is_valid():
            message = form.save(commit=False)

            topic = Topic(sender=request.user)
            topic.recipient = form.cleaned_data['recipient']
            topic.subject = form.cleaned_data['subject']
            topic.last_sent_at = datetime.now()
            topic.save()

            message.topic = topic
            message.sender = request.user
            message.save()

            return HttpResponseRedirect(topic.get_absolute_url())
    else:
        initial = {}
        if request.GET.has_key('recipient'):
            initial['recipient'] = request.GET['recipient']

        form = NewTopicForm(initial=initial)

    return TemplateResponse(request, template_name, {
        'pm_form': form,
    })
Example #25
0
def new_topic(request, forum_slug):
    forum = get_object_or_404(Forum, slug=forum_slug)
    if request.method == 'GET':
        topic_form = TopicForm()
    elif request.method == 'POST':
        topic_form = TopicForm(request.POST)
        if topic_form.is_valid():
            data = topic_form.cleaned_data
            new_topic = Topic(forum=forum, title=data['title'], user=request.user)
            new_topic.save()
            new_post = Post(topic=new_topic, body=data['body'], user=request.user, ip_address=request.META.get('REMOTE_ADDR'))
            new_post.save()
            return HttpResponseRedirect(new_topic.get_absolute_url())
    return render_to_response('forum/topic_new.html', {'forum':forum, 'form':topic_form}, RequestContext(request))
Example #26
0
def topics(operation=None, topic_id=-1):
    form = NewTopicForm(request.form)

    if request.method == 'POST' and form.validate_on_submit():
        topic = Topic(name=form.topic.data)
        db.session.add(topic)
        db.session.commit()
        flash('New topic is created')
        return redirect(url_for('topics'))
    if operation == 'delete':
        try:
            topic = Topic().query.get(topic_id)
            db.session.delete(topic)
            db.session.commit()
        except:
            flash("Failed to delete topic {}.".format(topic_id))
        return redirect(url_for('topics'))
    if operation == 'update':
        try:
            topic = Topic().query.get(topic_id)
            topic.name = request.values.get("value")
            db.session.add(topic)
            db.session.commit()
        except:
            return 'Error renaming topic.', 400
        else:
            return 'Topic updted successfuly.', 200

    topics = Topic().query.all()
    return render_template('topics.html',
                           title='Topics',
                           form=form,
                           topics=topics)
Example #27
0
 def save(self):
     if not self.topic:
         ## caution I maybe will modified the name to
         ## tag in the future
         topic = Topic(tag = self.tag,
                 subject = self.cleaned_data['subject'],
                 posted_by = self.user,
                 )
         topic.save()
     else:
         topic = self.topic
     post = Post(topic=topic,tag = self.tag,posted_by=self.user,poster_ip=self.ip,content = self.cleaned_data['content'])
     post.save()
     return post
Example #28
0
def publish_topic():
    if request.method == 'GET':
        return render_template('publish_topic.html')
    else:
        title = request.form.get('title')
        content = request.form.get('content')
        topic = Topic(title=title, content=content)
        # 获得当前的用户id
        user_id = session.get('user_id')
        user = User.query.filter(User.id == user_id).first()
        topic.author = user
        db.session.add(topic)
        db.session.commit()
        # flash(u'发布成功') 页面跳转的太快了看不到
        return redirect(url_for('all_topic'))  # 这里原来是topic_detail
Example #29
0
def search():
    query = request.args.get('query')
    limit = int(request.args.get('limit', 10))
    offset = int(request.args.get('offset', 0))

    result = Topic.search(query, offset=offset, limit=limit)
    topics = result.get('data')

    pagination = dict(limit=limit,
                      offset=offset,
                      total=Topic.count_search(query))

    return jsonify(
        dict(data=[topic.json_data() for topic in topics],
             pagination=pagination))
Example #30
0
    def save(self, user, topic=None):
        data = self.data
        try:
            node_name = data.pop('node_name')
            if not self.node:
                self.node = Node.get(name=node_name)
        except KeyError:
            logging.info('no node_name in form data, data: %s', data)

        if not self.node:
            logging.info('node is None in form instance, self: %s', self)
        content = unicode(data.get('content'))
        data.update({'user_id': user.id, 'node_id': self.node.id,
                     'content': strip_xss_tags(content)})
        if topic:
            category = 'edit'
            pre_node_id = topic.node_id
            pre_title = topic.title
            pre_content = topic.content
            cur_node_id = data.get('node_id')
            cur_title = data.get('title')
            cur_content = data.get('content')
            changed = 0
            if pre_node_id != cur_node_id:
                topic.node.topic_count -= 1
                self.node.topic_count += 1
                diff_content = '主题节点从' + '<a class="node" href="' +\
                    topic.node.url + '">' + topic.node.name +\
                    '</a>移动到<a class="node" href="' + self.node.url + '">' +\
                    self.node.name + '</a>'
                changed = 1
            if pre_title != cur_title or pre_content != cur_content:
                content1 = '<p><h2>' + pre_title + '</h2></p>' + pre_content
                content2 = '<p><h2>' + cur_title + '</h2></p>' + cur_content
                diff_content = ghdiff.diff(content1, content2, css=None)
                changed = 1
            if changed == 1:
                topic.node_id = cur_node_id
                topic.title = cur_title
                topic.content = cur_content
                History(user_id=user.id, content=diff_content,
                        topic_id=topic.id).save()
            else:
                return topic
        else:
            category = 'create'
            topic = Topic(**data)
        return topic.save(category=category)
Example #31
0
def seed(db=DATABASE_URI):
    """Seed the database with some seed data."""
    connect(db)
    user = User.create(email='*****@*****.**', password='******')

    # Create seed subscriptions through json file.
    with open('resources/seed/subscriptions.json', 'r') as f:
        subscriptions = Subscription.from_json(f.read())
        for subscription in subscriptions:
            if random.choice([True, False]):
                user.subscribe(subscription)

        # Ensure at least one subscription
        user.subscribe(subscriptions[0])

    # Create seed topics through json file.
    with open('resources/seed/topics.json', 'r') as f:
        topics = Topic.from_json(f.read())
        for topic in topics:
            user.subscribe(subscriptions[0], topic)

    # Create seed articles through json file.
    with open('resources/seed/articles.json', 'r') as f:
        articles = Article.from_json(f.read())
        for article in articles:
            topic = random.choice(list(article.source.topics()))
            ArticleTopic.create(article=article, topic=topic)

            user.add_article(article)
Example #32
0
 def get(self):
     qry = Topic.query().order(Topic.topic)
     topics = []
     for row in qry:
         likes = Like.query().filter(Like.topic == row.key).count()
         topics.append(TOPIC(key=row.key, topic=row.topic, description=row.description, archived=row.archived, likes=likes))
     self.render_template('home.html', {'topics': topics})
Example #33
0
    def POST(self):
        if not session.user or not session.user.id:
            return bad_request('请先登录!')
        if session.user.username != 'ff':
            return bad_request('sorry,你没有创建权限')

        data = web.data()
        data = json.loads(data)

        topic_data = {
            "title": data.get('title'),
            "owner_id": session.user.id,
            "created_time": datetime.now(),
        }

        try:
            topic_id = Topic.create(**topic_data)
        except sqlite3.IntegrityError:
            return bad_request('你已创建过该名称!')

        result = {
            "id": topic_id,
            "title": topic_data.get('title'),
            "owner_id": session.user.id,
            "owner_name": session.user.username,
            "created_time": str(topic_data.get('created_time')),
        }
        return json.dumps(result)
Example #34
0
def search():
    query = request.args.get('query', '')
    query = query.strip()

    if len(query) == 0:
        return redirect('/')

    offset = int(request.args.get('offset', 0))
    limit = int(request.args.get('limit', 10))

    # search articles
    result = Article.search(query, offset=offset, limit=limit)
    articles = result.get('data')
    articles = [article.json_data() for article in articles]

    context = {
        'search': query,
        'offset': offset,
        'limit': limit,
        'js_module': 'search',
        'style': 'search',
        'articles': articles,
        'total_article': result['raw']['total_found'],
        'total_topic': Topic.count_search(query)
    }
    return render_template('site/search.html', **context)
Example #35
0
 def getTopForum(self, request):
     key = 'top:forum:' + request.title
     topics = memcache.get(key)
     if not topics:
         q = Topic.query()
         q = q.filter(Topic.forums == request.title)
         q = q.order(-Topic.vote)
         if request.limit > 50:
             limit = 50
         else:
             limit = request.limit
         q = q.fetch(limit)
         topics = [self._copyTopicToForm(t) for t in q]
         memcache.set(key, topics)
         sum_tags = [
             self._copyTagToForm(Tag(tag=t[0], score=t[1]))
             for t in self._sumTag(topics)
         ]
         memcache.set('tag' + key, sum_tags)
     else:
         sum_tags = memcache.get('tag' + key)
         if not sum_tags:
             sum_tags = [
                 self._copyTagToForm(Tag(tag=t[0], score=t[1]))
                 for t in self._sumTag(topics)
             ]
             memcache.set('tag' + key, sum_tags)
     n = len(topics)
     return TopicForms(topics=topics, length=n, tags=sum_tags)
Example #36
0
def flush():
    ndb.delete_multi(School.query().fetch(keys_only=True))
    ndb.delete_multi(QuestionInstance.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Question.query().fetch(keys_only=True))
    ndb.delete_multi(State.query().fetch(keys_only=True))
    ndb.delete_multi(Address.query().fetch(keys_only=True))
    ndb.delete_multi(Teacher.query().fetch(keys_only=True))
    ndb.delete_multi(Class.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(Student.query().fetch(keys_only=True))
    ndb.delete_multi(UserInfo.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment.query().fetch(keys_only=True))
    ndb.delete_multi(Subject.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Subject_Topics.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Topic.query().fetch(keys_only=True))
    ndb.delete_multi(User.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(State_Types.query().fetch(keys_only=True))
Example #37
0
    def get(self):

        version_name = self.request.get('version', 'edit')
        topics = map(str, self.request.get_all("topic") or self.request.get_all("topic[]"))

        edit_version = TopicVersion.get_by_id(version_name)
        if edit_version is None:
            default_version = TopicVersion.get_default_version()
            if default_version is None:
                # Assuming this is dev, there is an empty datastore and we need an import
                edit_version = TopicVersion.create_new_version()
                edit_version.edit = True
                edit_version.put()
                create_root(edit_version)
            else:
                raise Exception("Wait for setting default version to finish making an edit version.")

        if self.request.get('migrate', False):
            return self.topic_migration()
        if self.request.get('fixdupes', False):
            return self.fix_duplicates()

        root = Topic.get_root(edit_version)
        data = root.get_visible_data()
        tree_nodes = [data]
        
        template_values = {
            'edit_version': jsonify(edit_version),
            'tree_nodes': jsonify(tree_nodes)
            }
 
        self.render_jinja2_template('topics-admin.html', template_values)
        return
Example #38
0
    def get(self):
        user = users.get_current_user()

        if user:
            logiran = True
            logout_url = users.create_logout_url('/')
            user = users.get_current_user()
            if user.nickname() in ADMIN:
                user.admin = True

            seznam = Topic.query().fetch()
            urejen = sorted(seznam, key=attrgetter("date"), reverse=True)
            params = {
                "logiran": logiran,
                "logout_url": logout_url,
                "user": user,
                "seznam": urejen
            }

        else:
            logiran = False
            login_url = users.create_login_url('/')
            params = {"logiran": logiran, "login_url": login_url, "user": user}

        return self.render_template("base.html", params=params)
Example #39
0
    def setUp(self):
        print('\r')
        # drop all tables in the database
        db.session.remove()
        db.drop_all()
        # crete all tables in the database
        db.create_all()

        # adding users
        user_1 = User('*****@*****.**', encrypt('password'), 'student_1')
        student_1 = Student(user_1, 'U00000000A')
        db.session.add(student_1)

        user_2 = User('*****@*****.**', encrypt('password'), 'student_2')
        student_2 = Student(user_2, 'U00000000B')
        db.session.add(student_2)

        user_3 = User('*****@*****.**', encrypt('password'), 'teacher_1')
        staff_1 = Staff(user_3)
        db.session.add(staff_1)

        # adding topics
        topic = Topic(name='seng')
        db.session.add(topic)

        # adding lessons
        lesson = Lesson(1, 1, 'lesson_1', 'content')
        db.session.add(lesson)

        # adding quizzes
        quiz = Quiz(3, 'quiz_1', True, '2020-03-30', '2020-03-31')
        db.session.add(quiz)

        db.session.commit()
Example #40
0
def append_comment_page(topic_id):
    comment = request.form['comment']
    topic = Topic.find_by_id(topic_id)
    if topic:
        topic.append_comment(comment)
        return redirect(url_for('topic_page', topic_id=topic.id))
    return 'Page not found', 404
Example #41
0
def hide_topics(version):
    from topics_list import topics_list
    logging.info("hiding topics")

    root = Topic.get_by_id("root", version)
    topics = Topic.all().ancestor(root).fetch(10000)
    for topic in topics:
        if topic.title not in topics_list:
            topic.hide = True
            topic.put()
        else:
            topic.hide = False
            topic.put()

    logging.info("hid topics")
    deferred.defer(recreate_topic_list_structure)
Example #42
0
 def put(self, topic_id):
     topic_id = int(topic_id)
     topic = Topic.get(id=topic_id)
     if not topic:
         raise tornado.web.HTTPError(404)
     action = self.get_argument('action', None)
     user = self.current_user
     if not action:
         result = {'status': 'info', 'message': '需要 action 参数'}
     if action == 'up':
         if topic.user_id != user.id:
             result = user.up(topic_id=topic_id)
         else:
             result = {'status': 'info', 'message': '不能为自己的主题投票'}
     if action == 'down':
         if topic.user_id != user.id:
             result = user.down(topic_id=topic_id)
         else:
             result = {'status': 'info', 'message': '不能为自己的主题投票'}
     if action == 'collect':
         result = user.collect(topic_id=topic_id)
     if action == 'thank':
         result = user.thank(topic_id=topic_id)
     if action == 'report':
         result = user.report(topic_id=topic_id)
     if self.is_ajax:
         return self.write(result)
     else:
         self.flash_message(**result)
         return self.redirect_next_url()
Example #43
0
 def get(self, topic_id):
     topic = Topic.get(id=topic_id)
     if not topic:
         return self.redirect_next_url()
     if not topic.histories:
         return self.redirect(topic.url)
     return self.render("topic/history.html", topic=topic, histories=topic.histories)
Example #44
0
def flush():
    ndb.delete_multi(School.query().fetch(keys_only=True))
    ndb.delete_multi(QuestionInstance.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Question.query().fetch(keys_only=True))
    ndb.delete_multi(State.query().fetch(keys_only=True))
    ndb.delete_multi(Address.query().fetch(keys_only=True))
    ndb.delete_multi(Teacher.query().fetch(keys_only=True))
    ndb.delete_multi(Class.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(Student.query().fetch(keys_only=True))
    ndb.delete_multi(UserInfo.query().fetch(keys_only=True))
    ndb.delete
    _multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment.query().fetch(keys_only=True))
    ndb.delete_multi(Subject.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Subject_Topics.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Topic.query().fetch(keys_only=True))
    ndb.delete_multi(User.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(State_Types.query().fetch(keys_only=True))
Example #45
0
def library_content_html(mobile=False, version_number=None):

    if version_number:
        version = TopicVersion.get_by_number(version_number)
    else:
        version = TopicVersion.get_default_version()

    tree = Topic.get_root(version).make_tree(types = ["Topics", "Video", "Exercise", "Url"])

    videos = [item for item in walk_children(tree) if item.kind()=="Video"]

    root, = prepare(tree)
    topics = root.subtopics

    timestamp = time.time()

    template_values = {
        'topics': topics,
        'is_mobile': mobile,
        # convert timestamp to a nice integer for the JS
        'timestamp': int(round(timestamp * 1000)),
        'version_date': str(version.made_default_on),
        'version_id': version.number,
        'approx_vid_count': Video.approx_count(),
        'exercise_count': Exercise.get_count(),
    }

    html = shared_jinja.get().render_template("library_content_template.html", **template_values)

    return html
Example #46
0
    def setUp(self):
        print('\r')
        # drop all tables in the database
        db.session.remove()
        db.drop_all()
        # crete all tables in the database
        db.create_all()

        # adding users
        user = User(
            email='*****@*****.**',
            encrypted_password=encrypt('password'),
            name='john_doe'
        )
        student = Student(user, 'U1722')
        db.session.add(student)

        # adding topics
        topic = Topic(name='seng')
        db.session.add(topic)

        # adding lessons
        lesson = Lesson(topic_id=1, id=1, name='se', content='test')
        db.session.add(lesson)

        # adding questions
        qn_1 = Question(1, 1,'easy')
        db.session.add(qn_1)

        qn_2 = Question(1, 1,'medium')
        db.session.add(qn_2)
        
        db.session.commit()
Example #47
0
 def put(self, topic_id):
     topic_id = int(topic_id)
     topic = Topic.get(id=topic_id)
     if not topic:
         raise tornado.web.HTTPError(404)
     action = self.get_argument('action', None)
     user = self.current_user
     if not action:
         result = {'status': 'info', 'message':
                   '需要 action 参数'}
     if action == 'up':
         if topic.user_id != user.id:
             result = user.up(topic_id=topic_id)
         else:
             result = {'status': 'info', 'message':
                       '不能为自己的主题投票'}
     if action == 'down':
         if topic.user_id != user.id:
             result = user.down(topic_id=topic_id)
         else:
             result = {'status': 'info', 'message':
                       '不能为自己的主题投票'}
     if action == 'collect':
         result = user.collect(topic_id=topic_id)
     if action == 'thank':
         result = user.thank(topic_id=topic_id)
     if action == 'report':
         result = user.report(topic_id=topic_id)
     if self.is_ajax:
         return self.write(result)
     else:
         self.flash_message(**result)
         return self.redirect_next_url()
Example #48
0
    def POST(self):
        if not session.user or session.user.id is None:
            return bad_request('请先登录!')

        data = web.data()
        data = json.loads(data)

        tags = [tag for tag in data.get('tags', '').split(' ') if tag]
        topic_data = {
            "title": data.get('title'),
            "tags": tags,
            "owner_id": session.user.id,
            "created_time": datetime.now(),
        }

        try:
            topic_id = Topic.create(**topic_data)
        except sqlite3.IntegrityError:
            return bad_request('你已创建过该名称!')

        topic_data.update({
            "id": topic_id,
            "owner_name": session.user.username,
            "created_time": display_time(topic_data.get('created_time')),
        })
        return json.dumps(topic_data)
    def setUp(self):
        print('\r')
        # drop all tables in the database
        db.session.remove()
        db.drop_all()
        # crete all tables in the database
        db.create_all()

        # adding topics
        topic = Topic(name='seng')
        db.session.add(topic)

        # adding lessons
        lesson = Lesson(topic_id=1, id=1, name='se', content='test')
        db.session.add(lesson)

        # adding users
        user = User('*****@*****.**', encrypt('password'), 'staff_name')
        staff = Staff(user)
        db.session.add(staff)

        # adding quizzes
        quiz = Quiz(1, 'quiz_name', True, '2020-03-21', '2020-03-22')
        db.session.add(quiz)

        db.session.commit()
Example #50
0
 def initForum(self, request):
     forum_key = ndb.Key(Forum, request.title)
     task_key = ndb.Key(ForumInitTask, request.title, parent=forum_key)
     task = task_key.get()
     # t = task
     if not task:
         item = getTopicsForum(request.title)
         count, last_id = saveTopics(item, request.title)
         put = self._initForum(request.title, count, last_id)
         if put:
             taskqueue.add(params={
                 'title': request.title,
                 'loops': request.loops,
                 'limit': request.limit
             },
                           url='/collect_topics/forum')
     elif not task.done:
         taskqueue.add(params={
             'title': request.title,
             'loops': request.loops,
             'limit': request.limit
         },
                       url='/collect_topics/forum')
     q = Topic.query()
     q = q.filter(Topic.forums == request.title)
     q = q.order(-Topic.vote)
     q = q.fetch(10)
     topics = [self._copyTopicToForm(t) for t in q]
     n = len(topics)
     return TopicForms(topics=topics, length=n)
Example #51
0
def push_notifications_register():
    content = request.get_json(force=True)
    if content is None:
        return bad_request("failed to decode JSON object")
    params, err_response = get_json_params(content, ["registration_token"])
    if err_response:
        return err_response
    registration_token, = params
    latitude, longitude = get_json_params_optional(content,
                                                   ["latitude", "longitude"])
    topics = Topic.topic_list(db.session)
    fcm.subscribe_to_topics(registration_token, topics)
    if latitude and longitude:
        latitude = float(latitude)
        longitude = float(longitude)
        push_location = PushNotificationLocation.from_token(
            db.session, registration_token)
        if push_location:
            push_location.update(latitude, longitude)
        else:
            push_location = PushNotificationLocation(registration_token,
                                                     latitude, longitude)
        db.session.add(push_location)
        db.session.commit()
    return jsonify(dict(result="ok"))
Example #52
0
    def post(self):
        """
        POST method adds new topic to collection
        """
        if not request.json:
            return create_error_response(415, "Unsupported media type",
                                         "Request must be JSON")

        try:
            validate(request.json, BoardBuilder.topic_schema())
        except ValidationError as e:
            return create_error_response(400, "Invalid JSON document", str(e))

        new_topic = Topic(id=request.json["id"],
                          header=request.json["header"],
                          message=request.json["message"],
                          time=request.json["time"],
                          user_id=request.json["user_id"])

        try:
            db.session.add(new_topic)
            db.session.commit()
        except IntegrityError:
            return create_error_response(409, "Already exists",
                                         "Topic already inserted")

        return Response(
            status=201,
            headers={"Location": api.url_for(TopicItem, id=new_topic.id)})
    def init_app_basics(self, init_topics=False):
        from models import User, Topic
        from constants import API_AUTH, TOPIC

        self.user1 = User.Create(email="*****@*****.**",
                                 phone="254729465000")
        self.user2 = User.Create(email="*****@*****.**",
                                 phone="254729465999")
        ndb.put_multi([self.user1, self.user2])

        if init_topics:
            # 4 topics, politics is a poll
            self.topics = []
            ndb_put = []
            for topic_name in ["health", "matatus", "politics", "rain"]:
                t = Topic.Create()
                t.Update(name=topic_name, status=TOPIC.LIVE)
                if topic_name == "politics":
                    t.Update(poll=True, poll_choices=["Hillary", "Donald"])
                ndb_put.append(t)
                self.topics.append(t)
            ndb.put_multi(ndb_put)

        # Setup API authentication params for use in API calls
        self.api_auth_params = {'auth': API_AUTH}
Example #54
0
 def getTop(self, request):
     topics = memcache.get('top:all')
     if not topics:
         q = Topic.query()
         q = q.filter(Topic.vote > 0)
         q = q.order(-Topic.vote)
         if request.limit > 50:
             limit = 50
         else:
             limit = request.limit
         q = q.fetch(limit)
         topics = [self._copyTopicToForm(t) for t in q]
         memcache.set('top:all', topics)
         sum_tags = [
             self._copyTagToForm(Tag(tag=t[0], score=t[1]))
             for t in self._sumTag(topics)
         ]
         memcache.set('tag:top:all', sum_tags)
     else:
         sum_tags = memcache.get('tag:top:all')
         if not sum_tags:
             sum_tags = [
                 self._copyTagToForm(Tag(tag=t[0], score=t[1]))
                 for t in self._sumTag(topics)
             ]
             memcache.set('tag:top:all', sum_tags)
     # freq_tags = memcache.get('tag:top:all')
     # if not freq_tags:
     #     tags = []
     #     for topic in topics:
     #         tags.extend(topic.tags)
     #     freq_tags = [self._copyTagToForm(Tag(tag=t[0], score=t[1])) for t in self._freqTag(tags)]
     #     memcache.set('tag:top:all', freq_tags)
     n = len(topics)
     return TopicForms(topics=topics, length=n, tags=sum_tags)
Example #55
0
 def get(self, topic_id):
     topic_id = int(topic_id)
     page = force_int(self.get_argument('page', 0), 0)
     topic = Topic.get(id=topic_id)
     if not topic:
         raise tornado.web.HTTPError(404)
     category = self.get_argument('category', None)
     if not category:
         category = 'all'
     if category == 'all':
         reply_count = topic.reply_count
         url = topic.url
     elif category == 'hot':
         reply_count = orm.count(
             topic.get_replies(page=None, category=category))
         url = topic.url + '?category=hot'
     page_count = (reply_count + config.reply_paged -
                   1) // config.reply_paged
     if page == 0:
         page = page_count
     replies = topic.get_replies(page=page, category=category)
     form = ReplyForm()
     return self.render("topic/index.html",
                        topic=topic,
                        replies=replies,
                        form=form,
                        category=category,
                        page=page,
                        page_count=page_count,
                        url=url)
Example #56
0
def create_topic():
    """View for create topic"""
    if request.method == 'POST':

        topic_s = request.form['topic']
        error = None

        if not topic_s:
            error = 'No mandatory property is set.'
        else:
            topic = Topic.query.filter_by(topic=topic_s).first()
            if topic is not None:
                error = "The topic is already exist."      

        if error is not None:
            flash(error)
        else:            
            try:
                topic = Topic(topic=topic_s)
                db.session.add(topic)
                db.session.commit()
                return redirect(url_for('topic.topic_index'))

            except OSError as e:
                flash("Creation of the directory %s failed" % tag)
            except Exception as e:
                print(e)
                flash("DB Creation Failed")

    return render_template('topics/create.html')
Example #57
0
def search():
    query = request.args.get('query', '')
    query = query.strip()

    if len(query) == 0:
        return redirect('/')

    offset = int(request.args.get('offset', 0))
    limit = int(request.args.get('limit', 10))

    # search articles
    result = Article.search(query, offset=offset, limit=limit)
    articles = result.get('data')
    articles = [article.json_data() for article in articles]

    context = {
        'search': query,
        'offset': offset,
        'limit': limit,
        'js_module': 'search',
        'style': 'search',
        'articles': articles,
        'total_article': result['raw']['total_found'],
        'total_topic': Topic.count_search(query)
    }
    return render_template('site/search.html', **context)
Example #58
0
def about_top(request, turl_number):
    topic = Topic.objects(url_number=turl_number).get()
    if topic.is_top:
        topic.update(set__is_top=False)
    else:
        topic.update(set__is_top=True)
        
    return HttpResponse('success')