Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,8 @@ Worker files older than approximately **30 minutes** are cleaned up when relevan
1. Install the updated `requirements.txt` (or rebuild the Docker containers).
2. In Google Cloud Console, enable **YouTube Data API v3**, configure the OAuth consent screen and, while the app is in testing, add your Google account as a test user. Download an **OAuth client secret JSON** file.
3. Open **Video Studio → YouTube upload**, choose the JSON file, and click **Connect Google / YouTube**. Approve access to the desired channel.
4. Set a YouTube title (or leave it empty to use the video headline), description, comma-separated tags, visibility, and the made-for-kids setting.
5. Enable **Automatically upload after rendering**, then render. AutoMap uploads the resulting MP4 in the background and shows progress and a YouTube link. You can also click **Upload rendered video to YouTube** after rendering. Visibility defaults to **Private**; automatic upload must be enabled again on each visit.
4. The YouTube title follows the video topic by default (up to 100 characters). Disable **Use the video topic as the YouTube title** to enter a custom title. Set the description, comma-separated tags, visibility, and the made-for-kids setting.
5. Enable **Automatically upload after rendering**, then render. AutoMap uploads the resulting MP4 in the background and shows progress and a YouTube link. You can also click **Upload rendered video to YouTube** after rendering. Visibility defaults to **Private**. Metadata, custom title, title mode, and the automatic upload setting are saved in this browser and restored when you return.

AutoMap renders vertical 9:16 videos lasting up to 30 seconds, which meet the
[YouTube Shorts format requirements](https://support.google.com/youtube/answer/15424877?hl=en).
Expand All @@ -225,8 +225,9 @@ Google tokens and client secrets are never sent back to the browser, saved in
localStorage, or forwarded to the media worker. A signed browser session selects
its own credentials and upload jobs. Sharing a browser profile shares this
connection; clearing cookies, logging out, or changing the web login requires
connecting again. **Disconnect** deletes that browser's saved credentials; it
connecting again. **Sign out of YouTube** deletes that browser's saved credentials; it
does not cancel an upload already started or revoke the grant in Google Account.
Sign in again to choose a different Google account.

For persistent server storage, retain the `automap-session` Docker volume (it
already mounts `/app/instance`). For native deployment, back up `instance/` and
Expand Down
51 changes: 42 additions & 9 deletions static/youtube-upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,27 @@
let youtubeCsrf = '';
let youtubeConnected = false;
let youtubePolling = 0;
const youtubeFields = ['youtubeTitle', 'youtubeDescription', 'youtubeTags', 'youtubePrivacy', 'youtubeKids'];
const youtubeFields = ['youtubeTitle', 'youtubeDescription', 'youtubeTags', 'youtubePrivacy', 'youtubeKids', 'youtubeAuto', 'youtubeUseTopic'];
let youtubeCustomTitle = '';
const ytElement = id => document.getElementById(id);

function syncYouTubeTitle() {
const input = ytElement('youtubeTitle');
const useTopic = ytElement('youtubeUseTopic').checked;
input.readOnly = useTopic;
input.value = useTopic ? ytElement('videoTitleInput').value.replace(/\s+/g, ' ').trim().slice(0, 100) : youtubeCustomTitle;
}

function saveYouTubeSettings() {
const settings = Object.fromEntries(youtubeFields.map(id => {
const input = ytElement(id);
return [id, id === 'youtubeTitle' ? youtubeCustomTitle : input.type === 'checkbox' ? input.checked : input.value];
}));
try { localStorage.setItem('automap-youtube-settings', JSON.stringify(settings)); } catch {}
}

function youtubeSettings() {
syncYouTubeTitle();
const settings = {
title: ytElement('youtubeTitle').value.trim() || ytElement('videoTitleInput').value.trim(),
description: ytElement('youtubeDescription').value,
Expand All @@ -29,13 +46,20 @@ async function loadYouTubeConnection() {
if (!response.ok) throw new Error(result.error || 'Could not check YouTube connection.');
youtubeCsrf = result.csrf_token;
youtubeConnected = result.connected;
ytElement('youtubeConnection').textContent = result.connected ? 'YouTube account connected.' : 'YouTube account not connected.';
ytElement('youtubeSignOut').disabled = !result.connected;
const label = result.connected ? 'Signed in to YouTube' : 'Not signed in to YouTube';
ytElement('youtubeConnection').textContent = label;
const badge = ytElement('youtubeConnectionBadge');
badge.textContent = label;
badge.className = `ml-2 text-xs font-normal ${result.connected ? 'text-emerald-400' : 'text-amber-300'}`;
ytElement('youtubeRedirect').textContent = result.redirect_uri;
return result;
})();
try { return await youtubeConnectionRequest; }
catch (error) {
ytElement('youtubeConnection').textContent = error.message;
ytElement('youtubeConnectionBadge').textContent = 'YouTube sign-in status unavailable';
ytElement('youtubeConnectionBadge').className = 'ml-2 text-xs font-normal text-slate-400';
throw error;
} finally { youtubeConnectionRequest = null; }
}
Expand Down Expand Up @@ -83,7 +107,9 @@ async function disconnectYouTube() {
try {
await youtubeRequest('/api/youtube/disconnect', {method: 'POST'});
ytElement('youtubeAuto').checked = false;
saveYouTubeSettings();
await loadYouTubeConnection();
showToast('Signed out of YouTube. Sign in again to choose another Google account.', 'info');
} catch (error) { showToast(error.message, 'error'); }
}

Expand Down Expand Up @@ -135,17 +161,24 @@ document.addEventListener('DOMContentLoaded', () => {
try {
const saved = JSON.parse(localStorage.getItem('automap-youtube-settings') || '{}');
for (const id of youtubeFields) {
if (id === 'youtubeKids') ytElement(id).checked = saved[id] === true;
else if (typeof saved[id] === 'string') ytElement(id).value = saved[id];
const input = ytElement(id);
if (input.type === 'checkbox') {
if (typeof saved[id] === 'boolean') input.checked = saved[id];
} else if (typeof saved[id] === 'string') input.value = saved[id];
}
const job = sessionStorage.getItem('automap-youtube-job');
if (job) watchYouTubeUpload(job);
} catch {}
for (const id of youtubeFields) ytElement(id).addEventListener('input', () => {
const settings = Object.fromEntries(youtubeFields.map(key => [key, key === 'youtubeKids' ? ytElement(key).checked : ytElement(key).value]));
try { localStorage.setItem('automap-youtube-settings', JSON.stringify(settings)); } catch {}
});
// Automatic upload is an explicit choice for each visit.
youtubeCustomTitle = ytElement('youtubeTitle').value;
syncYouTubeTitle();
document.addEventListener('automap:video-topic-changed', syncYouTubeTitle);
for (const id of youtubeFields) {
for (const event of ['input', 'change']) ytElement(id).addEventListener(event, () => {
if (id === 'youtubeTitle') youtubeCustomTitle = ytElement(id).value;
if (id === 'youtubeUseTopic') syncYouTubeTitle();
saveYouTubeSettings();
});
}
const outcome = new URLSearchParams(location.search).get('youtube');
if (outcome) {
ytElement('youtubePanel').open = true;
Expand Down
5 changes: 4 additions & 1 deletion templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,8 @@ <h2 class="font-display font-semibold text-sm sm:text-base text-white leading-ti
</button>
</div>

<p class="mt-1.5 text-[11px] text-slate-500">Your last topic is saved. New ideas are generated only when you click Generate idea.</p>

<!-- Quick Prompt Presets Chips -->
<div class="mt-2.5">
<div class="flex items-center justify-between mb-1.5">
Expand Down Expand Up @@ -2280,9 +2282,10 @@ <h4 class="text-xs font-semibold text-white flex items-center gap-2">
syncGsm(base + delta);
}

// Keep synchronous storage and preview DOM work out of keyboard input events.
// Save the topic immediately; debounce the more expensive preview work.
let topicPreviewTimer;
function scheduleTopicPreview(event) {
saveBrowserValue(MAP_TOPIC_STORAGE_KEY, document.getElementById('topicInput').value);
clearTimeout(topicPreviewTimer);
if (event && event.isComposing) return;
topicPreviewTimer = setTimeout(flushTopicPreview, 250);
Expand Down
10 changes: 6 additions & 4 deletions templates/video.html
Original file line number Diff line number Diff line change
Expand Up @@ -1393,7 +1393,7 @@ <h3 class="text-xs font-semibold text-slate-200 flex items-center gap-2">
</div>

<details class="p-4 rounded-xl bg-slate-950/80 border border-slate-700 space-y-3" id="youtubePanel">
<summary class="cursor-pointer text-sm font-semibold text-rose-300"><i class="fa-brands fa-youtube mr-2"></i>YouTube upload</summary>
<summary class="cursor-pointer text-sm font-semibold text-rose-300"><i class="fa-brands fa-youtube mr-2"></i>YouTube upload <span id="youtubeConnectionBadge" role="status" class="ml-2 text-xs font-normal text-slate-400">Checking sign-in…</span></summary>
<div class="space-y-3 mt-3 text-xs">
<p class="text-slate-400">Connect your channel once, then upload automatically after rendering. Credentials stay on the server.</p>
<p class="text-slate-400">Rendered videos are vertical 9:16 and up to 30 seconds long, ready for Shorts. YouTube classifies them automatically after processing.</p>
Expand All @@ -1403,12 +1403,13 @@ <h3 class="text-xs font-semibold text-slate-200 flex items-center gap-2">
<p class="text-slate-400 break-all">Web application redirect URI: <code id="youtubeRedirect">Loading…</code>. Desktop app files work on localhost.</p>
<div class="flex flex-wrap gap-2">
<button type="button" id="youtubeConnect" onclick="connectYouTube()" class="px-3 py-2 rounded-lg bg-rose-700 hover:bg-rose-600">Connect Google / YouTube</button>
<button type="button" onclick="disconnectYouTube()" class="px-3 py-2 rounded-lg bg-slate-700">Disconnect</button>
<button type="button" id="youtubeSignOut" onclick="disconnectYouTube()" disabled class="px-3 py-2 rounded-lg bg-slate-700 disabled:opacity-50">Sign out of YouTube</button>
</div>
<p id="youtubeConnection" role="status" class="text-slate-300">Checking connection…</p>
<label class="flex items-center gap-2"><input id="youtubeAuto" type="checkbox">Automatically upload after rendering</label>
<label class="block">YouTube title <span class="text-slate-400">(empty = video title)</span>
<input id="youtubeTitle" maxlength="100" class="w-full mt-1 p-2 rounded-lg bg-slate-900 border border-slate-700" placeholder="Title on YouTube">
<label class="flex items-center gap-2"><input id="youtubeUseTopic" type="checkbox" checked>Use the video topic as the YouTube title</label>
<label class="block">YouTube title <span class="text-slate-400">(up to 100 characters)</span>
<input id="youtubeTitle" maxlength="100" class="w-full mt-1 p-2 rounded-lg bg-slate-900 border border-slate-700" placeholder="Automatically filled from the video topic" readonly>
</label>
<label class="block">Description
<textarea id="youtubeDescription" rows="3" maxlength="5000" class="w-full mt-1 p-2 rounded-lg bg-slate-900 border border-slate-700"></textarea>
Expand Down Expand Up @@ -3840,6 +3841,7 @@ <h3 class="text-xs font-semibold text-slate-200 flex items-center gap-2">
}

function updateStageTitlePreview(val) {
document.dispatchEvent(new Event('automap:video-topic-changed'));
const title = (val || '').trim();
const banner = document.getElementById('stageTitleBanner');
const status = document.getElementById('titlePreviewStatus');
Expand Down
22 changes: 22 additions & 0 deletions tests/browser/test_map_palettes.py
Original file line number Diff line number Diff line change
Expand Up @@ -666,3 +666,25 @@ def test_clear_history_is_persistent_and_late_restore_cannot_resurrect_it(map_pa
}''')
assert page.locator('#historyCountBadge').inner_text() == '1'
assert 'Kept for this visit only' in page.locator('#historyStorageStatus').inner_text()


def test_topic_is_saved_immediately_and_idea_generation_requires_a_click(map_page):
page = map_page
idea_requests = []
def generate(route):
idea_requests.append(route.request.post_data_json)
route.fulfill(json={'status':'success', 'idea':'Explicitly generated idea'})
page.route('**/api/generate_idea', generate)
page.evaluate('closeFillingStudio()')
# Save while still typing, before the preview debounce or a blur event.
page.locator('#topicInput').fill('Моя остання тема')
assert page.evaluate("localStorage.getItem('automap-map-topic')") == 'Моя остання тема'
page.reload()
assert page.locator('#topicInput').input_value() == 'Моя остання тема'
assert idea_requests == []
page.locator('#generateIdeaBtn').click()
page.wait_for_function("document.getElementById('topicInput').value === 'Explicitly generated idea'")
assert len(idea_requests) == 1
page.reload()
assert page.locator('#topicInput').input_value() == 'Explicitly generated idea'
assert len(idea_requests) == 1
57 changes: 56 additions & 1 deletion tests/browser/test_video_studio.py
Original file line number Diff line number Diff line change
Expand Up @@ -755,6 +755,7 @@ def test_youtube_auto_upload_uses_metadata_and_shows_video_link(studio):
'connected': True, 'csrf_token': 'csrf-test', 'redirect_uri': 'https://automap.test/api/youtube/callback'}))
page.evaluate('loadYouTubeConnection()')
page.locator('#youtubePanel summary').click()
page.locator('#youtubeUseTopic').uncheck()
page.locator('#youtubeTitle').fill('Заголовок YouTube')
page.locator('#youtubeDescription').fill('Опис відео\n🌍')
page.locator('#youtubeTags').fill('географія, maps')
Expand Down Expand Up @@ -784,7 +785,10 @@ def render(route):
page.locator('#youtubePanel summary').click()
assert page.locator('#youtubeTitle').input_value() == 'Заголовок YouTube'
assert page.locator('#youtubeDescription').input_value() == 'Опис відео\n🌍'
assert not page.locator('#youtubeAuto').is_checked()
assert page.locator('#youtubeAuto').is_checked()
assert not page.locator('#youtubeUseTopic').is_checked()
assert page.locator('#youtubeTags').input_value() == 'географія, maps'
assert page.locator('#youtubePrivacy').input_value() == 'unlisted'
assert page.locator('#youtubeSecret').input_value() == ''


Expand All @@ -807,3 +811,54 @@ def disconnect(route):
page.evaluate("youtubeCsrf = 'old-tab-token'; youtubeRequest('/api/youtube/disconnect', {method:'POST'})")
assert requests == ['token-1', 'token-2']
assert len(status_count) == 2


def test_youtube_title_follows_video_topic_and_remembers_title_mode(studio):
page, _ = studio
page.evaluate('async () => { await window.videoStudioReady; }')
page.locator('#youtubePanel summary').click()
assert page.locator('#youtubeUseTopic').is_checked()
page.locator('#videoTitleInput').fill('Населення країн Європи')
assert page.locator('#youtubeTitle').input_value() == 'Населення країн Європи'
assert page.locator('#youtubeTitle').get_attribute('readonly') is not None
page.evaluate("document.getElementById('videoTitleInput').value = 'Нова тема'; updateStageTitlePreview('Нова тема'); saveVideoSettings()")
assert page.evaluate('youtubeSettings().title') == 'Нова тема'
page.locator('#youtubeUseTopic').uncheck()
page.locator('#youtubeTitle').fill('Custom title')
page.locator('#youtubeUseTopic').check()
assert page.locator('#youtubeTitle').input_value() == 'Нова тема'
reopen_studio(page)
page.locator('#youtubePanel summary').click()
assert page.locator('#youtubeUseTopic').is_checked()
assert page.locator('#youtubeTitle').input_value() == 'Нова тема'
page.locator('#videoTitleInput').fill('Another\ntopic')
assert page.evaluate('youtubeSettings().title') == 'Another topic'
page.locator('#youtubeUseTopic').uncheck()
assert page.locator('#youtubeTitle').input_value() == 'Custom title'
page.locator('#youtubeUseTopic').check()
page.locator('#videoTitleInput').fill('A' * 110)
assert page.evaluate('youtubeSettings().title') == 'A' * 100


def test_youtube_sign_in_status_is_visible_when_panel_is_closed(studio):
page, _ = studio
assert not page.locator('#youtubePanel').evaluate('el => el.open')
page.route('**/api/youtube/status', lambda route: route.fulfill(json={
'connected': False, 'csrf_token': 'test-token', 'redirect_uri': 'https://automap.test/api/youtube/callback'}))
page.evaluate('loadYouTubeConnection()')
assert page.locator('#youtubeConnectionBadge').is_visible()
assert page.locator('#youtubeConnectionBadge').inner_text() == 'Not signed in to YouTube'
page.route('**/api/youtube/status', lambda route: route.fulfill(json={
'connected': True, 'csrf_token': 'test-token', 'redirect_uri': 'https://automap.test/api/youtube/callback'}))
page.evaluate('loadYouTubeConnection()')
assert page.locator('#youtubeConnectionBadge').inner_text() == 'Signed in to YouTube'
page.route('**/api/youtube/disconnect', lambda route: route.fulfill(json={'connected': False}))
page.route('**/api/youtube/status', lambda route: route.fulfill(json={
'connected': False, 'csrf_token': 'test-token', 'redirect_uri': 'https://automap.test/api/youtube/callback'}))
page.locator('#youtubePanel summary').click()
page.locator('#youtubeAuto').check()
page.locator('#youtubeSignOut').click()
page.wait_for_function("document.getElementById('youtubeConnectionBadge').textContent === 'Not signed in to YouTube'")
assert page.locator('#youtubeSignOut').is_disabled()
assert not page.locator('#youtubeAuto').is_checked()
assert page.evaluate("JSON.parse(localStorage.getItem('automap-youtube-settings')).youtubeAuto") is False
1 change: 1 addition & 0 deletions tests/test_youtube_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ def test_oauth_connect_pkce_callback_and_replay(web, tmp_path, monkeypatch):
assert response.status_code == 200
query = parse_qs(urlsplit(response.json['authorization_url']).query)
assert query['scope'] == ['https://www.googleapis.com/auth/youtube.upload']
assert set(query['prompt'][0].split()) == {'consent', 'select_account'}
assert query['access_type'] == ['offline'] and query['code_challenge_method'] == ['S256']
with client.session_transaction() as cookie:
assert 'test-secret' not in str(dict(cookie))
Expand Down
2 changes: 1 addition & 1 deletion youtube_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ def youtube_connect():
if urlsplit(callback).scheme != 'https' and urlsplit(callback).hostname not in ('localhost', '127.0.0.1', '::1'):
raise ValueError('Hosted Google authorization requires HTTPS.')
flow = Flow.from_client_config(config, scopes=[SCOPE], redirect_uri=callback, autogenerate_code_verifier=True)
auth_url, state = flow.authorization_url(access_type='offline', prompt='consent')
auth_url, state = flow.authorization_url(access_type='offline', prompt='consent select_account')
owner = self.owner()
pending = {'config': config, 'state': state, 'verifier': flow.code_verifier, 'redirect': callback, 'created': time.time()}
self.save_secret(self.token_path(owner).with_suffix('.pending'), pending)
Expand Down
Loading