const PUBLISHER = Object.freeze({ handler: 'publishScheduled', uploadMinutes: 45, verificationMinutes: 90, attemptLimit: 3, maxBytes: 50000000, }); function preflightPublisher() { ScriptApp.requireAllScopes(ScriptApp.AuthMode.FULL); return preflightConfig_(PropertiesService.getScriptProperties()); } function preflightConfig_(properties) { const config = publisherConfig_(properties); const identity = publisherIdentity_(config); console.log(JSON.stringify({ mailboxVerified: true, channelVerified: true, channelAudience: identity.madeForKids, timeZone: config.timeZone, startTime: config.startTime, visibility: config.visibility, })); return config; } function enablePublisher() { ScriptApp.requireAllScopes(ScriptApp.AuthMode.FULL); const result = withPublisherLock_(() => { const properties = PropertiesService.getScriptProperties(); const config = preflightConfig_(properties); const snapshot = JSON.stringify(config); const activeConfig = properties.getProperty('publisher:active-config'); if (activeConfig && snapshot !== activeConfig) throw new PublisherError('disable_before_changing_settings'); const triggers = publisherTriggers_(); if (!triggers.length) ScriptApp.newTrigger(PUBLISHER.handler).timeBased().everyMinutes(5).create(); triggers.slice(1).forEach(trigger => ScriptApp.deleteTrigger(trigger)); properties.setProperties({ 'publisher:active-config': snapshot, 'publisher:identity': JSON.stringify([config.mailbox, config.channelId]), 'publisher:first-enabled-ms': properties.getProperty('publisher:first-enabled-ms') || String(Date.now()), }); return publisherStatus(); }); if (result && typeof reportPreviewStatus_ === 'function') reportPreviewStatus_(); return result; } function disablePublisher() { const result = withPublisherLock_(() => { PropertiesService.getScriptProperties().deleteProperty('publisher:active-config'); publisherTriggers_().forEach(trigger => ScriptApp.deleteTrigger(trigger)); return publisherStatus(); }); if (result && typeof reportPreviewStatus_ === 'function') reportPreviewStatus_(); return result; } function publisherStatus() { const properties = PropertiesService.getScriptProperties(); const activeConfig = properties.getProperty('publisher:active-config'); let config, configurationIssue; try { config = publisherConfig_(properties); } catch (error) { if (!(error instanceof PublisherError)) throw error; configurationIssue = error.code; } const result = { enabled: Boolean(activeConfig), matchingSettings: Boolean(activeConfig && config && JSON.stringify(config) === activeConfig), configurationIssue, triggerCount: publisherTriggers_().length, timeZone: config?.timeZone, startTime: config?.startTime, visibility: config?.visibility, last: JSON.parse(properties.getProperty('publisher:last') || 'null'), }; console.log(JSON.stringify(result)); return result; } function publishScheduled() { const properties = PropertiesService.getScriptProperties(); const activeConfig = properties.getProperty('publisher:active-config'); if (!activeConfig) return; const clock = scheduledClock_(new Date(), JSON.parse(activeConfig)); if (clock.elapsedMinutes < 0 || clock.elapsedMinutes >= PUBLISHER.verificationMinutes) return; const uploadWindow = clock.elapsedMinutes < PUBLISHER.uploadMinutes; let previousStatus; const result = withPublisherLock_(() => { if (activeConfig !== properties.getProperty('publisher:active-config')) return; if (typeof syncPreviewStatusAfterChange_ === 'function') previousStatus = properties.getProperty('publisher:last'); try { const config = publisherConfig_(properties); if (JSON.stringify(config) !== activeConfig) throw new PublisherError('settings_changed_since_activation'); const messageId = properties.getProperty('publisher:day:' + clock.day); if (messageId) { const job = loadJob_(properties, messageId); if (job.phase === 'complete' || job.phase === 'needs_attention') return; if (!uploadWindow && job.phase !== 'uploaded') return; advanceJob_(properties, job, config, publisherIdentity_(config).madeForKids); return; } if (!uploadWindow) return; const identity = publisherIdentity_(config); const submission = findSubmission_(properties, clock.day, config); if (!submission) { if (lastRunDay_(properties) !== clock.day) recordStatus_(properties, 'waiting_for_mail', clock.day); return; } const job = { ...submission, day: clock.day, visibility: config.visibility, categoryId: config.categoryId, phase: 'queued', attempts: 0 }; saveJob_(properties, job); recordStatus_(properties, 'queued', clock.day, { messageId: job.messageId }); advanceJob_(properties, job, config, identity.madeForKids); } catch (error) { const reason = error instanceof PublisherError ? error.code : 'google_service_error'; recordStatus_(properties, 'blocked', clock.day, { reason }); } }); if (previousStatus !== undefined) syncPreviewStatusAfterChange_(properties, previousStatus); return result; } function verifyPublisherVideo() { return withPublisherLock_(() => { const properties = PropertiesService.getScriptProperties(); const job = Object.entries(properties.getProperties()) .filter(([key]) => key.startsWith('publisher:message:')) .map(([, value]) => JSON.parse(value)) .filter(item => item.phase === 'uploaded') .sort((left, right) => right.day.localeCompare(left.day))[0]; if (!job) return publisherStatus(); const config = publisherConfig_(properties); publisherIdentity_(config); verifyVideo_(properties, job, config); return publisherStatus(); }); } class PublisherError extends Error { constructor(code, retryable = false) { super(code); this.code = code; this.retryable = retryable; } } function publisherConfig_(properties) { const setting = name => (properties.getProperty(name) || '').trim(); const mailbox = setting('VS_MAILBOX').toLowerCase(); const channelId = setting('VS_CHANNEL_ID'); const timeZone = setting('VS_TIME_ZONE'); const startTime = setting('VS_START_TIME'); const visibility = setting('VS_VISIBILITY'); const categoryId = setting('VS_CATEGORY_ID') || '22'; if (!/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/.test(mailbox)) throw new PublisherError('invalid_VS_MAILBOX'); if (!/^UC[A-Za-z0-9_-]{22}$/.test(channelId)) throw new PublisherError('invalid_VS_CHANNEL_ID'); try { if (!timeZone) throw new Error('Missing time zone'); new Intl.DateTimeFormat('en', { timeZone }); } catch (_) { throw new PublisherError('invalid_VS_TIME_ZONE'); } if (!/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(startTime)) throw new PublisherError('invalid_VS_START_TIME'); if (!['private', 'unlisted', 'public'].includes(visibility)) throw new PublisherError('invalid_VS_VISIBILITY'); if (!/^[1-9]\d*$/.test(categoryId)) throw new PublisherError('invalid_VS_CATEGORY_ID'); const originalIdentity = properties.getProperty('publisher:identity'); if (originalIdentity && originalIdentity !== JSON.stringify([mailbox, channelId])) { throw new PublisherError('project_bound_to_different_identity'); } return Object.freeze({ mailbox, channelId, timeZone, startTime, visibility, categoryId }); } function publisherIdentity_(config) { const mailbox = (Gmail.Users.getProfile('me').emailAddress || '').toLowerCase(); if (mailbox !== config.mailbox) throw new PublisherError('wrong_mailbox'); const channels = YouTube.Channels.list('id,status', { mine: true }).items || []; if (channels.length !== 1 || channels[0].id !== config.channelId) { throw new PublisherError('wrong_youtube_channel'); } const audience = channels[0].status?.selfDeclaredMadeForKids; return { madeForKids: typeof audience === 'boolean' ? audience : null }; } function publisherTriggers_() { return ScriptApp.getProjectTriggers().filter(trigger => trigger.getHandlerFunction() === PUBLISHER.handler); } function withPublisherLock_(work) { const lock = LockService.getScriptLock(); if (!lock.tryLock(1000)) return; try { return work(); } finally { lock.releaseLock(); } } function offsetDay_(day, offset) { const utcMidnight = Date.parse(day + 'T00:00:00Z'); return new Date(utcMidnight + offset * 86400000).toISOString().slice(0, 10); } function scheduledClock_(now, config) { let day = Utilities.formatDate(now, config.timeZone, 'yyyy-MM-dd'); let scheduled = Utilities.parseDate(day + ' ' + config.startTime, config.timeZone, 'yyyy-MM-dd HH:mm'); if (now < scheduled) { day = offsetDay_(day, -1); scheduled = Utilities.parseDate(day + ' ' + config.startTime, config.timeZone, 'yyyy-MM-dd HH:mm'); } return { day, elapsedMinutes: (now - scheduled) / 60000 }; } function lastRunDay_(properties) { return JSON.parse(properties.getProperty('publisher:last') || 'null')?.day; } function recordStatus_(properties, phase, day, detail = {}) { const status = { day, phase, updatedAt: new Date().toISOString(), ...detail }; properties.setProperty('publisher:last', JSON.stringify(status)); console.log(JSON.stringify(status)); } function messageKey_(id) { return `publisher:message:${id}`; } function fileKey_(id) { return `publisher:file:${id}`; } function loadJob_(properties, id) { const job = JSON.parse(properties.getProperty(messageKey_(id)) || 'null'); if (!job || !job.messageId) throw new PublisherError('missing_job_record'); return job; } function saveJob_(properties, job) { properties.setProperties({ [messageKey_(job.messageId)]: JSON.stringify(job), [fileKey_(job.driveId)]: job.messageId, [`publisher:day:${job.day}`]: job.messageId, }); } function findSubmission_(properties, day, config) { const dayStart = Utilities.parseDate(day + ' 00:00', config.timeZone, 'yyyy-MM-dd HH:mm').getTime(); const dayEnd = Utilities.parseDate(offsetDay_(day, 1) + ' 00:00', config.timeZone, 'yyyy-MM-dd HH:mm').getTime(); const firstEnable = Number(properties.getProperty('publisher:first-enabled-ms')); if (!Number.isSafeInteger(firstEnable) || firstEnable <= 0) throw new PublisherError('missing_initial_activation_time'); const eligibleFrom = Math.max(dayStart, firstEnable); if (eligibleFrom >= dayEnd) return null; const list = Gmail.Users.Messages.list('me', { labelIds: ['SENT'], q: `to:${config.mailbox} subject:"YT-SHORT" after:${Math.floor(eligibleFrom / 1000) - 1} before:${dayEnd / 1000}`, maxResults: 50, }); if (list.nextPageToken) { recordStatus_(properties, 'ambiguous_mail', day, { reason: 'too_many_matching_messages' }); return null; } const messages = (list.messages || []) .filter(({ id }) => !properties.getProperty(messageKey_(id))) .map(({ id }) => getPublisherMessage_(id)) .filter(message => Number(message.internalDate) >= eligibleFrom && Number(message.internalDate) < dayEnd) .sort((left, right) => Number(right.internalDate) - Number(left.internalDate)); const candidates = new Map(); let invalidReason; for (const message of messages) { if (!hasPublisherEnvelope_(message, config.mailbox)) continue; let fields; try { fields = parseSubmission_(message.payload); } catch (error) { if (!(error instanceof PublisherError)) throw error; if (!invalidReason) invalidReason = error.code; continue; } if (properties.getProperty(fileKey_(fields.driveId))) continue; if (!candidates.has(fields.driveId)) candidates.set(fields.driveId, { messageId: message.id, driveId: fields.driveId }); } if (candidates.size > 1) { recordStatus_(properties, 'ambiguous_mail', day, { reason: 'multiple_distinct_drive_videos', count: candidates.size }); return null; } if (candidates.size === 1) return candidates.values().next().value; if (invalidReason) recordStatus_(properties, 'invalid_mail', day, { reason: invalidReason }); return null; } function getPublisherMessage_(id) { const url = `https://gmail.googleapis.com/gmail/v1/users/me/messages/${encodeURIComponent(id)}?format=full`; const response = fetchGoogle_(url, { method: 'get' }, ScriptApp.getOAuthToken()); if (response.getResponseCode() !== 200) throw responseError_(response, 'gmail_message'); return JSON.parse(response.getContentText()); } function hasPublisherEnvelope_(message, mailbox) { const headers = Object.fromEntries((message.payload?.headers || []).map(header => [header.name.toLowerCase(), header.value])); const exactAddress = value => (value || '').trim().replace(/^.*<([^<>]+)>$/, '$1').toLowerCase(); return message.labelIds?.includes('SENT') && /^\[YT-SHORT\]/.test(headers.subject || '') && exactAddress(headers.from) === mailbox && exactAddress(headers.to) === mailbox; } function parseSubmission_(payload) { const body = textBody_(payload); const labels = [...body.matchAll(/^[ \t]*(YOUTUBE_TITLE|YOUTUBE_DESCRIPTION|YOUTUBE_MADE_FOR_KIDS|YOUTUBE_HASHTAGS|VIDEO_URL|DRIVE_URL|SOURCE_FILM|DURATION|ATTACHMENT)[ \t]*:[ \t]*/gmi)]; const fields = {}; for (let index = 0; index < labels.length; index++) { const label = labels[index]; const key = label[1].toUpperCase(); if (Object.prototype.hasOwnProperty.call(fields, key)) throw new PublisherError('duplicate_email_field'); fields[key] = body.slice(label.index + label[0].length, labels[index + 1]?.index).trim(); } const title = fields.YOUTUBE_TITLE; const description = fields.YOUTUBE_DESCRIPTION; if (!title || /[\r\n<>]/.test(title) || Array.from(title).length > 100) { throw new PublisherError('invalid_youtube_title'); } if (!description || /[<>]/.test(description) || Utilities.newBlob(description).getBytes().length > 5000) { throw new PublisherError('invalid_youtube_description'); } const links = [fields.VIDEO_URL, fields.DRIVE_URL].filter(Boolean); const ids = links.map(driveIdFromUrl_); if (!ids.length || ids.some(id => !id) || new Set(ids).size !== 1) { throw new PublisherError('expected_one_drive_video_url'); } const audience = fields.YOUTUBE_MADE_FOR_KIDS; if (audience !== undefined && !/^(true|false)$/i.test(audience)) { throw new PublisherError('invalid_youtube_made_for_kids'); } return { title, description, driveId: ids[0], madeForKids: audience === undefined ? null : /^true$/i.test(audience) }; } function textBody_(payload) { const textParts = []; function visit(part) { if (!part.filename && ['text/plain', 'text/html'].includes(part.mimeType) && part.body?.data) { textParts.push(part); } (part.parts || []).forEach(visit); } visit(payload); const part = textParts.find(item => item.mimeType === 'text/plain') || textParts[0]; if (!part) throw new PublisherError('missing_text_email_body'); const data = part.body.data; const bytes = Utilities.base64DecodeWebSafe(data.padEnd(Math.ceil(data.length / 4) * 4, '=')); const body = Utilities.newBlob(bytes).getDataAsString('UTF-8'); if (part.mimeType === 'text/plain') return body.replace(/\r\n?/g, '\n'); return body.replace(/<\s*(?:br\b[^>]*|\/(?:p|div|li|tr))\s*\/?>/gi, '\n') .replace(/<[^>]*>/g, '') .replace(/&(nbsp|amp|quot|apos|lt|gt|#39);/g, (_, entity) => ({ nbsp: ' ', amp: '&', quot: '"', apos: "'", lt: '<', gt: '>', '#39': "'", })[entity]); } function driveIdFromUrl_(value) { const link = value.trim().replace(/^[<](.*)[>]$/s, '$1'); const pathMatch = /^https:\/\/drive\.google\.com\/file\/d\/([A-Za-z0-9_-]{10,})(?:\/[\w-]+)?(?:\?[^\s#]*)?(?:#[^\s]*)?$/i.exec(link); if (pathMatch) return pathMatch[1]; const query = /^https:\/\/drive\.google\.com\/(?:open|uc)\?([^\s#]+)(?:#[^\s]*)?$/i.exec(link); return query ? /(?:^|&)id=([A-Za-z0-9_-]{10,})(?:&|$)/.exec(query[1])?.[1] : null; } function driveVideo_(id) { const file = Drive.Files.get(id, { fields: 'id,name,mimeType,size,version,capabilities(canDownload)' }); const size = Number(file.size); if (file.id !== id || !file.capabilities?.canDownload || !Number.isSafeInteger(size) || size <= 0 || size > PUBLISHER.maxBytes || !(file.mimeType === 'video/mp4' || (file.mimeType === 'application/octet-stream' && /\.mp4$/i.test(file.name)))) { throw new PublisherError('invalid_or_unavailable_drive_mp4'); } return { size, version: String(file.version) }; } function advanceJob_(properties, job, config, defaultAudience) { if (job.phase === 'complete' || job.phase === 'needs_attention') return; if (job.phase === 'uploaded') { verifyVideo_(properties, job, config); return; } if (job.visibility !== config.visibility || job.categoryId !== config.categoryId) { markAttention_(properties, job, 'upload_settings_changed'); return; } if (job.attempts >= PUBLISHER.attemptLimit) { markAttention_(properties, job, job.reason || 'retry_limit_reached'); return; } job.attempts++; saveJob_(properties, job); try { const token = ScriptApp.getOAuthToken(); let offset = 0; if (job.session) { const previous = uploadProgress_(job, token); if (previous.videoId) return acceptUpload_(properties, job, previous.videoId, config); offset = previous.offset; } const file = driveVideo_(job.driveId); if (job.session && (file.size !== job.size || file.version !== job.version)) { throw new PublisherError('drive_file_changed_during_upload'); } const blob = downloadMedia_(job.driveId, file.size, offset, token); if (driveVideo_(job.driveId).version !== file.version) throw new PublisherError('drive_file_changed_during_download'); if (!job.session) { const message = getPublisherMessage_(job.messageId); if (!hasPublisherEnvelope_(message, config.mailbox)) throw new PublisherError('mail_envelope_changed'); const submission = parseSubmission_(message.payload); if (submission.driveId !== job.driveId) throw new PublisherError('mail_video_changed'); job.size = file.size; job.version = file.version; job.session = startUpload_(submission, file.size, token, job, defaultAudience); job.phase = 'transferring'; saveJob_(properties, job); } const progress = transferMedia_(job, blob, offset, token); if (!progress.videoId) throw new PublisherError('upload_incomplete', true); acceptUpload_(properties, job, progress.videoId, config); } catch (error) { const reason = error instanceof PublisherError ? error.code : 'google_service_error'; if (job.phase === 'uploaded' || job.phase === 'complete') { recordStatus_(properties, job.phase, job.day, { messageId: job.messageId, videoId: job.videoId, reason }); } else if ((!(error instanceof PublisherError) || error.retryable) && job.attempts < PUBLISHER.attemptLimit) { job.reason = reason; saveJob_(properties, job); recordStatus_(properties, 'retry_pending', job.day, { messageId: job.messageId, reason, attempts: job.attempts }); } else { markAttention_(properties, job, reason); } } } function fetchGoogle_(url, options, token) { try { return UrlFetchApp.fetch(url, { ...options, followRedirects: false, muteHttpExceptions: true, headers: { ...options.headers, Authorization: `Bearer ${token}` } }); } catch (_) { throw new PublisherError('network_error', true); } } function header_(response, key) { const entry = Object.entries(response.getAllHeaders()).find(([name]) => name.toLowerCase() === key.toLowerCase()); return entry ? String(entry[1]) : ''; } function responseError_(response, prefix) { const status = response.getResponseCode(); let reason = ''; try { const value = JSON.parse(response.getContentText())?.error?.errors?.[0]?.reason || ''; if (/^[A-Za-z0-9_]{1,64}$/.test(value)) reason = `_${value}`; } catch (_) { // Google can return an unexpected or empty error body. } return new PublisherError(`${prefix}_${status}${reason}`, status === 429 || status >= 500); } function downloadMedia_(id, size, offset, token) { if (offset < 0 || offset >= size) throw new PublisherError('invalid_resume_position', true); const headers = offset ? { Range: `bytes=${offset}-${size - 1}` } : {}; const response = fetchGoogle_(`https://www.googleapis.com/drive/v3/files/${encodeURIComponent(id)}?alt=media`, { method: 'get', headers }, token); if (response.getResponseCode() !== (offset ? 206 : 200)) throw responseError_(response, 'drive_download'); if (offset && header_(response, 'Content-Range') !== `bytes ${offset}-${size - 1}/${size}`) { throw new PublisherError('unexpected_drive_byte_range'); } const blob = response.getBlob().setContentType('video/mp4'); const length = header_(response, 'Content-Length'); if ((length ? Number(length) : blob.getBytes().length) !== size - offset) { throw new PublisherError('unexpected_drive_byte_count'); } return blob; } function startUpload_(submission, size, token, job, defaultAudience) { const resource = { snippet: { title: submission.title, description: submission.description, categoryId: job.categoryId }, status: { privacyStatus: job.visibility }, }; const audience = submission.madeForKids ?? defaultAudience; if (typeof audience === 'boolean') resource.status.selfDeclaredMadeForKids = audience; const response = fetchGoogle_('https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet%2Cstatus', { method: 'post', contentType: 'application/json; charset=UTF-8', payload: JSON.stringify(resource), headers: { 'X-Upload-Content-Length': String(size), 'X-Upload-Content-Type': 'video/mp4' }, }, token); if (response.getResponseCode() !== 200) throw responseError_(response, 'youtube_session'); const session = header_(response, 'Location'); if (!/^https:\/\/(?:[a-z0-9-]+\.)*googleapis\.com\/upload\/youtube\/v3\/videos\?[^\s]+$/i.test(session)) { throw new PublisherError('invalid_youtube_session_location'); } return session; } function uploadProgress_(job, token) { const response = fetchGoogle_(job.session, { method: 'put', payload: '', headers: { 'Content-Range': `bytes */${job.size}` }, }, token); return interpretUpload_(response, job.size); } function transferMedia_(job, blob, offset, token) { const headers = { 'Content-Range': `bytes ${offset}-${job.size - 1}/${job.size}` }; const response = fetchGoogle_(job.session, { method: 'put', contentType: 'video/mp4', payload: blob, headers }, token); return interpretUpload_(response, job.size); } function interpretUpload_(response, size) { const status = response.getResponseCode(); if (status === 404 || status === 410) throw new PublisherError('upload_session_expired_check_studio'); if (status === 308) { const range = header_(response, 'Range'); const match = /^bytes=0-(\d+)$/i.exec(range); if (range && !match) throw new PublisherError('unexpected_youtube_byte_range', true); const offset = match ? Number(match[1]) + 1 : 0; if (offset > size) throw new PublisherError('unexpected_youtube_byte_range', true); return { offset }; } if (status === 200 || status === 201) { try { const id = JSON.parse(response.getContentText()).id || ''; if (/^[A-Za-z0-9_-]{11}$/.test(id)) return { videoId: id }; } catch (_) { // Query the saved session again if the success response was incomplete. } throw new PublisherError('upload_outcome_unknown', true); } throw responseError_(response, 'youtube_upload'); } function acceptUpload_(properties, job, videoId, config) { job.videoId = videoId; job.phase = 'uploaded'; delete job.session; delete job.reason; saveJob_(properties, job); recordStatus_(properties, job.phase, job.day, { messageId: job.messageId, videoId }); verifyVideo_(properties, job, config); } function verifyVideo_(properties, job, config) { const videos = YouTube.Videos.list('snippet,status,processingDetails', { id: job.videoId }).items || []; if (videos.length !== 1 || videos[0].id !== job.videoId) return; const video = videos[0]; if (video.snippet?.channelId !== config.channelId || video.status?.privacyStatus !== job.visibility) { markAttention_(properties, job, 'youtube_channel_or_visibility_mismatch'); return; } if (['deleted', 'failed', 'rejected'].includes(video.status.uploadStatus) || ['failed', 'terminated'].includes(video.processingDetails?.processingStatus)) { markAttention_(properties, job, 'youtube_processing_failed'); return; } if (video.status.uploadStatus === 'processed' || video.processingDetails?.processingStatus === 'succeeded') { properties.setProperty(messageKey_(job.messageId), JSON.stringify({ phase: 'complete', messageId: job.messageId, driveId: job.driveId, day: job.day, videoId: job.videoId, visibility: job.visibility })); recordStatus_(properties, 'complete', job.day, { messageId: job.messageId, videoId: job.videoId, visibility: job.visibility, url: 'https://www.youtube.com/watch?v=' + job.videoId }); } } function markAttention_(properties, job, reason) { job.phase = 'needs_attention'; job.reason = reason; saveJob_(properties, job); recordStatus_(properties, job.phase, job.day, { messageId: job.messageId, videoId: job.videoId, reason }); }