File: window-dock-youtube-app.cpp

package info (click to toggle)
obs-studio 30.2.3%2Bdfsg-3.2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 47,928 kB
  • sloc: ansic: 202,137; cpp: 112,403; makefile: 868; python: 599; sh: 275; javascript: 19
file content (478 lines) | stat: -rw-r--r-- 12,194 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
#include <QUuid>

#include "window-basic-main.hpp"
#include "youtube-api-wrappers.hpp"
#include "window-dock-youtube-app.hpp"

#include "ui-config.h"
#include "qt-wrappers.hpp"

#include <nlohmann/json.hpp>
using json = nlohmann::json;

#ifdef YOUTUBE_WEBAPP_PLACEHOLDER
static constexpr const char *YOUTUBE_WEBAPP_PLACEHOLDER_URL =
	YOUTUBE_WEBAPP_PLACEHOLDER;
#else
static constexpr const char *YOUTUBE_WEBAPP_PLACEHOLDER_URL =
	"https://studio.youtube.com/live/channel/UC/console?kc=OBS";
#endif

#ifdef YOUTUBE_WEBAPP_ADDRESS
static constexpr const char *YOUTUBE_WEBAPP_ADDRESS_URL =
	YOUTUBE_WEBAPP_ADDRESS;
#else
static constexpr const char *YOUTUBE_WEBAPP_ADDRESS_URL =
	"https://studio.youtube.com/live/channel/%1/console?kc=OBS";
#endif

static constexpr const char *BROADCAST_CREATED = "BROADCAST_CREATED";
static constexpr const char *BROADCAST_SELECTED = "BROADCAST_SELECTED";
static constexpr const char *INGESTION_STARTED = "INGESTION_STARTED";
static constexpr const char *INGESTION_STOPPED = "INGESTION_STOPPED";

YouTubeAppDock::YouTubeAppDock(const QString &title)
	: BrowserDock(title),
	  dockBrowser(nullptr),
	  cookieManager(nullptr)
{
	cef->init_browser();
	OBSBasic::InitBrowserPanelSafeBlock();
	AddYouTubeAppDock();
}

YouTubeAppDock::~YouTubeAppDock()
{
	if (cookieManager) {
		cookieManager->FlushStore();
		delete cookieManager;
	}
}

bool YouTubeAppDock::IsYTServiceSelected()
{
	if (!cef_js_avail)
		return false;

	obs_service_t *service_obj = OBSBasic::Get()->GetService();
	OBSDataAutoRelease settings = obs_service_get_settings(service_obj);
	const char *service = obs_data_get_string(settings, "service");
	return IsYouTubeService(service);
}

void YouTubeAppDock::AccountConnected()
{
	channelId.clear(); // renew channel id
	UpdateChannelId();
}

void YouTubeAppDock::AccountDisconnected()
{
	SettingsUpdated(true);
}

void YouTubeAppDock::SettingsUpdated(bool cleanup)
{
	bool ytservice = IsYTServiceSelected();
	SetVisibleYTAppDockInMenu(ytservice);

	// definitely cleanup if YT switched off
	if (!ytservice || cleanup) {
		if (cookieManager)
			cookieManager->DeleteCookies("", "");
	}
	if (ytservice)
		Update();
}

std::string YouTubeAppDock::InitYTUserUrl()
{
	std::string user_url(YOUTUBE_WEBAPP_PLACEHOLDER_URL);

	if (IsUserSignedIntoYT()) {
		YoutubeApiWrappers *apiYouTube = GetYTApi();
		if (apiYouTube) {
			ChannelDescription channel_description;
			if (apiYouTube->GetChannelDescription(
				    channel_description)) {
				QString url =
					QString(YOUTUBE_WEBAPP_ADDRESS_URL)
						.arg(channel_description.id);
				user_url = url.toStdString();
			} else {
				blog(LOG_ERROR,
				     "YT: InitYTUserUrl() Failed to get channel id");
			}
		}
	} else {
		blog(LOG_ERROR, "YT: InitYTUserUrl() User is not signed");
	}

	blog(LOG_DEBUG, "YT: InitYTUserUrl() User url: %s", user_url.c_str());
	return user_url;
}

void YouTubeAppDock::AddYouTubeAppDock()
{
	QString bId(QUuid::createUuid().toString());
	bId.replace(QRegularExpression("[{}-]"), "");
	this->setProperty("uuid", bId);
	this->setObjectName("youtubeLiveControlPanel");
	this->resize(580, 500);
	this->setMinimumSize(400, 300);
	this->setAllowedAreas(Qt::AllDockWidgetAreas);

	OBSBasic::Get()->AddDockWidget(this, Qt::RightDockWidgetArea);

	if (IsYTServiceSelected()) {
		const std::string url = InitYTUserUrl();
		CreateBrowserWidget(url);
	} else {
		this->setVisible(false);
		this->toggleViewAction()->setVisible(false);
	}
}

void YouTubeAppDock::CreateBrowserWidget(const std::string &url)
{
	std::string dir_name = std::string("obs_profile_cookies_youtube/") +
			       config_get_string(OBSBasic::Get()->Config(),
						 "Panels", "CookieId");
	if (cookieManager)
		delete cookieManager;
	cookieManager = cef->create_cookie_manager(dir_name, true);

	if (dockBrowser)
		delete dockBrowser;
	dockBrowser = cef->create_widget(this, url, cookieManager);
	if (!dockBrowser)
		return;

	if (obs_browser_qcef_version() >= 1)
		dockBrowser->allowAllPopups(true);

	this->SetWidget(dockBrowser);
	Update();
}

void YouTubeAppDock::SetVisibleYTAppDockInMenu(bool visible)
{
	if (visible && toggleViewAction()->isVisible())
		return;

	toggleViewAction()->setVisible(visible);
	this->setVisible(visible);
}

// only 'ACCOUNT' mode supported
void YouTubeAppDock::BroadcastCreated(const char *stream_id)
{
	DispatchYTEvent(BROADCAST_CREATED, stream_id, YTSM_ACCOUNT);
}

// only 'ACCOUNT' mode supported
void YouTubeAppDock::BroadcastSelected(const char *stream_id)
{
	DispatchYTEvent(BROADCAST_SELECTED, stream_id, YTSM_ACCOUNT);
}

// both 'ACCOUNT' and 'STREAM_KEY' modes supported
void YouTubeAppDock::IngestionStarted()
{
	obs_service_t *service_obj = OBSBasic::Get()->GetService();
	OBSDataAutoRelease settings = obs_service_get_settings(service_obj);
	const char *service = obs_data_get_string(settings, "service");
	if (IsYouTubeService(service)) {
		if (IsUserSignedIntoYT()) {
			const char *broadcast_id =
				obs_data_get_string(settings, "broadcast_id");
			this->IngestionStarted(broadcast_id,
					       YouTubeAppDock::YTSM_ACCOUNT);
		} else {
			const char *stream_key =
				obs_data_get_string(settings, "key");
			this->IngestionStarted(stream_key,
					       YouTubeAppDock::YTSM_STREAM_KEY);
		}
	}
}

void YouTubeAppDock::IngestionStarted(const char *stream_id,
				      streaming_mode_t mode)
{
	DispatchYTEvent(INGESTION_STARTED, stream_id, mode);
}

// both 'ACCOUNT' and 'STREAM_KEY' modes supported
void YouTubeAppDock::IngestionStopped()
{
	obs_service_t *service_obj = OBSBasic::Get()->GetService();
	OBSDataAutoRelease settings = obs_service_get_settings(service_obj);
	const char *service = obs_data_get_string(settings, "service");

	if (IsYouTubeService(service)) {
		if (IsUserSignedIntoYT()) {
			const char *broadcast_id =
				obs_data_get_string(settings, "broadcast_id");
			this->IngestionStopped(broadcast_id,
					       YouTubeAppDock::YTSM_ACCOUNT);
		} else {
			const char *stream_key =
				obs_data_get_string(settings, "key");
			this->IngestionStopped(stream_key,
					       YouTubeAppDock::YTSM_STREAM_KEY);
		}
	}
}

void YouTubeAppDock::IngestionStopped(const char *stream_id,
				      streaming_mode_t mode)
{
	DispatchYTEvent(INGESTION_STOPPED, stream_id, mode);
}

void YouTubeAppDock::showEvent(QShowEvent *)
{
	if (!dockBrowser)
		Update();
}

void YouTubeAppDock::closeEvent(QCloseEvent *event)
{
	BrowserDock::closeEvent(event);
	this->SetWidget(nullptr);
}

void YouTubeAppDock::DispatchYTEvent(const char *event, const char *video_id,
				     streaming_mode_t mode)
{
	if (!dockBrowser)
		return;

	// update channelId if empty:
	UpdateChannelId();

	// notify YouTube Live Streaming API:
	std::string script;
	if (mode == YTSM_ACCOUNT) {
		script = QString(R"""(
			if (window.location.hostname == 'studio.youtube.com') {
				let event = {
					type: '%1',
					channelId: '%2',
					videoId: '%3',
				};
				console.log(event);
				if (window.ytlsapi && window.ytlsapi.dispatchEvent)
					window.ytlsapi.dispatchEvent(event);
			}
		)""")
				 .arg(event)
				 .arg(channelId)
				 .arg(video_id)
				 .toStdString();
	} else {
		const char *stream_key = video_id;
		script = QString(R"""(
			if (window.location.hostname == 'studio.youtube.com') {
				let event = {
					type: '%1',
					streamKey: '%2',
				};
				console.log(event);
				if (window.ytlsapi && window.ytlsapi.dispatchEvent)
					window.ytlsapi.dispatchEvent(event);
			}
		)""")
				 .arg(event)
				 .arg(stream_key)
				 .toStdString();
	}
	dockBrowser->executeJavaScript(script);

	// in case of user still not logged in in dock panel, remember last event
	SetInitEvent(mode, event, video_id, channelId.toStdString().c_str());
}

void YouTubeAppDock::Update()
{
	std::string url = InitYTUserUrl();

	if (!dockBrowser) {
		CreateBrowserWidget(url);
	} else {
		dockBrowser->setURL(url);
	}

	// if streaming already run, let's notify YT about past event
	if (OBSBasic::Get()->StreamingActive()) {
		obs_service_t *service_obj = OBSBasic::Get()->GetService();
		OBSDataAutoRelease settings =
			obs_service_get_settings(service_obj);
		if (IsUserSignedIntoYT()) {
			channelId.clear(); // renew channelId
			UpdateChannelId();
			const char *broadcast_id =
				obs_data_get_string(settings, "broadcast_id");
			SetInitEvent(YTSM_ACCOUNT, INGESTION_STARTED,
				     broadcast_id,
				     channelId.toStdString().c_str());
		} else {
			const char *stream_key =
				obs_data_get_string(settings, "key");
			SetInitEvent(YTSM_STREAM_KEY, INGESTION_STARTED,
				     stream_key);
		}
	} else {
		SetInitEvent(IsUserSignedIntoYT() ? YTSM_ACCOUNT
						  : YTSM_STREAM_KEY);
	}

	dockBrowser->reloadPage();
}

void YouTubeAppDock::UpdateChannelId()
{
	if (channelId.isEmpty()) {
		YoutubeApiWrappers *apiYouTube = GetYTApi();
		if (apiYouTube) {
			ChannelDescription channel_description;
			if (apiYouTube->GetChannelDescription(
				    channel_description)) {
				channelId = channel_description.id;
			} else {
				blog(LOG_ERROR, "YT: AccountConnected() Failed "
						"to get channel id");
			}
		}
	}
}

void YouTubeAppDock::SetInitEvent(streaming_mode_t mode, const char *event,
				  const char *video_id, const char *channelId)
{
	const std::string version = App()->GetVersionString();

	QString api_event;
	if (event) {
		if (mode == YTSM_ACCOUNT) {
			api_event = QString(R"""(,
					initEvent: {
						type: '%1',
						channelId: '%2',
						videoId: '%3',
					}
			)""")
					    .arg(event)
					    .arg(channelId)
					    .arg(video_id);
		} else {
			api_event = QString(R"""(,
					initEvent: {
						type: '%1',
						streamKey: '%2',
					}
			)""")
					    .arg(event)
					    .arg(video_id);
		}
	}

	std::string script = QString(R"""(
		let obs_name = '%1';
		let obs_version = '%2';
		let client_mode = %3;
		if (window.location.hostname == 'studio.youtube.com') {
			console.log("name:", obs_name);
			console.log("version:", obs_version);
			console.log("initEvent:", {
					initClientMode: client_mode
					%4 });
			if (window.ytlsapi && window.ytlsapi.init)
				window.ytlsapi.init(obs_name, obs_version, undefined, {
					initClientMode: client_mode
					%4 });
		}
	)""")
				     .arg("OBS")
				     .arg(version.c_str())
				     .arg(mode == YTSM_ACCOUNT ? "'ACCOUNT'"
							       : "'STREAM_KEY'")
				     .arg(api_event)
				     .toStdString();
	dockBrowser->setStartupScript(script);
}

YoutubeApiWrappers *YouTubeAppDock::GetYTApi()
{
	Auth *auth = OBSBasic::Get()->GetAuth();
	if (auth) {
		YoutubeApiWrappers *apiYouTube(
			dynamic_cast<YoutubeApiWrappers *>(auth));
		if (apiYouTube) {
			return apiYouTube;
		} else {
			blog(LOG_ERROR,
			     "YT: GetYTApi() Failed to get YoutubeApiWrappers");
		}
	} else {
		blog(LOG_ERROR, "YT: GetYTApi() Failed to get Auth");
	}
	return nullptr;
}

void YouTubeAppDock::CleanupYouTubeUrls()
{
	if (!cef_js_avail)
		return;

	static constexpr const char *YOUTUBE_VIDEO_URL =
		"://studio.youtube.com/video/";
	// remove legacy YouTube Browser Docks (once)

	bool youtube_cleanup_done = config_get_bool(
		App()->GlobalConfig(), "General", "YtDockCleanupDone");

	if (youtube_cleanup_done)
		return;

	config_set_bool(App()->GlobalConfig(), "General", "YtDockCleanupDone",
			true);

	const char *jsonStr = config_get_string(
		App()->GlobalConfig(), "BasicWindow", "ExtraBrowserDocks");
	if (!jsonStr)
		return;

	json array = json::parse(jsonStr);
	if (!array.is_array())
		return;

	json save_array;
	std::string removedYTUrl;

	for (json &item : array) {
		auto url = item["url"].get<std::string>();

		if (url.find(YOUTUBE_VIDEO_URL) != std::string::npos) {
			blog(LOG_DEBUG, "YT: found legacy url: %s",
			     url.c_str());
			removedYTUrl += url;
			removedYTUrl += ";\n";
		} else {
			save_array.push_back(item);
		}
	}

	if (!removedYTUrl.empty()) {
		const QString msg_title = QTStr("YouTube.DocksRemoval.Title");
		const QString msg_text =
			QTStr("YouTube.DocksRemoval.Text")
				.arg(QT_UTF8(removedYTUrl.c_str()));
		OBSMessageBox::warning(OBSBasic::Get(), msg_title, msg_text);

		std::string output = save_array.dump();
		config_set_string(App()->GlobalConfig(), "BasicWindow",
				  "ExtraBrowserDocks", output.c_str());
	}
}