{
  "nodes": [
    {
      "parameters": {
        "content": "## Everything you can change\n\n- The second node holds the three folder IDs, the GoHighLevel location, accounts and post status, the brand voice, the call to action and the whole prompt. Edit it and the change carries through the rest of the flow.\n- Nothing else in this workflow has a value typed into it, so new folders or a reworded prompt never means rebuilding anything.",
        "height": 300,
        "width": 480,
        "color": 4
      },
      "id": "everything-you-can-change",
      "name": "Everything you can change",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        260,
        -420
      ]
    },
    {
      "parameters": {
        "content": "## When a file does not make it\n\n- A file type nobody asked for, or an answer from the model that came back unreadable, lands on this lane instead of stopping the run.\n- The file moves to Failed carrying the reason, so the next person can open the folder and see what to fix.",
        "height": 260,
        "width": 480,
        "color": 3
      },
      "id": "when-a-file-does-not-make-it",
      "name": "When a file does not make it",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1180,
        620
      ]
    },
    {
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        },
        "triggerOn": "specificFolder",
        "folderToWatch": {
          "__rl": true,
          "mode": "id",
          "value": "1kBaysideUploadsDemo9Xq2"
        },
        "event": "fileCreated",
        "options": {}
      },
      "id": "watch-uploads-folder",
      "name": "Watch the uploads folder for new files",
      "type": "n8n-nodes-base.googleDriveTrigger",
      "typeVersion": 1,
      "position": [
        -280,
        60
      ],
      "credentials": {
        "googleDriveOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// EVERYTHING YOU CAN CHANGE LIVES IN THIS BLOCK.\n// Drive folders, GoHighLevel IDs, the brand voice and the prompt are all\n// here. No other node in this workflow holds a fixed value of its own.\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst SETTINGS = {\n  // Grab each ID from the end of the folder's Drive URL.\n  folders: {\n    uploads: '1kBaysideUploadsDemo9Xq2',\n    published: '1kBaysidePublishedDemo7Lm4',\n    failed: '1kBaysideFailedDemo3Rt8',\n  },\n\n  ghl: {\n    locationId: 'Wm8QpL2xTvBaysideDemo',\n    accountIds: ['aFbBaysideFacebookDemo1029384756', 'aFbBaysideInstagramDemo1029384757'],\n    userId: 'usrBaysideDemo4820',\n    postStatus: 'draft',   // draft, scheduled, published\n    postType: 'post',      // post, story, reel\n  },\n\n  brand: {\n    name: 'Bayside Fitness Club',\n    website: 'bayside-fit.example.com',\n    voice: 'a neighborhood gym that talks like a person and never sounds salesy',\n    callToAction: 'Book a free week at bayside-fit.example.com',\n    hashtagCount: 5,\n    model: 'gpt-4o',\n  },\n\n  // Anything not on these lists gets filed under Failed instead of guessed at.\n  fileTypes: {\n    pictures: ['jpg', 'jpeg', 'png', 'webp', 'heic'],\n    videos: ['mp4', 'mov', 'm4v', 'webm'],\n  },\n};\n\n// The prompt. Reword any of it. Keep the last paragraph so the answer still\n// comes back as JSON the next node can read.\nconst PROMPT = [\n  'You write social posts for ' + SETTINGS.brand.name + ' (' + SETTINGS.brand.website + ').',\n  '',\n  'Voice: ' + SETTINGS.brand.voice + '.',\n  'Write the way you would text a friend. Short sentences. No marketing words, no emojis, no em dashes, no lists of three. Do not open with a greeting and do not close with a summary line. Never say reaching out or excited to share.',\n  '',\n  'Write a caption of 2 to 4 sentences about what is actually in this file, ' + SETTINGS.brand.hashtagCount + ' hashtags a local person would really search, and this call to action word for word: \"' + SETTINGS.brand.callToAction + '\"',\n  '',\n  'Reply with a JSON object and nothing else. No code fence, no sentence before or after it. Use exactly these keys: caption, hashtags (an array of strings, each one starting with #), call_to_action.',\n].join('\\n');\n\n// \u2500\u2500 Below here is plumbing. You should not need to touch it. \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst file = $json;\nconst fileId = file.id || file.fileId || '';\nconst fileName = file.name || file.title || 'untitled';\nconst mimeType = file.mimeType || '';\nconst ext = fileName.includes('.') ? fileName.split('.').pop().toLowerCase() : '';\n\nlet kind = 'other';\nif (mimeType.startsWith('image/') || SETTINGS.fileTypes.pictures.includes(ext)) {\n  kind = 'picture';\n} else if (mimeType.startsWith('video/') || SETTINGS.fileTypes.videos.includes(ext)) {\n  kind = 'video';\n}\n\nconst videoPrompt = PROMPT + '\\n\\n' +\n  'You cannot watch the video. Write the post from the file name \"' + fileName + '\" and from what ' +\n  SETTINGS.brand.name + ' does. If the name says nothing useful, keep the caption general and true.';\n\nreturn {\n  json: {\n    fileId,\n    fileName,\n    mimeType,\n    ext,\n    kind,\n    mediaType: kind === 'video' ? 'video' : 'image',\n    directLink: 'https://drive.google.com/uc?export=download&id=' + fileId,\n    prompt: PROMPT,\n    videoPrompt,\n    settings: SETTINGS,\n  },\n};\n"
      },
      "id": "settings-you-can-change",
      "name": "Settings you can change",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -40,
        60
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.kind }}",
                    "rightValue": "picture",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Picture"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.kind }}",
                    "rightValue": "video",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Video"
            }
          ]
        },
        "options": {
          "fallbackOutput": "extra",
          "renameFallbackOutput": "Something else"
        }
      },
      "id": "is-it-a-picture-or-video",
      "name": "Is it a picture, a video, or something else?",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        200,
        60
      ]
    },
    {
      "parameters": {
        "resource": "file",
        "operation": "download",
        "fileId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $json.fileId }}"
        },
        "options": {}
      },
      "id": "download-the-picture",
      "name": "Download the picture",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        460,
        -80
      ],
      "credentials": {
        "googleDriveOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "resource": "image",
        "operation": "analyze",
        "modelId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Settings you can change').item.json.settings.brand.model }}"
        },
        "text": "={{ $('Settings you can change').item.json.prompt }}",
        "inputType": "base64",
        "options": {
          "detail": "high",
          "maxTokens": 700
        }
      },
      "id": "openai-reads-the-picture",
      "name": "OpenAI looks at the picture and writes the post",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 1.8,
      "position": [
        700,
        -80
      ],
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "resource": "text",
        "operation": "message",
        "modelId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $json.settings.brand.model }}"
        },
        "messages": {
          "values": [
            {
              "role": "system",
              "content": "={{ $json.videoPrompt }}"
            },
            {
              "role": "user",
              "content": "=The file is a video named {{ $json.fileName }}. Write the post for it."
            }
          ]
        },
        "options": {}
      },
      "id": "openai-writes-from-video-name",
      "name": "OpenAI writes the post from the video's name",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 1.8,
      "position": [
        700,
        180
      ],
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// Turn the model's answer into one block of post text.\nlet reply = $json.content ?? $json.message?.content ?? $json.text ?? $json.output ?? $json;\n\nif (Array.isArray(reply)) {\n  const textBlock = reply.find(block => typeof block?.text === 'string') ?? reply[0];\n  reply = textBlock?.text ?? textBlock;\n}\nif (reply && typeof reply === 'object' && typeof reply.text === 'string') {\n  reply = reply.text;\n}\nif (typeof reply === 'string') {\n  reply = JSON.parse(reply.replace(/```(?:json)?/g, '').trim());\n}\n\nconst file = $('Settings you can change').item.json;\n\nconst caption = String(reply?.caption ?? '').trim();\n\nconst rawTags = Array.isArray(reply?.hashtags)\n  ? reply.hashtags\n  : String(reply?.hashtags ?? '').split(/[\\s,]+/);\nconst hashtags = rawTags\n  .map(tag => String(tag).trim())\n  .filter(Boolean)\n  .map(tag => (tag.startsWith('#') ? tag : '#' + tag));\n\nconst callToAction = String(reply?.call_to_action || file.settings.brand.callToAction).trim();\n\nif (!caption) {\n  throw new Error('The model came back without a caption.');\n}\n\nreturn {\n  json: {\n    ...file,\n    caption,\n    hashtags,\n    callToAction,\n    summary: [caption, callToAction, hashtags.join(' ')].filter(Boolean).join('\\n\\n'),\n  },\n};\n"
      },
      "id": "tidy-up-what-openai-wrote",
      "name": "Tidy up what OpenAI wrote",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        960,
        40
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "resource": "file",
        "operation": "share",
        "fileId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $json.fileId }}"
        },
        "permissionsUi": {
          "permissionsValues": {
            "role": "reader",
            "type": "anyone"
          }
        },
        "options": {}
      },
      "id": "let-the-file-be-viewed-by-link",
      "name": "Let the file be viewed by link",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        1200,
        40
      ],
      "credentials": {
        "googleDriveOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://services.leadconnectorhq.com/medias/upload-file",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Version",
              "value": "2021-07-28"
            }
          ]
        },
        "sendBody": true,
        "contentType": "multipart-form-data",
        "bodyParameters": {
          "parameters": [
            {
              "name": "hosted",
              "value": "true"
            },
            {
              "name": "fileUrl",
              "value": "={{ $('Settings you can change').item.json.directLink }}"
            },
            {
              "name": "name",
              "value": "={{ $('Settings you can change').item.json.fileName }}"
            }
          ]
        },
        "options": {}
      },
      "id": "put-file-on-ghl-media-library",
      "name": "Put the file on GoHighLevel's media library",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1440,
        40
      ],
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      },
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://services.leadconnectorhq.com/social-media-posting/{{ $('Settings you can change').item.json.settings.ghl.locationId }}/posts",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Version",
              "value": "2021-07-28"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ accountIds: $('Settings you can change').item.json.settings.ghl.accountIds, summary: $('Tidy up what OpenAI wrote').item.json.summary, media: [{ url: ($json.url || $json.fileUrl || $json.file?.url || $('Settings you can change').item.json.directLink), type: $('Settings you can change').item.json.mediaType, caption: $('Tidy up what OpenAI wrote').item.json.caption }], status: $('Settings you can change').item.json.settings.ghl.postStatus, type: $('Settings you can change').item.json.settings.ghl.postType, userId: $('Settings you can change').item.json.settings.ghl.userId, createdBy: $('Settings you can change').item.json.settings.ghl.userId }) }}",
        "options": {}
      },
      "id": "create-the-draft-post",
      "name": "Create the draft post in the Social Planner",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1680,
        40
      ],
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      },
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "resource": "file",
        "operation": "move",
        "fileId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Settings you can change').item.json.fileId }}"
        },
        "driveId": {
          "__rl": true,
          "mode": "list",
          "value": "My Drive",
          "cachedResultName": "My Drive"
        },
        "folderId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Settings you can change').item.json.settings.folders.published }}"
        }
      },
      "id": "move-file-to-published",
      "name": "Move the file to the Published folder",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        1920,
        40
      ],
      "credentials": {
        "googleDriveOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// Anything that lands here gets filed under Failed with a reason attached,\n// so nobody has to open the execution log to find out what happened.\nlet file;\ntry {\n  file = $('Settings you can change').item.json;\n} catch (err) {\n  file = $('Settings you can change').first().json;\n}\n\nlet reason = $json?.error?.message || $json?.error?.description || $json?.error;\n\nif (!reason && file.kind === 'other') {\n  reason = 'This workflow handles pictures and videos. A ' + (file.ext || file.mimeType || 'file of this type') + ' is not on the list in the settings node.';\n}\nif (!reason) {\n  reason = 'The run stopped before the draft post was created.';\n}\n\nreturn {\n  json: {\n    fileId: file.fileId,\n    fileName: file.fileName,\n    failedFolderId: file.settings.folders.failed,\n    reason: String(reason),\n    failedAt: $execution.id,\n  },\n};\n"
      },
      "id": "note-why-the-file-did-not-post",
      "name": "Note why the file did not make a post",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1440,
        480
      ]
    },
    {
      "parameters": {
        "resource": "file",
        "operation": "move",
        "fileId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $json.fileId }}"
        },
        "driveId": {
          "__rl": true,
          "mode": "list",
          "value": "My Drive",
          "cachedResultName": "My Drive"
        },
        "folderId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $json.failedFolderId }}"
        }
      },
      "id": "move-file-to-failed",
      "name": "Move the file to the Failed folder",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        1680,
        480
      ],
      "credentials": {
        "googleDriveOAuth2Api": {
          "name": "<your credential>"
        }
      }
    }
  ],
  "connections": {
    "Watch the uploads folder for new files": {
      "main": [
        [
          {
            "node": "Settings you can change",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings you can change": {
      "main": [
        [
          {
            "node": "Is it a picture, a video, or something else?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Is it a picture, a video, or something else?": {
      "main": [
        [
          {
            "node": "Download the picture",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "OpenAI writes the post from the video's name",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Note why the file did not make a post",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download the picture": {
      "main": [
        [
          {
            "node": "OpenAI looks at the picture and writes the post",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Note why the file did not make a post",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI looks at the picture and writes the post": {
      "main": [
        [
          {
            "node": "Tidy up what OpenAI wrote",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Note why the file did not make a post",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI writes the post from the video's name": {
      "main": [
        [
          {
            "node": "Tidy up what OpenAI wrote",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Note why the file did not make a post",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tidy up what OpenAI wrote": {
      "main": [
        [
          {
            "node": "Let the file be viewed by link",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Note why the file did not make a post",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Let the file be viewed by link": {
      "main": [
        [
          {
            "node": "Put the file on GoHighLevel's media library",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Note why the file did not make a post",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Put the file on GoHighLevel's media library": {
      "main": [
        [
          {
            "node": "Create the draft post in the Social Planner",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Note why the file did not make a post",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create the draft post in the Social Planner": {
      "main": [
        [
          {
            "node": "Move the file to the Published folder",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Note why the file did not make a post",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Note why the file did not make a post": {
      "main": [
        [
          {
            "node": "Move the file to the Failed folder",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}