소스 검색

Updates on blog module

TC pushbot 5 4 년 전
부모
커밋
f17b5cc3ee

+ 56 - 0
web/Blog/backend/helper.js

@@ -11,6 +11,62 @@ function filepathClean(webroot){
     return webroot;
 }
 
+//Generate a quick summary for post object
+function extractPostInfo(filepath){
+    var content = filelib.readFile(filepath);
+    var postObject = JSON.parse(content);
+
+    var title = "Untitled";
+    var content = "(This post has no content)";
+    var tags = [];
+
+    if (typeof postObject.Title != "undefined"){
+        title = postObject.Title
+    }
+
+    if (typeof postObject.Content != "undefined"){
+        content = postObject.Content;
+        if (content.split(" ").length > 100){
+            //Trim the content off if it is longer than 100 words
+            var words = content.split(" ");
+            var trimmedContent = "";
+            for (var i = 0; i < 100; i++){
+                trimmedContent = trimmedContent + words[i] + " ";
+            }
+
+            trimmedContent = trimmedContent + "..."
+            content = trimmedContent;
+        }else if (content.length > 300){
+            //To handle lang with no space, like Cantonese
+            var trimmedContent = content.substr(0, 300) + "..."
+            content = trimmedContent;
+        }
+    }
+
+    if (typeof postObject.Tags != "undefined"){
+        tags = postObject.Tags
+    }
+
+    return [title, content, tags];
+}
+
+
+function loadFooter(){
+    //WIP
+    var footerTemplate = appdata.readFile("Blog/template/footer.html");
+    if (footerTemplate == false){
+        return "Powered by ArozOS Blog Engine";
+    }else{
+        return footerTemplate;
+    }
+}
+
+function loadBlogInfo(){
+    //WIP
+    return ["My Blog", "An amazing blog written by me!"]
+}
+
+
 function retrunErrorObject(message){
     sendJSONResp(JSON.stringify({
         error: message

+ 37 - 0
web/Blog/backend/hidePost.js

@@ -0,0 +1,37 @@
+/*
+    Hide a published post from the blog engine
+    Require paramter:
+
+    filepath
+    webroot
+*/
+
+requirelib("filelib");
+requirelib("appdata");
+includes("config.js");
+includes("helper.js");
+includes("indexManager.js");
+
+function hidePost(postObjectName, webroot){
+    //Check public post exists
+    var publishWebPosition = filepathClean(webroot) + "/blog/posts/" + postObjectName + ".html";
+    if (filelib.fileExists(publishWebPosition)){
+        filelib.deleteFile(publishWebPosition);
+    }
+
+    sendResp("OK");
+}
+
+function getPostNameFromFilepath(path){
+    var tmp = path.split("/").pop();
+    if (tmp.indexOf(".html") >= 0){
+        tmp = tmp.replace(".html", "");
+    }else if (tmp.indexOf(".json") >= 0){
+        tmp = tmp.replace(".json", "");
+    }
+
+    return tmp;
+}
+
+var postName = getPostNameFromFilepath(filepath);
+hidePost(postName, webroot);

+ 29 - 15
web/Blog/backend/indexManager.js

@@ -7,6 +7,7 @@
 
 includes("helper.js");
 
+//Get the current post in the system
 function getIndexList(webroot){
     webroot = filepathClean(webroot);
     var indexFile = webroot + "/blog/posts.json"
@@ -22,6 +23,7 @@ function getIndexList(webroot){
     }
 }
 
+//Write new index list into the list
 function writeIndexList(webroot, newListObject){
     webroot = filepathClean(webroot);
     var indexFile = webroot + "/blog/posts.json"
@@ -31,35 +33,47 @@ function writeIndexList(webroot, newListObject){
 //This inject a new title into the post list
 function injectTitleIntoPostList(webroot, postObjectName){
     var currentIndexList = getIndexList(webroot);
-    if (currentIndexList.indexOf(postObjectName) > 0){
-        //Already exists in the list. No need to add it in
+    var postObjectPath = filepathClean(getBlogPostStore()) + "/posts/" + postObjectName + ".json";
+    var summary = extractPostInfo(postObjectPath);
 
-    }else{
-        //Push to the list
-        currentIndexList.push(postObjectName);
-        writeIndexList(webroot,currentIndexList);
+    var newIndexList = [];
+    for (var i = 0; i < currentIndexList.length; i++){
+        if (currentIndexList[i].name != postObjectName){
+            //Only push index list that is not this one
+            newIndexList.push(currentIndexList[i]);
+        }
     }
+
+    currentIndexList = newIndexList;
+
+    //Push to the list
+    currentIndexList.push({
+        name: postObjectName, 
+        summary: summary
+    });
+    writeIndexList(webroot,currentIndexList);
+    
 }
 
 //This remove a post from the post list base on title
 function removeTitleFromPostList(webroot, postObjectName){
     var currentIndexList = getIndexList(webroot);
-    if (currentIndexList.indexOf(postObjectName) > 0){
-        //Already removed
+    var postExists = false;
 
-    }else{
+    for (var i = 0; i < currentIndexList.length; i++){
+        if (currentIndexList[i].name == postObjectName){
+            postExists = true;
+        }
+    }
+
+    if (postExists){
         var newarray = [];
         for (var i = 0; i < currentIndexList.length; i++){
             var thisIndex = currentIndexList[i];
-            if (thisIndex != postObjectName){
+            if (thisIndex.name != postObjectName){
                 newarray.push(thisIndex);
             }
         }
         writeIndexList(webroot, newarray);
     }
 }
-
-//Get the current post in the system
-function getCurrentPostList(webroot, ){
-
-}

+ 7 - 0
web/Blog/backend/jsondb.js

@@ -0,0 +1,7 @@
+/*
+
+    JSON Database
+
+    For easier migration in the future
+
+*/

+ 22 - 72
web/Blog/backend/listPosts.js

@@ -4,6 +4,8 @@
 
     This script list all the post within the system
 
+    Require paramter:
+    webroot //The web deploy root of this user
 */
 
 //Require the file library
@@ -11,99 +13,47 @@ requirelib("filelib");
 
 //Require the internal library for handling the path of blog posting
 includes("config.js");
+includes("helper.js");
 
 var blogPostStorage = getBlogPostStore();
 
-function extractPostInfo(filepath){
-    var content = filelib.readFile(filepath);
-    var postObject = JSON.parse(content);
-
-    var title = "Untitled";
-    var content = "(This post has no content)";
-    var tags = [];
-
-    if (typeof postObject.Title != "undefined"){
-        title = postObject.Title
-    }
-
-    if (typeof postObject.Content != "undefined"){
-        content = postObject.Content;
-        if (content.split(" ").length > 100){
-            //Trim the content off if it is longer than 100 words
-            var words = content.split(" ");
-            var trimmedContent = "";
-            for (var i = 0; i < 100; i++){
-                trimmedContent = trimmedContent + words[i] + " ";
-            }
-
-            trimmedContent = trimmedContent + "..."
-            content = trimmedContent;
-        }else if (content.length > 300){
-            //To handle lang with no space, like Cantonese
-            var trimmedContent = content.substr(0, 300) + "..."
-            content = trimmedContent;
-        }
-    }
-
-    if (typeof postObject.Tags != "undefined"){
-        tags = postObject.Tags
-    }
-
-    return [title, content, tags];
-}
-
 function main(){
     //Filter out the last / if exists
-    if (blogPostStorage.substr(blogPostStorage.length - 1, 1) == "/"){
-        blogPostStorage = blogPostStorage.substr(0, blogPostStorage.length - 1);
-    }
+    blogPostStorage = filepathClean(blogPostStorage);
 
-    //If it doesn't exists
-    filelib.mkdir(blogPostStorage + "/public");
-    filelib.mkdir(blogPostStorage + "/private");
+    filelib.mkdir(blogPostStorage + "/posts/");
 
     //List all the created post
-    var publicPosts = filelib.aglob(blogPostStorage + "/public/*.json","reverse");
-    var privatePosts = filelib.aglob(blogPostStorage + "/private/*.json","reverse");
+    var posts = filelib.aglob(blogPostStorage + "/posts/*.json","reverse");
 
-
-
-    var posts = [];
-    for(var i = 0; i < publicPosts.length; i++){
+    var renderedPostList = [];
+    for(var i = 0; i < posts.length; i++){
         //Extract post information
-        var postInfo = extractPostInfo( publicPosts[i]);
+        var postInfo = extractPostInfo( posts[i]);
 
         //Get the poost modification time
-        var modTime = filelib.mtime(publicPosts[i], false);
-
-        posts.push({
-            "title": postInfo[0],
-            "content":postInfo[1],
-            "tags": postInfo[2],
-            "modtime": modTime,
-            "view": "public",
-            "filepath": publicPosts[i]
-        });
-    }
-
-    for(var i = 0; i < privatePosts.length; i++){
-        var postInfo = extractPostInfo( privatePosts[i]);
-
-        //Get the poost modification time
-        var modTime = filelib.mtime(privatePosts[i], false);
+        var modTime = filelib.mtime(posts[i], false);
+
+        //Check if this post is published
+        webroot = filepathClean(webroot);
+        var postView = "private";
+        var postfilename = posts[i].split("/").pop().replace(".json", ".html");
+        if (filelib.fileExists(webroot + "/blog/posts/" + postfilename)){
+            postView = "public";
+        }
 
-        posts.push({
+        renderedPostList.push({
             "title": postInfo[0],
             "content":postInfo[1],
             "tags": postInfo[2],
             "modtime": modTime,
-            "view": "private",
-            "filepath": privatePosts[i]
+            "view": postView,
+            "filepath": posts[i]
         });
     }
 
     //Return the value of the posts
-    sendJSONResp(JSON.stringify(posts));
+    sendJSONResp(JSON.stringify(renderedPostList));
 }
 
 main();

+ 5 - 17
web/Blog/backend/publish.js

@@ -29,22 +29,8 @@ function applyTemplate(templateFilepath, templateObjects){
     return templateContent;
 }
 
-function loadFooter(){
-    var footerTemplate = appdata.readFile("Blog/template/footer.html");
-    if (footerTemplate == false){
-        return "Powered by ArozOS Blog Engine";
-    }else{
-        return footerTemplate;
-    }
-}
-
-function loadBlogInfo(){
-    return ["My Blog", "An amazing blog written by me!"]
-}
-
-
 //Main function to publish the file to webroot
-function publish(){
+function publish(filepath, webroot){
     //Check if the blog post object exists
     if (!filelib.fileExists(filepath)){
         retrunErrorObject("Given post not exists: " + filepath);
@@ -88,8 +74,10 @@ function publish(){
     filelib.writeFile(targetPostLocation, renderedPage);
 
     //Update the index file
-    injectTitleIntoPostList(webroot, postObjectName)
+    injectTitleIntoPostList(webroot, postObjectName);
 
 }
 
-publish();
+if (typeof(runAsFunc) == "undefined"){
+    publish(filepath, webroot);
+}

+ 19 - 1
web/Blog/backend/savePost.js

@@ -7,18 +7,28 @@
     - title
     - tags
     - content (HTML, not markdown)
+    - webroot (Web deploy root)
 */
 
 //Require libraries
 includes("config.js")
+includes("helper.js")
 
 function main(){
     //Get a safe title from removing all special characters
     var safeTitle = title.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
-    var saveFilename =  getBlogPostStore() + "private/" +  Date.now() + "-" + safeTitle + ".json"
+    var postObjectName =  Date.now() + "-" + safeTitle;
+    var saveFilename =  getBlogPostStore() + "posts/" +  postObjectName + ".json"
     if (filepath == "" || !filelib.fileExists(filepath)){
         //This is a new file or the original file not exists. Assign a filename for it
        filepath = saveFilename;
+    }else{
+        //Extract the post object name from the path
+        var tmp = filepath.split("/").pop();
+        var fname = tmp.split(".");
+        fname.pop();
+        postObjectName = fname.join(".");
+        console.log(postObjectName);
     }
 
     //Generate tags array
@@ -43,6 +53,14 @@ function main(){
     var postObjectEncoded = JSON.stringify(blogObject);
     filelib.writeFile(filepath, postObjectEncoded);
 
+    //Check if this is published. IF yes, update the render as well
+    var publishWebPosition = filepathClean(webroot) + "/blog/posts/" + postObjectName + ".html";
+    if (filelib.fileExists(publishWebPosition)){
+        includes("publish.js");
+        var runAsFunc = true;
+        publish(filepath, webroot)
+    }
+
     //Send back the filepath for save confirmation
     sendResp(filepath);
 }

+ 19 - 1
web/Blog/editor.html

@@ -129,6 +129,7 @@
 			var editingFile = "";
 			var inputFiles = ao_module_loadInputFiles();
 			var editorWindow = $("#editorFrame")[0].contentWindow;
+			var currentWebDeployRoot = "";
 			
 			if (inputFiles != null && inputFiles.length > 0){
 				//Edit  mode
@@ -138,6 +139,8 @@
 				
 			}
 
+			getWebRoot();
+
 			function newEditor(){
 				editorWindow.newEditor();
 			}
@@ -194,7 +197,8 @@
 					filepath: editingFile,
 					title: title,
 					tags: tags,
-					content: postContent
+					content: postContent,
+					webroot: currentWebDeployRoot
 				}, function(data){
 					if (data.error !== undefined){
 						alert(data.error);
@@ -213,6 +217,20 @@
 					window.location.href = "index.html"
 				}
 			}
+
+			function getWebRoot(callback = undefined){
+				$.get("../system/network/www/webRoot", function(data){
+					if (data == null || data == "" || data == undefined){
+						callback("");
+						return;
+					}
+					currentWebDeployRoot = data;
+					if (callback != undefined){
+						callback(data);
+					}
+					
+				});
+			}
 		</script>
 	</body>
 </html>

+ 27 - 5
web/Blog/index.html

@@ -107,11 +107,12 @@
 		<script>
 			var currentWebDeployRoot = "";
 
-			//List all the post stored in the system
-			listPost();
 
 			//Get the current web root path
-			getWebRoot();
+			getWebRoot(function(){
+				//List all the post stored in the system
+				listPost();
+			});
 
 			function openPost(object){
 				//Parse the file object following ArozOS file descriptor protocol
@@ -142,12 +143,28 @@
 				publishPost(filepath);
 			}
 
+			function hidePostButton(btn){
+					var filepath = $(btn).attr('filepath');
+					$(btn).addClass("loading");
+					ao_module_agirun("Blog/backend/hidePost.js",{
+						webroot: currentWebDeployRoot,
+						filepath: filepath
+					}, function(data){
+						listPost();
+						$(btn).removeClass("loading");
+					}, function(){
+						//failed return
+						$(btn).removeClass("loading");
+					})
+				}
+
 			function publishPost(filepath){
 				ao_module_agirun("Blog/backend/publish.js", {
 					filepath: filepath,
 					webroot: currentWebDeployRoot
 				}, function(data){
 					console.log(data);
+					listPost();
 				})
 			}
 
@@ -190,7 +207,10 @@
 			}
 
 			function listPost(){
-				ao_module_agirun("Blog/backend/listPosts.js", {}, function(data){
+				$("#postList").html(``);
+				ao_module_agirun("Blog/backend/listPosts.js", {
+					webroot: currentWebDeployRoot
+				}, function(data){
 					if (data.length == 0){
 						//There is no post in the system
 						$("#postList").html(`<div class="ts segment post">
@@ -250,7 +270,7 @@
 							${stripHtml(post.content)}
 			
 							<div class="postControls">
-								<button style="${publicPostOnly}" class="ts mini icon button blog red" title="Hide Post"><i class="hide icon"></i></button>
+								<button onclick="hidePostButton(this);" filepath="${post.filepath}" style="${publicPostOnly}" class="ts mini icon button blog red" title="Hide Post"><i class="hide icon"></i></button>
 								<button onclick="publishPostButton(this);" filepath="${post.filepath}" style="${privatePostOnly}" class="ts mini icon button blog green" title="Publish Post"><i class="upload icon"></i></button>
 							</div>
 						</div>`)
@@ -258,6 +278,8 @@
 					}
 				});
 
+
+
 				function stripHtml(html){
 					let tmp = document.createElement("DIV");
 					tmp.innerHTML = html;

+ 1 - 1
web/Blog/template/post.html

@@ -34,7 +34,7 @@
 				{{post_content}}
 
 				<div class="ui divider"></div>
-				<a href="index.html"><i class="angle left icon"></i> Back</a>
+				<a href="../index.html"><i class="angle left icon"></i> Back</a>
 			</div>
 		</div>