diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..cf4c669 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,13 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch Package", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}/glee.go", + "args": ["sample_post.md"] + } + ] +} diff --git a/ghost_upload_image.py b/ghost_upload_image.py index 64b4a94..54849d8 100644 --- a/ghost_upload_image.py +++ b/ghost_upload_image.py @@ -28,14 +28,17 @@ def upload_to_ghost(token, image, hash_name, blog_image_list, logging): if hash_value in image_name: logging.debug(f"The image {name} already exists and is being reused.") return name - + print("image",image) + print("hash_name",hash_name) mulit_encoder = MultipartEncoder( fields={ "file": (hash_name, open(image, "rb"), "image/png"), "ref": hash_name, } ) + # print(mulit_encoder, "mulit_encoder") boundary_value = mulit_encoder.boundary_value + # print(boundary_value, "boundary_value") response = {} response = requests.post( POSTS_API_BASE, diff --git a/glee.go b/glee.go index de089f5..0fa431f 100644 --- a/glee.go +++ b/glee.go @@ -6,12 +6,14 @@ import ( "encoding/hex" "encoding/json" "errors" - "flag" + "fmt" "io" "io/ioutil" "mime" + "mime/multipart" "net/http" + "net/textproto" "os" "os/user" "path/filepath" @@ -26,6 +28,7 @@ import ( "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/ghodss/yaml" + "github.com/jessevdk/go-flags" "github.com/pelletier/go-toml" // "github.com/russross/blackfriday/v2" @@ -54,6 +57,13 @@ type ResponseData struct { Posts []Post `json:"posts"` } +var opts struct { + ShowConfig bool `short:"c" long:"config" description:"Show glee configuration global file"` + Debug bool `short:"d" long:"debug" description:"debug mode"` + File string `description:"Markdown file to process"` + Help bool `short:"h" long:"help" description:"Show this help message"` +} + var postsApiBase string var buf bytes.Buffer @@ -110,7 +120,7 @@ func getPostId(slug string, headers http.Header) (*Post, error) { if resp.StatusCode == http.StatusNotFound { return nil, nil } - return nil, fmt.Errorf("Unable to communicate with the Ghost Admin API: %s", body) + return nil, fmt.Errorf("unable to communicate with the Ghost Admin API: %s", body) } var data ResponseData @@ -123,7 +133,7 @@ func getPostId(slug string, headers http.Header) (*Post, error) { return &data.Posts[0], nil } - return nil, errors.New("No posts found for the given slug") + return nil, errors.New("no posts found for the given slug") } func toHTML(markdown string) string { @@ -154,14 +164,13 @@ func initLogging(debug bool) { } func addBlogConfigurations(meta map[string]interface{}) map[string]interface{} { - // Check if config is nil if config == nil { - log.Fatal("Configuration is not initialized. Call viewTOMLFile to initialize it.") + log.Fatal("Configuration is not initialized. Call loadGlobalConfig to initialize it.") } globalSidebarTOC := config.GetDefault("blog-configuration.SIDEBAR_TOC", "").(bool) - globalFeatured := config.GetDefault("blog-configuration.FEATURED", "").(bool) - globalStatus := config.GetDefault("blog-configuration.STATUS", "").(string) + // globalFeatured := config.GetDefault("blog-configuration.FEATURED", "").(bool) + // globalStatus := config.GetDefault("blog-configuration.STATUS", "").(string) defaultStyle := `pre { line-height: 125%; } td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } @@ -259,33 +268,26 @@ func addBlogConfigurations(meta map[string]interface{}) map[string]interface{} { } ` - // Append the default styles to the head - // Ensure meta["codeinjection_head"] is a string before appending if existingHead, ok := meta["codeinjection_head"].(string); ok { meta["codeinjection_head"] = existingHead + "" } else { meta["codeinjection_head"] = "" } - - // Conditionally append sidebar TOC head and footer + if globalSidebarTOC { if existingHead, ok := meta["codeinjection_head"].(string); ok { meta["codeinjection_head"] = existingHead + sidebarTocHead + log.Debug("Done Sidebar TOC Code injection") } else { meta["codeinjection_head"] = sidebarTocHead } meta["codeinjection_foot"] = sidebarTocFooter } - // Assuming meta is a map[string]interface{}, add or update relevant fields - fmt.Printf("SIDEBAR_TOC: %v\n", globalSidebarTOC) - fmt.Printf("FEATURED: %v\n", globalFeatured) - fmt.Printf("STATUS: %v\n", globalStatus) - return meta } -func viewTOMLFile() { +func loadGlobalConfig() { configPath := filepath.Join(os.Getenv("HOME"), ".glee.toml") var err error config, err = toml.LoadFile(configPath) @@ -296,10 +298,10 @@ func viewTOMLFile() { } func getTOMLFile(configPath string) { - fmt.Printf("The configuration file at %s was not found.\n", configPath) + log.Error("The configuration file at %s was not found.\n", configPath) var configResponse string - fmt.Print("Would you like me to create the configuration file? (yes/no): ") + log.Info("Would you like me to create the configuration file? (yes/no): ") fmt.Scanln(&configResponse) if configResponse == "yes" || configResponse == "y" { @@ -322,7 +324,6 @@ func makeRequest(headers http.Header, body map[string]interface{}, pid string, u postsApiBase = ghostUrl + "/api/" + ghostVersion + "/admin/posts/" } if pid == "" { - // fmt.Printf("%#v\n", body) method = http.MethodPost apiEndpoint = postsApiBase + "?source=html" } else { @@ -334,13 +335,13 @@ func makeRequest(headers http.Header, body map[string]interface{}, pid string, u client := &http.Client{} bodyJson, err := json.Marshal(body) if err != nil { - fmt.Println("Error marshaling body to JSON:", err) + log.Error("Error marshaling body to JSON:", err) return } req, err := http.NewRequest(method, apiEndpoint, bytes.NewBuffer(bodyJson)) if err != nil { - fmt.Println("Error creating request:", err) + log.Error("Error creating request:", err) return } req.Header = headers @@ -348,19 +349,18 @@ func makeRequest(headers http.Header, body map[string]interface{}, pid string, u resp, err := client.Do(req) if err != nil { - fmt.Println("Error executing request:", err) + log.Error("Error executing request:", err) return } defer resp.Body.Close() if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { var errorMessage string - errorBytes, _ := ioutil.ReadAll(resp.Body) // Read the response body - if err := json.Unmarshal(errorBytes, &errorMessage); err != nil { - // If the error message is not JSON, just use the raw response body + errorBytes, _ := ioutil.ReadAll(resp.Body) + if err := json.Unmarshal(errorBytes, &errorMessage); err != nil { errorMessage = string(errorBytes) } - fmt.Printf("Request failed with status: %s. Error message: %s\n", resp.Status, errorMessage) + log.Error("Request failed with status: %s. Error message: %s\n", resp.Status, errorMessage) return } @@ -368,21 +368,19 @@ func makeRequest(headers http.Header, body map[string]interface{}, pid string, u var responseData map[string]interface{} err = json.NewDecoder(resp.Body).Decode(&responseData) if err != nil { - fmt.Println("Error unmarshaling response:", err) + log.Error("Error unmarshaling response:", err) return } // Log the result if pid == "" { - fmt.Println("Created new post") + log.Info("Created new post") } else { - fmt.Println("Updated existing post based on slug") + log.Info("Updated existing post based on slug") } fmt.Printf("Blog preview link: %s\n", responseData["posts"].([]interface{})[0].(map[string]interface{})["url"]) } - - func injectMultiTitles(meta map[string]interface{}) error { meta["codeinjection_head"] = "" @@ -390,23 +388,26 @@ func injectMultiTitles(meta map[string]interface{}) error { if !ok { titleDataMap, ok := meta["title"].(map[string]interface{}) if !ok { - return fmt.Errorf("missing default title") + log.Error("missing default title") + return nil } defaultTitle, ok := titleDataMap["default"].(string) if !ok { - return fmt.Errorf("missing 'default' key in title_data") + log.Error("missing default title in multi-title") + return nil } meta["title"] = defaultTitle titleDataBytes, err := json.Marshal(titleDataMap) if err != nil { - log.Printf("error marshaling title data: %v", err) + log.Error("error marshaling title data: %v", err) return err } titleDataStr := string(titleDataBytes) + log.Debug("multi title: ", titleDataStr) meta["codeinjection_head"] = fmt.Sprintf(`