def get_context_data(self, **kwargs): context = super(BlogView, self).get_context_data(**kwargs) default_blog = Blog.query().get() context['blog'] = default_blog if default_blog: context['posts'] = Blog.get_all_posts(default_blog.key.id()) return context
def test_post_no_title(self): self.users_login('admin@localhost', is_admin=True) data = {'tagline': 'new_tagline'} self.client.post(self.url, data) self.assertEqual(Blog.get_unique().title, 'blog_title') self.assertEqual(Blog.get_unique().tagline, 'blog_tagline')
def initialise_db(): # Create an ancestor for all of our Posts to ensure consistency when manipulating Posts blog_instance = Blog.query().get() if not blog_instance: blog_instance = Blog() blog_instance.put() # Create Users if not User.query().fetch(): User( username='******', password='******' # TODO - obfuscate this ).put()
def create_blog(**kwargs): """ Helper function to create a blog in tests """ default_kwargs = {'title': 'blog_title', 'tagline': 'blog_tagline'} default_kwargs.update(kwargs) return Blog(key_name=settings.BLOG_KEY_NAME, **default_kwargs).put()
def blog_republish(blog_id, pass_id=1, item_id=0): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_publisher(user, blog) data = [] # check for dirty templates? from core import cms from core.libs.bottle import HTTPResponse from settings import BASE_PATH r = HTTPResponse() if pass_id == 1: cms.queue.queue_ssi_actions(blog) item_id = 0 data.append( "<h3>Queuing <b>{}</b> for republishing, pass {}, item {}</h3><hr>" .format(blog.for_log, pass_id, item_id)) elif pass_id == 2: cms.queue.queue_index_actions(blog, include_manual=True) item_id = 0 data.append( "<h3>Queuing <b>{}</b> for republishing, pass {}, item {}</h3><hr>" .format(blog.for_log, pass_id, item_id)) elif pass_id == 3: total = blog.pages.published.naive().count() pages = blog.pages.published.paginate(item_id, 20).naive() data.append( "<h3>Queuing <b>{}</b> for republishing, pass {}, item {} of {}</h3><hr>" .format(blog.for_log, pass_id, item_id * 20, total)) if pages.count() > 0: cms.queue.queue_page_actions(pages, no_neighbors=True) item_id += 1 else: item_id = 0 if item_id == 0: pass_id += 1 r.body = ''.join(data) if pass_id < 4: r.add_header( 'Refresh', "0;{}/blog/{}/republish/{}/{}".format(BASE_PATH, blog_id, pass_id, item_id)) else: r.body = "Queue insertion finished." r.add_header('Refresh', "0;{}/blog/{}/publish".format(BASE_PATH, blog_id)) return r
def tag_make_for_page(blog_id=None, page_id=None): user = auth.is_logged_in(request) if page_id is None: # page = Page() blog = Blog.load(blog_id) page = None permission = auth.is_blog_editor(user, blog) assoc = {'blog': blog} else: page = Page.load(page_id) blog = None permission = auth.is_page_editor(user, page) assoc = {'page': page} tag_name = request.forms.getunicode('tag') if len(tag_name) < 1: return None # Note that this is a single tag only! tag = Tag.add_or_create([ tag_name, ], **assoc) if len(tag[0]) > 0: tpl = template(tag[0][0].new_tag_for_display) else: tpl = template(tag[1][0].for_display) return tpl
def blog_publish_process(blog_id): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_publisher(user, blog) control_jobs = Queue.control_jobs(blog) if control_jobs.count() > 0: queue_count = q_p(blog) # queue_count = transaction(queue.process_queue)(blog) time.sleep(RETRY_INTERVAL * 5) else: jobs = Queue.jobs(blog) if jobs.count() > 0: queue_count = jobs.count() Queue.start(blog, queue_count) queue_count = q_p(blog) # queue_count = transaction(queue.process_queue)(blog) time.sleep(RETRY_INTERVAL * 5) else: queue_count = 0 import settings return template('queue/queue_counter_include', blog=blog, settings=settings, queue_count=queue_count)
def blog_publish_process(blog_id): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_publisher(user, blog) control_jobs = Queue.control_jobs(blog) if control_jobs.count() > 0: queue_count = q_p(blog) # queue_count = transaction(queue.process_queue)(blog) time.sleep(RETRY_INTERVAL * 5) else: jobs = Queue.jobs(blog) if jobs.count() > 0: queue_count = jobs.count() Queue.start(blog, queue_count) queue_count = q_p(blog) # queue_count = transaction(queue.process_queue)(blog) time.sleep(RETRY_INTERVAL * 5) else: queue_count = 0 import settings return template('queue/queue_counter_include', blog=blog, settings=settings, queue_count=queue_count)
def blog_publish(blog_id): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_publisher(user, blog) queue_length = Queue.job_counts(blog=blog) if queue_length > 0: start_message = template('queue/queue_run_include', queue=Queue.jobs(blog), percentage_complete=0, blog=blog, break_path='{}/blog/{}/publish/break'.format(BASE_URL, blog.id) ) Queue.start(blog, queue_length) else: start_message = "Queue empty." tags = template_tags(blog_id=blog.id, user=user) # return template('queue/queue_run_ui', start=queue_length, start_message=start_message, action_url="../../blog/{}/publish/progress/{}".format(blog.id, queue_length), title='Publishing queue progress', # search_context=(search_context['blog_queue'], blog), menu=generate_menu('blog_queue', blog), **tags.__dict__)
def delete_category(blog_id, category_id, confirm='N'): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_admin(user, blog) category = Category.load(category_id, blog_id=blog.id) auth.check_category_editing_lock(blog) tags = template_tags(blog=blog, user=user) from core.utils import Status if request.forms.getunicode('confirm') == user.logout_nonce: message = 'Category {} successfully deleted'.format(category.for_log) url = '{}/blog/{}/categories'.format(BASE_URL, blog.id) action = 'Return to the category listing' reparent_categories = Category.update( parent_category=category.parent_category).where( Category.parent_category == category) reparent_categories.execute() delete_category = PageCategory.delete().where( PageCategory.category == category.id) delete_category.execute() category.delete_instance() tags.status = Status(type='success', message=message, action=action, url=url, close=False) else: message = ( 'You are about to delete category <b>{}</b> from blog <b>{}</b>.'. format(category.for_display, blog.for_display)) yes = { 'label': 'Yes, delete this category', 'id': 'delete', 'name': 'confirm', 'value': user.logout_nonce } no = { 'label': 'No, return to category properties', 'url': '{}/blog/{}/category/{}'.format(BASE_URL, blog.id, category.id) } tags.status = Status(message=message, type='warning', close=False, yes=yes, no=no) tags.category = category return report(tags, 'blog_delete_category', category)
def media_edit(blog_id, media_id, status=None): ''' UI for editing a given media entry ''' user = auth.is_logged_in(request) blog = Blog.load(blog_id) is_member = auth.is_blog_member(user, blog) media = Media.load(media_id, blog) permission = auth.is_media_owner(user, media) from core.ui import kv kv_ui_data = kv.ui(media.kv_list()) tags = template_tags( blog=blog, media=media, status=status, user=user, ) tags.sidebar = sidebar.render_sidebar(panel_set='edit_media', status_badge=status_badge, kv_object='Media', kv_objectid=media.id, kv_ui=kv_ui_data) return media_edit_output(tags)
def blog_delete_preview(blog_id, preview_id): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_admin(user, blog) f = lambda:None f.blog = blog if preview_id == 'all': previews_to_delete = blog.fileinfos.where(FileInfo.preview_path.is_null(False)) message = 'All previews for blog {} deleted.'.format(blog.for_display) f.msg = 'Delete all' else: previews_to_delete = blog.fileinfos.where(FileInfo.id == preview_id) message = 'Preview for fileinfo {} deleted.'.format(preview_id) f.msg = 'Delete preview {}'.format(preview_id) for n in previews_to_delete: if n.page is not None: n.page.delete_preview() else: n.template_mapping.template.delete_preview() tags = template_tags(blog_id=blog.id, user=user) from core.utils import Status tags.status = Status( type='success', message=message, close=False, ) return report(tags, 'blog_delete_preview', f)
def tag_make_for_page(blog_id=None, page_id=None): user = auth.is_logged_in(request) if page_id is None: # page = Page() blog = Blog.load(blog_id) page = None permission = auth.is_blog_editor(user, blog) assoc = {'blog':blog} else: page = Page.load(page_id) blog = None permission = auth.is_page_editor(user, page) assoc = {'page':page} tag_name = request.forms.getunicode('tag') if len(tag_name) < 1: return None # Note that this is a single tag only! tag = Tag.add_or_create( [tag_name, ], **assoc ) if len(tag[0]) > 0: tpl = template(tag[0][0].new_tag_for_display) else: tpl = template(tag[1][0].for_display) return tpl
def media_edit(blog_id, media_id, status=None): ''' UI for editing a given media entry ''' user = auth.is_logged_in(request) blog = Blog.load(blog_id) is_member = auth.is_blog_member(user, blog) media = Media.load(media_id, blog) permission = auth.is_media_owner(user, media) from core.ui import kv kv_ui_data = kv.ui(media.kv_list()) tags = template_tags(blog=blog, media=media, status=status, user=user, ) tags.sidebar = sidebar.render_sidebar( panel_set='edit_media', status_badge=status_badge, kv_object='Media', kv_objectid=media.id, kv_ui=kv_ui_data) return media_edit_output(tags)
def blog_publish_progress(blog_id, original_queue_length): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_publisher(user, blog) queue_count = 0 control_jobs = Queue.control_jobs(blog) if control_jobs.count() > 0: # queue_count = queue.process_queue(blog) # queue_count = transaction(queue.process_queue)(blog) queue_count = q_p(blog) time.sleep(RETRY_INTERVAL * 5) else: queue_count = 0 percentage_complete = int((1 - (int(queue_count) / int(original_queue_length))) * 100) import settings return template('queue/queue_run_include', queue_count=queue_count, blog=blog, break_path='{}/blog/{}/publish/break'.format(BASE_URL, blog.id), settings=settings, percentage_complete=percentage_complete)
def blog_publish(blog_id): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_publisher(user, blog) queue_length = Queue.job_counts(blog=blog) if queue_length > 0: start_message = template('queue/queue_run_include', queue=Queue.jobs(blog), percentage_complete=0, blog=blog, break_path='{}/blog/{}/publish/break'.format( BASE_URL, blog.id)) Queue.start(blog, queue_length) else: start_message = "Queue empty." tags = template_tags(blog_id=blog.id, user=user) # return template( 'queue/queue_run_ui', start=queue_length, start_message=start_message, action_url="../../blog/{}/publish/progress/{}".format( blog.id, queue_length), title='Publishing queue progress', # search_context=(search_context['blog_queue'], blog), menu=generate_menu('blog_queue', blog), **tags.__dict__)
def blog_publish_progress(blog_id, original_queue_length): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_publisher(user, blog) queue_count = 0 control_jobs = Queue.control_jobs(blog) if control_jobs.count() > 0: # queue_count = queue.process_queue(blog) # queue_count = transaction(queue.process_queue)(blog) queue_count = q_p(blog) time.sleep(RETRY_INTERVAL * 5) else: queue_count = 0 percentage_complete = int( (1 - (int(queue_count) / int(original_queue_length))) * 100) import settings return template('queue/queue_run_include', queue_count=queue_count, blog=blog, break_path='{}/blog/{}/publish/break'.format( BASE_URL, blog.id), settings=settings, percentage_complete=percentage_complete)
def test_tagline_not_displayed_if_its_none(self): blog = Blog.get(self.blog_key) blog.tagline = None blog.put() resp = self.client.get(self.url) self.assertNotContains(resp, 'None')
def test_post_create(self): """ create a post """ res = self.c.post('/post/{0}'.format(self.blog_id), {'title': 'First Post', 'synopsis': 'Post Extract', 'content': 'Post Content', 'tags': ['tag1', 'tag2', 'tag3']}) self.assertEqual(len(Blog.get_all_posts(self.blog_id)), 2)
def blog_user(user_id, blog_id): # Obtains user edit in blog context. user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_admin(user, blog) user_to_edit = User.find(user_id) return edit_user(user_to_edit, editing_user=user, context=blog_context, blog=blog)
def media_edit_save(blog_id, media_id): ''' Save changes to a media entry. ''' user = auth.is_logged_in(request) blog = Blog.load(blog_id) is_member = auth.is_blog_member(user, blog) media = Media.load(media_id) permission = auth.is_media_owner(user, media) friendly_name = request.forms.getunicode('media_friendly_name') changes = False if friendly_name != media.friendly_name: changes = True media.friendly_name = friendly_name import datetime if changes is True: media.modified_date = datetime.datetime.utcnow() media.save() status = utils.Status( type='success', message='Changes to media <b>{}</b> saved successfully.'.format( media.for_display) ) else: status = utils.Status( type='warning', no_sure=True, message='No discernible changes submitted for media <b>{}</b>.'.format( media.id, media.for_display) ) logger.info("Media {} edited by user {}.".format( media.for_log, user.for_log)) from core.ui import kv kv_ui_data = kv.ui(media.kv_list()) tags = template_tags(blog=blog, media=media, status=status, user=user) tags.sidebar = sidebar.render_sidebar( panel_set='edit_media', status_badge=status_badge, kv_object='Media', kv_objectid=media.id, kv_ui=kv_ui_data) return media_edit_output(tags)
def blog_queue_clear(blog_id): ''' Clear all pending jobs out of the queue ''' user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_publisher(user, blog) Queue.clear(blog)
def get_context_data(self, *args, **kwargs): context = super(BlogMixin, self).get_context_data(*args, **kwargs) blog = Blog.get_unique() context.update({ 'blog': blog, 'active_user': users.get_current_user(), 'is_admin': users.is_current_user_admin() }) return context
def get_context_data(self, *args, **kwargs): context = super(BlogMixin, self).get_context_data(*args, **kwargs) blog = Blog.get_unique() context.update({ 'blog': blog, 'active_user': users.get_current_user(), 'is_admin': users.is_current_user_admin() }) return context
def blog_new_page(blog_id): ''' Displays UI for newly created (unsaved) page ''' user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_member(user, blog) tags = template_tags(blog=blog, user=user) tags.page = Page() referer = request.headers.get('Referer') if referer is None: referer = BASE_URL + "/blog/" + str(blog.id) blog_new_page = tags.page for n in new_page_submission_fields: blog_new_page.__setattr__(n, "") if n in request.query: blog_new_page.__setattr__(n, request.query.getunicode(n)) import datetime blog_new_page.blog = blog blog_new_page.user = user blog_new_page.publication_date = datetime.datetime.utcnow() blog_new_page.basename = '' from core.cms import save_action_list from core.ui import kv kv_ui_data = kv.ui(blog_new_page.kv_list()) try: html_editor_settings = Template.get( Template.blog == blog, Template.title == 'HTML Editor Init', Template.template_type == template_type.system).body except Template.DoesNotExist: from core.static import html_editor_settings return template( 'edit/page', menu=generate_menu('create_page', blog), parent_path=referer, # search_context=(search_context['blog'], blog), html_editor_settings=html_editor_settings, sidebar=sidebar.render_sidebar(panel_set='edit_page', status_badge=status_badge, save_action=save_action, save_action_list=save_action_list, kv_ui=kv_ui_data, kv_object='Page', kv_objectid=None, **tags.__dict__), **tags.__dict__)
def blog_queue_clear(blog_id): ''' Clear all pending jobs out of the queue ''' user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_publisher(user, blog) Queue.clear(blog)
def post(self): data = request.get_json() if self.user_is_admin is False: response = failure_response(401, 'Unauthenticated requests') return jsonify(response) name = data.get('name') content = data.get('content') if name or content is None: response = failure_response(400, 'Missing required fields') return jsonify(response) elif name.isalpha() is False or content.isalpha() is False: response = failure_response(400, 'Non string values are not accepted') return jsonify(response) blog = Blog(name=name, content=content, posted_user=current_user) blog.save() response = success_response({'blog_id': blog.id}) return jsonify(response)
def delete(self, blog_id): if self.user_is_admin is False: response = failure_response(401, 'Unauthenticated requests') return jsonify(response) blog = Blog.objects(_id=blog_id).first() if blog is not None: blog.delete() response = success_response({'deleted': True}) return jsonify(response)
def blog_static(filepath): ''' Returns static routes for the currently staged blog. The blog ID is appended to the URL as a '_' parameter (e.g., ?_=1 for blog ID 1) The future of this function is currently being debated. ''' try: blog_id = int(request.query['_']) except KeyError: return system_site_index() # raise blog = Blog.load(blog_id) root_path = blog.path filesystem_filepath = urllib.parse.quote(filepath) # TODO: replace this with results from /preview path, # or another function that finds by abs path in db. if os.path.isfile(root_path + "/" + filesystem_filepath) is False: filepath += ("index.html") if os.path.isfile(root_path + "/" + filesystem_filepath) is False: abort( 404, 'File {} not found'.format(root_path + "/" + filesystem_filepath)) k = static_file(filesystem_filepath, root=root_path) if (k.headers['Content-Type'][:5] == "text/" or k.headers['Content-Type'] == "application/javascript"): k.add_header('Cache-Control', 'max-age=7200, public, must-revalidate') if (k._headers['Content-Type'][0][:5] == "text/" and not k.body == ""): x = k.body.read() k.body.close() y = x.decode('utf8') z = re.compile(r' href=["\']' + (blog.url) + '([^"\']*)["\']') z2 = re.compile(r' href=["\'](/[^"\']*)["\']') y = re.sub( z, r" href='" + BASE_URL_PROTOCOL + DEFAULT_LOCAL_ADDRESS + DEFAULT_LOCAL_PORT + "\\1?_={}'".format(blog_id), y) y = re.sub(z2, r" href='\1?_={}'".format(blog_id), y) y = y.encode('utf8') k.headers['Content-Length'] = len(y) k.body = y return (k)
def export_theme_for_blog(blog_id, theme_name, theme_description): from core.models import KeyValue, Blog blog = Blog.load(blog_id) theme_to_export = blog.templates() theme = {} theme["title"] = theme_to_export[0].theme.title theme["description"] = theme_to_export[0].theme.description theme["data"] = {} for n in theme_to_export: theme["data"][n.id] = {} theme["data"][n.id]["template"] = json_dump(n) mappings_to_export = n.mappings theme["data"][n.id]["mapping"] = {} for m in mappings_to_export: theme["data"][n.id]["mapping"][m.id] = json_dump(m) # We may not use the rest of this because of the way # KVs are being scaled back theme["kv"] = {} kv_list = [] top_kvs = KeyValue.select().where( KeyValue.object == 'Theme', KeyValue.objectid == theme_to_export[0].theme.id, KeyValue.is_schema == True) for n in top_kvs: kv_list.append(n) while len(kv_list) > 0: theme["kv"][kv_list[0].id] = json_dump(kv_list[0]) next_kvs = KeyValue.select().where( KeyValue.parent == kv_list[0], KeyValue.is_schema == True) for f in next_kvs: kv_list.append(f) del kv_list[0] import settings, os with open(os.path.join(settings.APPLICATION_PATH , "install" , "templates.json"), "w", encoding='utf-8') as output_file: output_file.write(json.dumps(theme, indent=1, sort_keys=True, allow_nan=True)) return theme
def post(self, request, **kwargs): ancestor_key = Blog.get_key(kwargs.get('id', None)) if request.method == 'POST': post_id = Post(parent=ancestor_key, title=request.POST.get('title', ''),\ synopsis=request.POST.get('synopsis', ''), author=request.POST.get('author', ''), content=request.POST.get('content', '')).put().id() return HttpResponse(json.dumps({'status': 'OK', 'message': 'Post Created', 'id': post_id}))
def test_post_valid(self): self.users_login('admin@localhost', is_admin=True) data = {'title': 'new_blog_title', 'tagline': 'new_tagline'} resp = self.client.post(self.url, data) blog = Blog.get_unique() self.assertRedirects(resp, reverse('index')) self.assertEqual(blog.title, 'new_blog_title') self.assertEqual(blog.tagline, 'new_tagline')
def export_theme_for_blog(blog_id, theme_name, theme_description): from core.models import KeyValue, Blog blog = Blog.load(blog_id) theme_to_export = blog.templates() theme = {} theme["title"] = theme_to_export[0].theme.title theme["description"] = theme_to_export[0].theme.description theme["data"] = {} for n in theme_to_export: theme["data"][n.id] = {} theme["data"][n.id]["template"] = json_dump(n) mappings_to_export = n.mappings theme["data"][n.id]["mapping"] = {} for m in mappings_to_export: theme["data"][n.id]["mapping"][m.id] = json_dump(m) # We may not use the rest of this because of the way # KVs are being scaled back theme["kv"] = {} kv_list = [] top_kvs = KeyValue.select().where( KeyValue.object == 'Theme', KeyValue.objectid == theme_to_export[0].theme.id, KeyValue.is_schema == True) for n in top_kvs: kv_list.append(n) while len(kv_list) > 0: theme["kv"][kv_list[0].id] = json_dump(kv_list[0]) next_kvs = KeyValue.select().where(KeyValue.parent == kv_list[0], KeyValue.is_schema == True) for f in next_kvs: kv_list.append(f) del kv_list[0] import settings, os with open(os.path.join(settings.APPLICATION_PATH, "install", "templates.json"), "w", encoding='utf-8') as output_file: output_file.write( json.dumps(theme, indent=1, sort_keys=True, allow_nan=True)) return theme
def new_category(blog_id): from core.models import db with db.atomic() as txn: user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_editor(user, blog) category_list = [n for n in blog.categories] category = Category(id=0, title='', blog=blog) top_level_category = Category( id=None, title='[Top-level category]', parent=None ) category_list.insert(0, top_level_category) tags = template_tags( blog=blog, user=user) if request.method == "POST": with db.atomic() as txn: category_title = request.forms.getunicode('category_title') try: parent_category = int(request.forms.getunicode('category_parent')) except ValueError: parent_category = None with db.atomic() as txn: category = Category(blog=blog, title=category_title, parent_category=parent_category ) category.save() redirect('{}/blog/{}/category/{}'.format( BASE_URL, blog.id, category.id)) tpl = template('edit/category', category=category, category_list=category_list, menu=generate_menu('blog_new_category', category), search_context=(search_contexts['sites'], None), **tags.__dict__) return tpl
def blog_list_users(blog_id): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_admin(user, blog) return listing(request, blog, blog.users, 'blog_users', 'blog_list_users', user=user, tags_data={'blog':blog} )
def blog_user(user_id, blog_id): # Obtains user edit in blog context. user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_admin(user, blog) user_to_edit = User.find(user_id) return edit_user(user_to_edit, editing_user=user, context=blog_context, blog=blog)
def blog_static(filepath): ''' Returns static routes for the currently staged blog. The blog ID is appended to the URL as a '_' parameter (e.g., ?_=1 for blog ID 1) The future of this function is currently being debated. ''' try: blog_id = int(request.query['_']) except KeyError: return system_site_index() # raise blog = Blog.load(blog_id) root_path = blog.path filesystem_filepath = urllib.parse.quote(filepath) # TODO: replace this with results from /preview path, # or another function that finds by abs path in db. if os.path.isfile(root_path + "/" + filesystem_filepath) is False: filepath += ("index.html") if os.path.isfile(root_path + "/" + filesystem_filepath) is False: abort(404, 'File {} not found'.format(root_path + "/" + filesystem_filepath)) k = static_file(filesystem_filepath, root=root_path) if (k.headers['Content-Type'][:5] == "text/" or k.headers['Content-Type'] == "application/javascript"): k.add_header( 'Cache-Control', 'max-age=7200, public, must-revalidate') if (k._headers['Content-Type'][0][:5] == "text/" and not k.body == ""): x = k.body.read() k.body.close() y = x.decode('utf8') z = re.compile(r' href=["\']' + (blog.url) + '([^"\']*)["\']') z2 = re.compile(r' href=["\'](/[^"\']*)["\']') y = re.sub(z, r" href='" + BASE_URL_PROTOCOL + DEFAULT_LOCAL_ADDRESS + DEFAULT_LOCAL_PORT + "\\1?_={}'".format(blog_id), y) y = re.sub(z2, r" href='\1?_={}'".format(blog_id), y) y = y.encode('utf8') k.headers['Content-Length'] = len(y) k.body = y return (k)
def blog_apply_theme(blog_id, theme_id): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_publisher(user, blog) reason = auth.check_template_lock(blog) theme = Theme.load(theme_id) tags = template_tags(blog=blog, user=user) from core.utils import Status if request.forms.getunicode('confirm') == user.logout_nonce: from core.models import db with db.atomic() as txn: blog.apply_theme(theme, user) status = Status( type='success', close=False, message=''' Theme <b>{}</b> was successfully applied to blog <b>{}</b>.</p> It is recommended that you <a href="{}">republish this blog.</a> '''.format(theme.for_display, blog.for_display, '{}/blog/{}/republish'.format( BASE_URL, blog.id)) ) else: status = Status( type='warning', close=False, message=''' You are about to apply theme <b>{}</b> to blog <b>{}</b>.</p> <p>This will OVERWRITE AND REMOVE ALL EXISTING TEMPLATES on this blog!</p> '''.format(theme.for_display, blog.for_display), url='{}/blog/{}/themes'.format( BASE_URL, blog.id), yes={'id':'delete', 'name':'confirm', 'label':'Yes, I want to apply this theme', 'value':user.logout_nonce}, no={'label':'No, don\'t apply this theme', 'url':'{}/blog/{}/themes'.format( BASE_URL, blog.id)} ) tags.status = status if reason is None else reason return report(tags, 'blog_apply_theme', [blog, theme])
def blog_settings(blog_id, nav_setting): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_admin(user, blog) auth.check_settings_lock(blog) tags = template_tags(blog_id=blog.id, user=user) tags.nav_default = nav_setting return blog_settings_output(tags)
def blog_list_users(blog_id): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_admin(user, blog) return listing(request, blog, blog.users, 'blog_users', 'blog_list_users', user=user, tags_data={'blog': blog})
def push_to_queue(**ka): ''' Inserts a single job item into the work queue. :param job_type: A string representing the type of job to be inserted. 'Page','Index', eventually 'Fileinfo' :param data_integer: Any integer data passed along with the job. For a job control item, this is the number of items remaining for that particular job. :param blog: The blog object associated with the job. :param site: The site object associated with the job. :param priority: An integer, from 0-9, representing the processing priority associated with the job. Higher-priority jobs are processed first. Most individual pages are given a high priority; indexes are lower. ''' try: queue_job = Queue.get(Queue.job_type == ka['job_type'], Queue.data_integer == ka['data_integer'], Queue.blog == ka['blog'], Queue.site == ka['site']) except Queue.DoesNotExist: queue_job = Queue() else: return queue_job.job_type = ka['job_type'] queue_job.data_integer = int(ka.get('data_integer', None)) queue_job.blog = ka.get('blog', Blog()).id queue_job.site = ka.get('site', Site()).id queue_job.priority = ka.get('priority', 9) queue_job.is_control = ka.get('is_control', False) if queue_job.is_control: queue_job.data_string = (queue_job.job_type + ": Blog {}".format(queue_job.blog.for_log)) else: queue_job.data_string = ( queue_job.job_type + ": " + FileInfo.get(FileInfo.id == queue_job.data_integer).file_path) queue_job.date_touched = datetime.datetime.now() queue_job.save()
def media_edit_save(blog_id, media_id): ''' Save changes to a media entry. ''' user = auth.is_logged_in(request) blog = Blog.load(blog_id) is_member = auth.is_blog_member(user, blog) media = Media.load(media_id) permission = auth.is_media_owner(user, media) friendly_name = request.forms.getunicode('media_friendly_name') changes = False if friendly_name != media.friendly_name: changes = True media.friendly_name = friendly_name import datetime if changes is True: media.modified_date = datetime.datetime.utcnow() media.save() status = utils.Status( type='success', message='Changes to media <b>{}</b> saved successfully.'.format( media.for_display)) else: status = utils.Status( type='warning', no_sure=True, message='No discernible changes submitted for media <b>{}</b>.'. format(media.id, media.for_display)) logger.info("Media {} edited by user {}.".format(media.for_log, user.for_log)) from core.ui import kv kv_ui_data = kv.ui(media.kv_list()) tags = template_tags(blog=blog, media=media, status=status, user=user) tags.sidebar = sidebar.render_sidebar(panel_set='edit_media', status_badge=status_badge, kv_object='Media', kv_objectid=media.id, kv_ui=kv_ui_data) return media_edit_output(tags)
def tag_get(blog_id, tag_name): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_member(user, blog) tag_name = url_unescape(tag_name) tag_list = Tag.select().where(Tag.tag.contains(tag_name), Tag.blog == blog) import json tag_list_json = json.dumps([{'tag': t.tag, 'id': t.id} for t in tag_list]) return tag_list_json
def blog_apply_theme(blog_id, theme_id): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_publisher(user, blog) reason = auth.check_template_lock(blog) theme = Theme.load(theme_id) tags = template_tags(blog=blog, user=user) from core.utils import Status if request.forms.getunicode('confirm') == user.logout_nonce: from core.models import db with db.atomic() as txn: blog.apply_theme(theme, user) status = Status(type='success', close=False, message=''' Theme <b>{}</b> was successfully applied to blog <b>{}</b>.</p> It is recommended that you <a href="{}">republish this blog.</a> '''.format(theme.for_display, blog.for_display, '{}/blog/{}/republish'.format(BASE_URL, blog.id))) else: status = Status(type='warning', close=False, message=''' You are about to apply theme <b>{}</b> to blog <b>{}</b>.</p> <p>This will OVERWRITE AND REMOVE ALL EXISTING TEMPLATES on this blog!</p> '''.format(theme.for_display, blog.for_display), url='{}/blog/{}/themes'.format(BASE_URL, blog.id), yes={ 'id': 'delete', 'name': 'confirm', 'label': 'Yes, I want to apply this theme', 'value': user.logout_nonce }, no={ 'label': 'No, don\'t apply this theme', 'url': '{}/blog/{}/themes'.format(BASE_URL, blog.id) }) tags.status = status if reason is None else reason return report(tags, 'blog_apply_theme', [blog, theme])
def media_pages(blog_id, media_id): user = auth.is_logged_in(request) blog = Blog.load(blog_id) is_member = auth.is_blog_member(user, blog) media = Media.load(media_id, blog) return listing(request, media, media.pages.order_by(Page.publication_date.desc()), 'blog', 'blog_media_pages', user=user, search_ui='blog_media_pages', search_context=media_search_results, tags_data={'blog':blog} )
def blog(blog_id, errormsg=None): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_member(user, blog) return listing(request, blog, blog.pages, 'blog', 'blog_menu', user=user, errormsg=errormsg, search_ui='blog', search_context=blog_search_results, tags_data={'blog':blog} )
def tag_list_pages(blog_id, tag_id): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_member(user, blog) tag = Tag.load(tag_id) return listing(request, tag, tag.pages.order_by(Page.publication_date.desc()), 'blog', 'blog_pages_for_tag', user=user, search_ui='blog_pages_with_tag', search_context=tag_in_blog_search_results, tags_data={'blog':blog} )
def blog_settings(blog_id, nav_setting): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_admin(user, blog) auth.check_settings_lock(blog) tags = template_tags(blog_id=blog.id, user=user) tags.nav_default = nav_setting return blog_settings_output(tags)
def blog_previews_list(blog_id): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_admin(user, blog) previews = blog.fileinfos.where(FileInfo.preview_path.is_null(False)) return listing(request, blog, previews, 'blog_previews', 'blog_previews', user=user, msg_float=False, tags_data={'blog':blog} )
def test_get_unique_one_blog(self): blog = Blog(key_name=settings.BLOG_KEY_NAME, title='blog_one') blog.put() result = Blog.get_unique() self.assertEqual(result.title, 'blog_one') self.assertEqual(result.tagline, None) self.assertEqual(Blog.all().count(), 1)
def template_delete(template_id): ''' UI for deleting a template ''' user = auth.is_logged_in(request) tpl = Template.load(template_id) blog = Blog.load(tpl.blog) permission = auth.is_blog_designer(user, blog) from core.utils import Status import settings tags = template_tags(template_id=tpl.id, user=user) if request.forms.getunicode('confirm') == user.logout_nonce: # _template.delete(tpl) tpl.delete_instance() status = Status(type='success', close=False, message='Template {} was successfully deleted.'.format( tpl.for_log), action='Return to template list', url='{}/blog/{}/templates'.format( settings.BASE_URL, blog.id)) else: status = Status( type='warning', close=False, message= 'You are attempting to delete template <b>{}</b> from blog <b>{}</b>.' .format(tpl.for_display, blog.for_display), no={ 'url': '{}/template/{}/edit'.format(settings.BASE_URL, tpl.id), 'label': 'No, I don\'t want to delete this template' }, yes={ 'id': 'delete', 'name': 'confirm', 'label': 'Yes, I want to delete this template', 'value': user.logout_nonce }) tags.status = status return report(tags, 'blog_delete_template', tpl)
def template_set_default(template_id): ''' UI for setting a given template as the default for an archive type ''' user = auth.is_logged_in(request) tpl = Template.load(template_id) blog = Blog.load(tpl.blog.id) permission = auth.is_blog_designer(user, blog) auth.check_template_lock(blog) tags = template_tags(template=tpl, user=user) from core.utils import Status import settings if request.forms.getunicode('confirm') == user.logout_nonce: # check for form submission # setting should be done by way of class object # theme? blog? template? # blog.set_default_archive_template(template,{archive_type.index...}) status = Status( type='success', close=False, message= 'Template <b>{}</b> was successfully refreshed from theme <b>{}</b>.' .format(tpl.for_display, tpl.theme.for_display), action='Return to template', url='{}/template/{}/edit'.format(settings.BASE_URL, tpl.id)) tags.status = status else: pass from core.models import archive_defaults return template('edit/template-set-default', icons=icons, search_context=(search_contexts['blog'], tags.blog), menu=generate_menu('blog_edit_template', tags.template), sidebar=sidebar.render_sidebar( panel_set='edit_template', publishing_mode=publishing_mode, types=template_type, **tags.__dict__), archive_defaults=archive_defaults, **tags.__dict__)
def media_pages(blog_id, media_id): user = auth.is_logged_in(request) blog = Blog.load(blog_id) is_member = auth.is_blog_member(user, blog) media = Media.load(media_id, blog) return listing(request, media, media.pages.order_by(Page.publication_date.desc()), 'blog', 'blog_media_pages', user=user, search_ui='blog_media_pages', search_context=media_search_results, tags_data={'blog': blog})
def put(self, blog_id): if self.user_is_admin is False: response = failure_response(401, 'Unauthenticated requests') return jsonify(response) data = request.get_json() name = data.get('name') content = data.get('content') blog = Blog.objects(_id=blog_id).first() if blog is None: response = failure_response(400, 'Invalid requests') return jsonify(response) blog.name = name blog.content = content blog.updated_date = datetime.now() blog.save()
def tags_list(blog_id): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_author(user, blog) errormsg = auth.check_tag_editing_lock(blog, True) return listing(request, blog, blog.tags, 'tags', 'blog_manage_tags', user=user, search_ui='blog_tags', search_context=tag_search_results, errormsg=errormsg, tags_data={'blog':blog} )
def blog_queue(blog_id, status=None): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_publisher(user, blog) tags = template_tags(blog_id=blog.id, user=user, status=status) return listing(request, blog, tags.queue, 'queue', 'blog_menu', user=user, tags_data={'blog':blog}, errormsg=tags.status )
def media_list(blog_id): ''' UI for listing media for a given blog ''' user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_member(user, blog) return listing(request, blog, blog.media.order_by(Media.id.desc()), 'media', 'blog_manage_media', user=user, search_ui='blog_media', search_context=media_search_results, tags_data={'blog':blog} )
def tag_get(blog_id, tag_name): user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_member(user, blog) tag_name = url_unescape(tag_name) tag_list = Tag.select().where( Tag.tag.contains(tag_name), Tag.blog == blog) import json tag_list_json = json.dumps([{'tag':t.tag, 'id':t.id} for t in tag_list]) return tag_list_json
def setUp(self): """ setup test bed """ self.c = Client() self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() self.blog_id = Blog(title='Sample Blog',\ description='Description', comments_is_enabled=True).put().id() self.post_id = Post(parent=Blog.get_key(self.blog_id), title='Sample Title', synopsis='The Synopsis', content='The Content').put().urlsafe()