Ejemplo n.º 1
0
def createPost(title, author, slug, content, createdDateTime, tags, status, publishedDateTime=None, publishedYear=None, publishedMonth=None):
	if len(title) < 3: return (False, "Title must be at least 3 characters", None)
	if len(slug) < 3: return (False, "Slug must be at least 3 characters", None)
	if len(content) < 3: return (False, "Content must be at least 3 characters", None)

	if isinstance(tags, basestring):
		tags = tags.split(",")

	id = database.execute(sql="""
		INSERT INTO post (
			  title
			, authorId
			, slug
			, content
			, createdDateTime
			, postStatusId
			, publishedDateTime
			, publishedYear
			, publishedMonth
		) VALUES (
			  %s
			, %s
			, %s
			, %s
			, %s
			, %s
			, %s
			, %s
			, %s
		)
	""", parameters=(
		  title
		, author["id"]
		, slug
		, content
		, dthelper.formatDateTime(date=createdDateTime)
		, status["id"]
		, None if publishedDateTime is None else dthelper.formatDateTime(date=publishedDateTime)
		, None if publishedYear is None else dthelper.getYear(date=publishedYear)
		, None if publishedMonth is None else dthelper.getMonth(date=publishedMonth)
	))

	createUpdatePostTags(postId=id, tags=tags)

	return newPostBean(
		title            = title,
		authorId         = author["id"],
		slug             = slug,
		content          = content,
		createdDateTime  = dthelper.parseDateTime(date=createdDateTime),
		publishedDateTime= None if publishedDateTime is None else dthelper.parseDateTime(date=publishedDateTime),
		publishedYear    = None if publishedYear is None else dthelper.getYear(date=publishedYear),
		publishedMonth   = None if publishedMonth is None else dthelper.getMonth(date=publishedMonth),
		postStatusId     = status["id"],
		tags             = tags,
	)
Ejemplo n.º 2
0
def publishPost(postId):
	database.execute(sql="""
		UPDATE post SET
			  postStatusId=(SELECT id FROM poststatus WHERE status='Published' LIMIT 1)
			, publishedDateTime=CASE
				WHEN publishedDateTime IS NULL THEN %s
				ELSE publishedDateTime
			END
			, publishedYear=CASE
				WHEN publishedYear IS NULL THEN %s
				ELSE publishedYear
			END
			, publishedMonth=CASE
				WHEN publishedMonth IS NULL THEN %s
				ELSE publishedMonth
			END
		WHERE id=%s
	""", parameters=(
		dthelper.formatDateTime(date=dthelper.utcNow()),
		dthelper.getYear(date=dthelper.utcNow()),
		dthelper.getMonth(date=dthelper.utcNow()),
		postId,
	))

	return database.LAST_NUM_AFFECTED
Ejemplo n.º 3
0
def updatePost(id, title, slug, content, tags, status, publishedDateTime=None, publishedYear=None, publishedMonth=None):
	if len(title) < 3: return (False, "Title must be at least 3 characters", None)
	if len(slug) < 3: return (False, "Slug must be at least 3 characters", None)
	if len(content) < 3: return (False, "Content must be at least 3 characters", None)

	post = getPostById(id=id)
	tags = tags.split(",")

	if post:
		post["title"] = title
		post["slug"] = slug
		post["content"] = content
		post["tags"] = tags
		post["status"] = status
		post["postStatusId"] = getPostStatus(status=status)["id"]
		post["publishedDateTime"] = None if publishedDateTime is None else dthelper.formatDateTime(date=publishedDateTime)
		post["publishedYear"] = None if publishedYear is None else dthelper.getYear(date=publishedYear)
		post["publishedMonth"] = None if publishedMonth is None else dthelper.getMonth(date=publishedMonth)

		sql = """
			UPDATE post SET
				  title=%s
				, slug=%s
				, content=%s
				, publishedDateTime=%s
				, publishedYear=%s
				, publishedMonth=%s
				, postStatusId=%s
			WHERE id=%s
		"""

		parameters = (
			post["title"],
			post["slug"],
			post["content"],
			post["publishedDateTime"],
			post["publishedYear"],
			post["publishedMonth"],
			post["postStatusId"],
			id,
		)

		database.execute(sql=sql, parameters=parameters)
		createUpdatePostTags(postId=id, tags=post["tags"])

	return post
Ejemplo n.º 4
0
def parseMarkdownFile(fileName, sourceTimezone):
	with open(fileName) as markdownFile:
		markdownContent = markdownFile.read()

	#
	# Parse the file
	#
	mode = "METADATA"
	metadata = {}
	content = []

	for line in markdownContent.split("\n"):
		if mode == "METADATA":
			if line.find(":") == -1:
				mode = "CONTENT"

				if len(line.strip()):
					content.append(line)
			else:
				split = line.split(":")
				key = split[0].strip().lower()

				if key == "tags":
					value = [tag.strip() for tag in split[1].split(",")]
				elif key == "date":
					value = "{0}:{1}".format(split[1], split[2]).strip()
					value = dthelper.formatDateTime(date=dthelper.timezoneToUtc(sourceTimezone=sourceTimezone, date=value, parseFormat="%Y-%m-%d %H:%M"), parseFormat="%Y-%m-%d %H:%M:%S%z")

					metadata["publishedMonth"] = int(dthelper.getMonth(date=value, parseFormat=dthelper.REST_DATETIME_FORMAT))
					metadata["publishedYear"] = int(dthelper.getYear(date=value, parseFormat=dthelper.REST_DATETIME_FORMAT))

				else:
					value = ":".join(split[1:]).strip()

				metadata[key] = value
		else:
			content.append(line)

	return (metadata, stipInvalidUnicodeCharacters("\n".join(content)))
Ejemplo n.º 5
0
def adminUploadMarkdownFile():
	logger = logging.getLogger(__name__)

	f = request.files.get("upload")
	name, ext = os.path.splitext(f.filename)

	if ext not in (".md"):
		return "Invalid file type"

	#
	# Upload the file, then parse it
	#
	f.save(config.UPLOAD_PATH, True)

	try:
		fullUploadedFilePath = os.path.join(config.UPLOAD_PATH, f.filename)
		metadata, content = postservice.parseMarkdownFile(fullUploadedFilePath, config.TIMEZONE)

		#
		# Find the author based on name
		#
		firstName, lastName = metadata["author"].split(" ")
		possibleAuthors = userservice.getUsersByName(firstName=firstName, lastName=lastName)

		if len(possibleAuthors) <= 0:
			raise Exception("Could not find author")

		#
		# Find status by name
		#
		status = postservice.getPostStatus(status="Published")

		dt = metadata["date"]
		d, t = metadata["date"].split(" ")

		#
		# Do we already have a matching post? If so say no
		#
		matchingPost = postservice.getPostByDateAndSlug(
			year=dthelper.getYear(date=d),
			month=dthelper.getMonth(date=d),
			slug=metadata["slug"]
		)

		if matchingPost:
			raise Exception("Already have a post that matches this slug, year and month")

		postservice.createPost(
			title             = metadata["title"],
			author            = possibleAuthors[0],
			slug              = metadata["slug"],
			content           = content,
			createdDateTime   = metadata["date"],
			tags              = metadata["tags"],
			status            = status,
			publishedDateTime = metadata["date"],
			publishedMonth    = d,
			publishedYear     = d
		)


	except Exception as e:
		logger.error(e.message, exc_info=True)
		return e.message

	finally:
		try:
			os.remove(fullUploadedFilePath)

		except OSError as ose:
			logger.error(ose.message, exc_info=True)

	return "ok"