-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1048 lines (868 loc) · 31.6 KB
/
index.js
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name PlanningCenter YouTube Integration
// @namespace https://github.com/Auxority/planningcenter-yt-stream-creator
// @version 2024-11-23
// @description Allows you to create a YouTube stream from a PlanningCenter service plan.
// @author Auxority
// @match https://services.planningcenteronline.com/*
// @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @grant window.onurlchange
// ==/UserScript==
// You must give your browser access to show Popups/Redirects and Google Sign-In popups on the PlanningCenter page.
(() => {
"use strict";
/**
* Represents a key-value storage for settings.
*/
class SettingsStorage {
/**
* Loads a value from the settings storage.
* @param {string} key
* @returns {unknown}
*/
static load(key) {
// eslint-disable-next-line no-undef
const value = GM_getValue(key);
console.debug(`Loaded value for key ${key}: ${value}`);
return value;
}
/**
* Saves a value to the settings storage.
* @param {string} key
* @param {unknown} value
*/
static save(key, value) {
console.debug(`Saving value for key ${key}: ${value}`);
// eslint-disable-next-line no-undef
GM_setValue(key, value);
}
/**
* Deletes a value from the settings storage.
* @param {string} key
* @returns {unknown}
*/
static delete(key) {
console.debug(`Deleting value for key: ${key}`);
// eslint-disable-next-line no-undef
GM_deleteValue(key);
}
}
/**
* Represents the response received from the Google OAuth API.
*/
class AuthToken {
/**
* The access token received from the Google OAuth API.
* @type {string} The access token.
*/
accessToken;
/**
* The expiration time of the access token in seconds.
* @type {number} The expiration time in seconds.
*/
expiresIn;
/**
* The type of token received from the Google OAuth API.
* @type {string} The token type.
*/
tokenType;
static EXPECTED_TOKEN_TYPE = "Bearer";
/**
* @param {string} accessToken
* @param {number} expiresIn
* @param {string} tokenType
*/
constructor(
accessToken,
expiresIn,
tokenType,
) {
this.accessToken = accessToken;
this.expiresIn = expiresIn;
this.tokenType = tokenType;
}
/**
* Deserializes the data received from the Google OAuth API into an auth token.
* @param {object} data The JSON data to deserialize.
* @returns {AuthToken} The deserialized auth token.
*/
static deserialize(data) {
console.debug("Deserializing auth token data.");
try {
AuthTokenValidator.validate(data);
} catch (e) {
throw new Error(`Failed to validate auth token: ${e}`);
}
return new AuthToken(
data.access_token,
data.expires_in,
data.token_type,
);
}
/**
* Calculates the expiration timestamp of the access token.
* @returns {number} The expiration timestamp of the access token.
*/
calculateExpirationTimestamp() {
console.debug("Calculating expiration timestamp.");
const now = new Date();
const newSeconds = now.getSeconds() + this.expiresIn;
now.setSeconds(newSeconds);
return now.getTime();
}
/**
* Gets the access token.
* @returns {string} The access token.
*/
getAccessToken() {
console.debug(`Getting access token: ${this.accessToken}`);
return this.accessToken;
}
}
/**
* Validates the data received from the Google OAuth API.
*/
class AuthTokenValidator {
/**
* Validates whether the data received from the Google OAuth API is a valid auth token.
* @param {object} data The data to validate.
*/
static validate(data) {
console.debug("Validating auth token data.");
if (!data) {
throw new Error("No data provided.");
}
try {
this.validateAccessToken(data.access_token);
this.validateExpiresIn(data.expires_in);
this.validateTokenType(data);
} catch (e) {
throw new Error(`Invalid data: ${e}`);
}
}
static validateAccessToken(token) {
if (!this.isValidAccessToken(token)) {
throw new Error("Invalid access token.");
}
}
static isValidAccessToken(token) {
return token && token.length > 0;
}
static validateExpiresIn(expiresIn) {
if (!this.isValidExpiresIn(expiresIn)) {
throw new Error("Invalid expiration time.");
}
}
static isValidExpiresIn(expiresIn) {
return expiresIn && expiresIn > 0;
}
static validateTokenType(data) {
if (!this.isValidTokenType(data.token_type)) {
throw new Error("Invalid token type.");
}
}
static isValidTokenType(tokenType) {
return tokenType && tokenType === AuthToken.EXPECTED_TOKEN_TYPE;
}
}
/**
* Represents a client used to authenticate the user with the Google OAuth API.
*/
class AuthClient {
/**
* The OAuth client ID used to authenticate the user.
* @type {string}
*/
clientId;
/**
* The scope of the OAuth client ID.
* @type {string}
*/
scope;
SCOPES = [
"https://www.googleapis.com/auth/youtube",
];
constructor(clientId) {
this.clientId = clientId;
this.scope = this.getScope();
}
/**
* Fetches an authentication token from the Google OAuth API.
* @returns {Promise<AuthToken>}
*/
fetchAuthToken() {
console.info("Fetching auth token.");
return new Promise((resolve, reject) => {
const googleClient = this.getGoogleClient(resolve, reject);
googleClient.requestAccessToken();
});
}
getGoogleClient(resolve, reject) {
// eslint-disable-next-line no-undef
return google.accounts.oauth2.initTokenClient({
client_id: this.clientId,
scope: this.scope,
callback: (data) => this.processTokenResponse(data, resolve, reject),
});
}
processTokenResponse(data, resolve, reject) {
try {
const loginResponse = AuthToken.deserialize(data);
console.info("Login response:", loginResponse);
resolve(loginResponse);
} catch (e) {
reject(`Could not deserialize response: ${e}`);
}
}
getScope() {
return this.SCOPES.join(this.SCOPE_SEPARATOR);
}
}
/**
* Represents a service that manages authentication tokens for the user.
*/
class TokenService {
ACCESS_TOKEN_KEY = "ACCESS_TOKEN";
EXPIRATION_TIMESTAMP_KEY = "EXPIRY_TIME";
constructor() { }
/**
* Saves the authentication token to the settings storage.
* @param {AuthToken} authToken
*/
saveAuthToken(authToken) {
const accessToken = authToken.getAccessToken();
const expirationTimestamp = authToken.calculateExpirationTimestamp();
SettingsStorage.save(this.ACCESS_TOKEN_KEY, accessToken);
SettingsStorage.save(this.EXPIRATION_TIMESTAMP_KEY, expirationTimestamp);
}
isUserAuthenticated() {
console.info("Checking if user is authenticated.");
return this.getAccessToken() && !this.hasTokenExpired();
}
reset() {
console.info("Resetting token service.");
SettingsStorage.delete(this.ACCESS_TOKEN_KEY);
SettingsStorage.delete(this.EXPIRATION_TIMESTAMP_KEY);
}
getAccessToken() {
return SettingsStorage.load(this.ACCESS_TOKEN_KEY);
}
hasTokenExpired() {
const expiryTime = SettingsStorage.load(this.EXPIRATION_TIMESTAMP_KEY);
return !expiryTime || Date.now() > expiryTime;
}
}
/**
* Represents a service that manages OAuth client IDs for the user.
*/
class ClientIdService {
CLIENT_ID_KEY = "CLIENT_ID";
constructor() { }
/**
* Retrieves the OAuth client ID from the user.
* @returns {string} The OAuth client ID.
*/
fetchClientId() {
console.info("Fetching OAuth client ID.");
const clientId = SettingsStorage.load(this.CLIENT_ID_KEY);
if (!clientId) {
return this.showClientIdPrompt();
}
return clientId;
}
showClientIdPrompt() {
const clientId = prompt("Please enter your Google OAuth client ID.");
if (!clientId) {
throw new Error("No client ID provided.");
}
SettingsStorage.save(this.CLIENT_ID_KEY, clientId);
return clientId;
}
reset() {
SettingsStorage.delete(this.CLIENT_ID_KEY);
}
}
/**
* Represents a service that manages authentication for the user.
*/
class AuthService {
/**
* Indicates whether the authentication service has been initialized.
* @type {boolean}
*/
initialized = false;
/**
* The token service used to manage authentication tokens.
* @type {TokenService}
*/
tokenService;
/**
* The client ID service used to manage OAuth client IDs.
* @type {ClientIdService}
*/
clientIdService;
GOOGLE_AUTH_MODE = "popup";
GSI_SCRIPT_URL = "https://accounts.google.com/gsi/client";
REDIRECT_URI = "https://services.planningcenteronline.com";
SCOPE_SEPARATOR = " ";
/**
* @param {TokenService} tokenService
* @param {ClientIdService} clientIdService
*/
constructor(tokenService, clientIdService) {
this.tokenService = tokenService;
this.clientIdService = clientIdService;
}
/**
* Initializes the authentication service by injecting the Google Sign-In script.
* @returns {Promise<void>}
*/
async init() {
console.debug("Initializing authentication service.");
if (this.initialized) {
return;
}
this.initialized = true;
await this.injectGSIScript();
}
/**
* Logs the user in using Google OAuth.
* @returns {Promise<void>}
*/
async login() {
if (this.tokenService.isUserAuthenticated()) {
console.info("User is already authenticated.");
return;
}
await this.authenticate();
}
logout() {
console.info("Logging user out.");
this.tokenService.reset();
}
async injectGSIScript() {
const script = document.createElement("script");
script.src = this.GSI_SCRIPT_URL;
document.head.appendChild(script);
await new Promise((resolve) => {
script.onload = resolve;
});
}
async authenticate() {
console.info("Authenticating user.");
const client = this.createTokenClient();
try {
const loginResponse = await client.fetchAuthToken();
this.tokenService.saveAuthToken(loginResponse);
} catch (e) {
throw new Error(`Failed to fetch access token: ${e}`);
}
}
createTokenClient() {
const clientId = this.clientIdService.fetchClientId();
if (!clientId) {
throw new Error("OAuth client ID is missing or invalid.");
}
return new AuthClient(clientId);
}
getAccessToken() {
return this.tokenService.getAccessToken();
}
reset() {
this.tokenService.reset();
this.clientIdService.reset();
this.initialized = false;
}
}
/**
* A service that interacts with the YouTube API to create and manage streams.
*/
class YouTubeApiService {
/**
* The authentication service used to authenticate the user.
* @type {AuthService}
*/
authenticationService;
HTTP_UNAUTHORIZED_CODE = 401;
HTTP_FORBIDDEN_CODE = 403;
RETRY_DELAY_MS = 1000;
YOUTUBE_API_BASE_URL = "https://www.googleapis.com/youtube/v3";
AUTHORIZATION_HEADER_KEY = "Authorization";
BEARER_TOKEN_PREFIX = "Bearer";
/**
* @param {AuthService} authenticationService - The authentication service used to authenticate the user.
*/
constructor(authenticationService) {
this.authenticationService = authenticationService;
}
/**
* Executes an API request to the YouTube API.
* @param {string} endpoint - The API endpoint to call.
* @param {unknown} options - The options to pass to the fetch request.
* @returns {Promise<unknown>} The response data from the API.
*/
async executeRequest(endpoint, options = {}) {
const url = this.buildUrl(endpoint);
options.headers = options.headers || new Headers();
options.headers.set(this.AUTHORIZATION_HEADER_KEY, this.getBearerToken());
console.info(`Executing request to ${url}`);
try {
const res = await fetch(url, options);
return await this.handleResponse(res, endpoint, options);
} catch (err) {
console.error(err);
}
}
async handleResponse(res, endpoint, options) {
console.debug(res);
if (res.ok) {
return await res.json();
} else if (this.isUnauthorized(res.status)) {
await this.authenticationService.login();
// This delay is here to prevent the API from being spammed with requests if the user is not authenticated.
await this.delay(this.RETRY_DELAY_MS);
// Retry the request after re-authentication
return await this.executeRequest(endpoint, options);
}
throw new Error("Failed to fetch YouTube data.");
}
buildUrl(endpoint) {
return `${this.YOUTUBE_API_BASE_URL}${endpoint}`;
}
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
isUnauthorized(status) {
return (
status === this.HTTP_UNAUTHORIZED_CODE ||
status === this.HTTP_FORBIDDEN_CODE
);
}
getRequestOptions() {
return {
headers: this.getRequestHeaders(),
};
}
getRequestHeaders() {
const headers = new Headers();
const bearerToken = this.getBearerToken();
headers.set(this.AUTHORIZATION_HEADER_KEY, bearerToken);
return headers;
}
getBearerToken() {
const accessToken = this.authenticationService.getAccessToken();
return `${this.BEARER_TOKEN_PREFIX} ${accessToken}`;
}
}
/**
* Represents the visibility status of a YouTube stream.
*/
class StreamVisibility {
static PUBLIC = "public";
static UNLISTED = "unlisted";
static PRIVATE = "private";
}
/**
* Represents a YouTube stream that can be uploaded to YouTube.
*/
class YouTubeStream {
/**
* The title of the stream.
* @type {string}
*/
title;
/**
* The description of the stream.
* @type {string}
*/
description;
/**
* The scheduled start time of the stream.
* @type {Date}
*/
startTime;
/**
* The visibility status of the stream.
* @type {string}
*/
visibility;
constructor() {
this.title = "";
this.startTime = new Date();
this.visibility = StreamVisibility.PRIVATE; // TODO: Change this to public by default
}
/**
* Serializes the stream data into a format that can be uploaded to YouTube.
*/
serialize() {
return {
snippet: {
title: this.getTitle(),
description: this.getDescription(),
scheduledStartTime: this.getStartTime().toISOString(),
},
status: {
privacyStatus: this.getVisibility(),
},
}
}
getTitle() {
return this.title;
}
setTitle(title) {
this.title = title;
return this;
}
getDescription() {
return this.description;
}
setDescription(description) {
this.description = description;
return this;
}
getStartTime() {
return this.startTime;
}
setStartTime(startTime) {
this.startTime = startTime;
return this;
}
getVisibility() {
return this.visibility;
}
setVisibility(visibility) {
this.visibility = visibility;
return this;
}
}
/**
* A service that interacts with the YouTube API to create and manage streams.
*/
class YouTubeStreamService {
/**
* The YouTube API service used to interact with the YouTube API.
* @type {YouTubeApiService}
*/
apiService;
DUMMY_ENDPOINT = "/channels?part=snippet&mine=true";
CREATE_STREAM_ENDPOINT = "/liveBroadcasts?part=snippet,status";
/**
* @param {YouTubeApiService} apiService
*/
constructor(apiService) {
this.apiService = apiService;
}
/**
* @deprecated
* Just a dummy API request to test the API connection and authentication.
*/
async dummyApiRequest() {
console.info("Making dummy API request.");
return await this.apiService.executeRequest(this.DUMMY_ENDPOINT);
}
/**
* Uploads a stream to YouTube.
* @param {YouTubeStream} stream
*/
async uploadStream(stream) {
console.log("Uploading stream to YouTube.");
const headers = this.apiService.getRequestHeaders();
headers.set("Content-Type", "application/json");
const data = stream.serialize();
await this.apiService.executeRequest(this.CREATE_STREAM_ENDPOINT, {
method: "POST",
headers: headers,
body: JSON.stringify(data),
});
}
}
class PlanningCenterService {
static API_BASE_URL = "https://api.planningcenteronline.com/services/v2";
constructor() { }
/**
* Gets a plan from PlanningCenter by its ID.
* @param {number} id the ID of the plan
* @returns {Promise<object>} the plan data
*/
async fetchPlan(id) {
const url = this.buildPlanUrl(id);
try {
return await this.fetchJsonData(url);
} catch (error) {
throw new Error(`Failed to fetch plan: ${error}`);
}
}
/**
* Gets the notes in a plan from PlanningCenter by its ID.
* @param {number} planId the ID of the plan
* @returns {Promise<object>} the notes in the plan
*/
async fetchNotes(planId) {
const url = `${this.buildPlanUrl(planId)}/notes`;
try {
return await this.fetchJsonData(url);
} catch (error) {
throw new Error(`Failed to fetch notes: ${error}`);
}
}
/**
* Gets the songs in a plan from PlanningCenter by its ID.
* @param {number} planId the ID of the plan
* @returns {Promise<object>} the songs in the plan
*/
async fetchSongs(planId) {
const items = await this.fetchItems(planId);
const songIds = items.data.filter((item) => item.relationships.song.data !== null).map((item) => item.relationships.song.data.id);
try {
const promises = songIds.map((songId) => this.fetchSong(songId));
return await Promise.all(promises);
} catch (error) {
throw new Error(`Failed to fetch songs: ${error}`);
}
}
async fetchSong(songId) {
const url = `${PlanningCenterService.API_BASE_URL}/songs/${songId}`;
try {
return await this.fetchJsonData(url);
} catch (error) {
throw new Error(`Failed to fetch song: ${error}`);
}
}
async fetchItems(planId) {
const url = `${this.buildPlanUrl(planId)}/items`;
try {
return await this.fetchJsonData(url);
} catch (error) {
throw new Error(`Failed to fetch items: ${error}`);
}
}
async fetchJsonData(url) {
const res = await fetch(url, { credentials: "include" });
return await res.json();
}
buildPlanUrl(id) {
return `${PlanningCenterService.API_BASE_URL}/plans/${id}`;
}
}
/**
* Handles everything related to the DOM.
*/
class DomService {
static ORIGINAL_BUTTON_SELECTOR = `button[aria-label="Share"]`;
constructor() { }
/**
* Creates a button that allows the user to create a stream.
*/
async createStreamButton() {
console.debug("Creating stream button.");
const originalButton = await this.queryElement(DomService.ORIGINAL_BUTTON_SELECTOR);
const youtubeButton = originalButton.cloneNode(true);
youtubeButton.setAttribute("aria-label", "New Stream");
youtubeButton.innerText = "New Stream";
originalButton.parentNode.prepend(youtubeButton);
return youtubeButton;
}
/**
* Gets the ID of the plan from the URL.
* @returns {number}
*/
getPlanId() {
const rawId = window.location.pathname.split("/").pop();
return Number(rawId);
}
/**
* Shows a preview of the stream that will be created, and allows the user to confirm the stream creation.
* @param {YouTubeStream} stream - The stream to preview.
*/
confirmStreamCreation(stream) {
return confirm(`Do you want to create a stream titled "${stream.getTitle()}"?`);
}
queryElement(selector) {
return new Promise((resolve) => {
const element = document.querySelector(selector);
if (element) {
resolve(element);
return;
}
const observer = new MutationObserver(() => {
const newElement = document.querySelector(selector);
if (newElement) {
observer.disconnect();
resolve(newElement);
}
});
observer.observe(document.body, {
childList: true,
subtree: true,
});
});
}
}
class DateFormatter {
static LOCALE_LANGUAGE = "nl-NL";
static YEAR_FORMAT = "numeric";
static MONTH_FORMAT = "2-digit";
static DAY_FORMAT = "2-digit";
static format(date) {
const options = {
year: DateFormatter.YEAR_FORMAT,
month: DateFormatter.MONTH_FORMAT,
day: DateFormatter.DAY_FORMAT,
};
return date.toLocaleString(DateFormatter.LOCALE_LANGUAGE, options);
}
}
/**
* Manages the streams that are created and uploaded to YouTube.
*/
class StreamManager {
static PREACHER_NOTE_CATEGORY = "Spreker";
static THEME_NOTE_CATEGORY = "Thema";
static DESCRIPTION_TEMPLATE = [
"De diensten beginnen elke zondag om 10:00 uur.",
"",
"Liederen",
"{SONGS}",
"",
"Informatie",
"Wil je meer weten over kerk De Fontein of in contact komen met ons? Bezoek dan onze website https://www.kerkdefontein.nl/",
"Liever mailen? Dat kan via info@kerkdefontein.nl",
].join("\n");
/**
* The YouTube stream service used to interact with the YouTube API.
* @type {YouTubeStreamService}
*/
youtubeStreamService;
/**
* The PlanningCenter service used to interact with the PlanningCenter API.
* @type {PlanningCenterService}
*/
planningCenterService;
/**
* @param {DomService} domService
*/
domService;
/**
* @param {YouTubeStreamService} youtubeStreamService
* @param {PlanningCenterService} planningCenterService
* @param {DomService} domService
*/
constructor(youtubeStreamService, planningCenterService, domService) {
this.youtubeStreamService = youtubeStreamService;
this.planningCenterService = planningCenterService;
this.domService = domService;
}
/**
* Initializes the stream manager.
*/
async init() {
console.info("Initializing stream manager.");
const planId = this.domService.getPlanId();
const streamButton = await this.domService.createStreamButton();
streamButton.addEventListener("click", () => this.onStreamButtonClick(planId));
}
/**
* Creates a stream and uploads it to YouTube.
* @param {number} planId - The ID of the plan to create a stream for.
*/
async onStreamButtonClick(planId) {
console.info("Stream button clicked.");
const stream = await this.getStreamFromPlanId(planId);
const confirmed = this.domService.confirmStreamCreation(stream);
if (confirmed) {
await this.createStream(stream);
} else {
alert("Stream creation cancelled.");
}
}
async getStreamFromPlanId(planId) {
const planData = await this.planningCenterService.fetchPlan(planId);
console.debug("Plan data:", planData);
const notes = await this.planningCenterService.fetchNotes(planId);
console.debug("Notes:", notes);
const description = await this.getDescription(planId);
console.debug("Description:", description);
const title = this.getTitle(planData, notes);
console.debug("Title:", title);
const date = this.getDate(planData);
return new YouTubeStream()
.setTitle(title)
.setDescription(description)
.setStartTime(date);
}
getTitle(planData, notes) {
const date = this.getFormattedDate(planData);
console.debug("Date:", date);
const preacher = this.getPreacher(notes);
console.debug("Preacher:", preacher);
const theme = this.getTheme(notes);
console.debug("Theme:", theme);
return `${theme} - ${preacher} | ${date}`;
}
getFormattedDate(planData) {
const rawDate = this.getDate(planData);
return DateFormatter.format(rawDate);
}
getDate(planData) {
const now = new Date();
console.debug("Date attributes:", planData.data.attributes);
// PlanningCenter stores dates in UTC, so we need to convert it to local time to match the date & time with the UI.
const utcDate = new Date(planData.data.attributes.sort_date);
// The timezone offset is in minutes, so we need to convert it to milliseconds.
const localOffsetMs = utcDate.getTimezoneOffset() * 60 * 1000;
let plannedDate = new Date(utcDate.getTime() + localOffsetMs);
// If the planned date is in the past, we need to schedule the stream for the future.
if (plannedDate < now) {
// add 5 minutes to the current time to prevent scheduling a stream in the past.
plannedDate = new Date(now.getTime() + 5 * 60 * 1000);
}
console.debug(`Planned date: ${plannedDate.toISOString()}`);
return plannedDate;
}
async getDescription(planId) {
const songs = await this.planningCenterService.fetchSongs(planId);
console.debug("Songs:", songs);
const songLines = songs.map((song) => {
const title = song.data.attributes.title;
const author = song.data.attributes.author;