diff --git a/CHANGELOG.md b/CHANGELOG.md index d147cc05..bb39b3b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Support for multiple profiles. You can now use multiple Invidious accounts. - When a video error dialog shows, a timer with 10 seconds starts to play the next video ### Fixed diff --git a/docs/playlet-web-api.yml b/docs/playlet-web-api.yml index 1f3a95ef..d65c1bb9 100644 --- a/docs/playlet-web-api.yml +++ b/docs/playlet-web-api.yml @@ -322,14 +322,63 @@ paths: schema: type: string format: uri - /invidious/logout: + /api/profiles: get: - summary: Logout from Invidious - description: Logout from Invidious, and invalidate the token if any. - operationId: invidiousLogout + summary: Get profiles + description: Get the logged profiles, and the currently active profile. + operationId: getProfiles responses: - "204": - description: No Content + "200": + description: OK + content: + application/json: + schema: + type: object + properties: + currentProfile: + type: string + profiles: + type: array + items: + $ref: "#/components/schemas/ProfileObject" + delete: + summary: Logout from a profile + description: Logout from a profile. This will remove the profile from the list of logged profiles. + operationId: logoutProfile + parameters: + - name: id + in: query + description: The ID of the profile to logout + required: true + schema: + type: string + responses: + "200": + description: OK + "400": + description: Bad Request + "404": + description: Not Found + /api/profiles/activate: + post: + summary: Activate a profile + description: Activate a profile. This will set the profile as the active profile. + operationId: activateProfile + requestBody: + content: + application/json: + schema: + type: object + properties: + id: + type: string + responses: + "200": + description: OK + "400": + description: Bad Request + "404": + description: Not Found # Roku External Control Protocol (ECP) /input/{appId}: @@ -530,14 +579,17 @@ components: type: string auth_url: type: string - logged_in: - type: boolean - logged_in_instance: - type: string - logged_in_username: - type: string preferences: $ref: "#/components/schemas/PreferencesObject" + profiles: + type: object + properties: + currentProfile: + type: string + profiles: + type: array + items: + $ref: "#/components/schemas/ProfileObject" PreferencesObject: type: object properties: @@ -560,6 +612,17 @@ components: type: boolean sponsorblock.show_notifications: type: boolean + ProfileObject: + type: object + properties: + id: + type: string + type: + type: string + username: + type: string + serverUrl: + type: string # TODO:P1 add the rest of properties VideoQueueObject: type: object diff --git a/playlet-lib/src/components/ContentNode/ActionContentNode.xml b/playlet-lib/src/components/ContentNode/ActionContentNode.xml deleted file mode 100644 index 9643fc02..00000000 --- a/playlet-lib/src/components/ContentNode/ActionContentNode.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/playlet-lib/src/components/ContentNode/ProfileContentNode.xml b/playlet-lib/src/components/ContentNode/ProfileContentNode.xml new file mode 100644 index 00000000..acd96368 --- /dev/null +++ b/playlet-lib/src/components/ContentNode/ProfileContentNode.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/playlet-lib/src/components/Dialog/LoginDialog.bs b/playlet-lib/src/components/Dialog/LoginDialog.bs index b5fc59ce..70278838 100644 --- a/playlet-lib/src/components/Dialog/LoginDialog.bs +++ b/playlet-lib/src/components/Dialog/LoginDialog.bs @@ -42,5 +42,6 @@ function OnUrlSet() end function function OnAuthTokenChange() + m.invidious.unobserveFieldScoped("authToken") Close() end function diff --git a/playlet-lib/src/components/MainScene.transpiled.xml b/playlet-lib/src/components/MainScene.transpiled.xml index 435af8f6..6a22bbd9 100644 --- a/playlet-lib/src/components/MainScene.transpiled.xml +++ b/playlet-lib/src/components/MainScene.transpiled.xml @@ -22,8 +22,9 @@ - + + @@ -41,6 +42,7 @@ + diff --git a/playlet-lib/src/components/MainScene.xml b/playlet-lib/src/components/MainScene.xml index ec5bdeb6..d9aab65a 100644 --- a/playlet-lib/src/components/MainScene.xml +++ b/playlet-lib/src/components/MainScene.xml @@ -8,8 +8,15 @@ videoQueue="bind:./VideoQueue"> - + + + + + + preferences="bind:../Preferences" + profiles="bind:../Profiles" /> + + \ No newline at end of file diff --git a/playlet-lib/src/components/NavBar/ProfileIconButton.bs b/playlet-lib/src/components/NavBar/ProfileIconButton.bs new file mode 100644 index 00000000..4b971a07 --- /dev/null +++ b/playlet-lib/src/components/NavBar/ProfileIconButton.bs @@ -0,0 +1,111 @@ +import "pkg:/source/utils/Logging.bs" +import "pkg:/source/utils/MathUtils.bs" +import "pkg:/source/utils/StringUtils.bs" +import "pkg:/source/utils/Types.bs" + +' TODO:P1 this file is a copy paste of IconButton. It should be refactored. +function Init() + m.buttonBackground = m.top.findNode("buttonBackground") + m.buttonIcon = m.top.findNode("buttonIcon") + m.buttonText = m.top.findNode("buttonText") + + m.circlePoster = m.top.findNode("circlePoster") + m.circlePosterInner = m.top.findNode("circlePosterInner") + m.letterLabel = m.top.findNode("LetterLabel") + + m.top.observeField("background", FuncName(onBackgroundChanged)) + m.top.observeField("icon", FuncName(onIconChanged)) + m.top.observeField("text", FuncName(onTextChanged)) + m.top.observeField("height", FuncName(onHeightChanged)) + m.top.observeField("width", FuncName(onWidthChanged)) + m.top.observeField("padding", FuncName(onPaddingChanged)) + + profiles = m.top.getScene().findNode("Profiles") + if profiles <> invalid + m.profiles = profiles + profiles.observeField("currentProfile", FuncName(OnCurrentProfile)) + OnCurrentProfile() + end if +end function + +function OnFocusChange() + if m.top.focus + m.buttonBackground.blendColor = m.top.focusBackground + else + m.buttonBackground.blendColor = m.top.background + end if + m.buttonBackground.visible = m.top.focus + m.buttonText.visible = m.top.focus +end function + +function onBackgroundChanged() + m.buttonBackground.blendColor = m.top.background +end function + +function onIconChanged() + m.buttonIcon.uri = m.top.icon +end function + +function onTextChanged() + m.buttonText.text = m.top.text +end function + +function setIconSize() + height = m.top.height + width = m.top.width + if height > 0 and width > 0 + iconSize = MathUtils.Min(height, width) - m.top.padding + m.buttonIcon.height = iconSize + m.buttonIcon.width = iconSize + + iconTranslation = [((width - iconSize) / 2), ((height - iconSize) / 2)] + m.buttonIcon.translation = iconTranslation + m.buttonText.translation = [-5, height + 2] + m.buttonText.width = width + 10 + + m.circlePoster.width = iconSize + m.circlePoster.height = iconSize + m.circlePoster.translation = iconTranslation + + m.circlePosterInner.width = iconSize - 4 + m.circlePosterInner.height = iconSize - 4 + + m.letterLabel.width = iconSize - 4 + m.letterLabel.height = iconSize - 4 + end if +end function + +function onHeightChanged() + m.buttonBackground.height = m.top.height + setIconSize() +end function + +function onWidthChanged() + m.buttonBackground.width = m.top.width - 10 + m.buttonBackground.translation = [5, 0] + setIconSize() +end function + +function onPaddingChanged() + setIconSize() +end function + +function OnCurrentProfile() as void + currentProfile = m.profiles.currentProfile + if currentProfile = invalid + m.circlePoster.visible = false + m.buttonIcon.visible = true + return + end if + + username = currentProfile.username + if not StringUtils.IsNullOrEmpty(username) + m.LetterLabel.text = UCase(username.Left(1)) + else + m.LetterLabel.text = "" + end if + m.circlePosterInner.blendColor = currentProfile.color + + m.circlePoster.visible = true + m.buttonIcon.visible = false +end function diff --git a/playlet-lib/src/components/NavBar/ProfileIconButton.xml b/playlet-lib/src/components/NavBar/ProfileIconButton.xml new file mode 100644 index 00000000..34da6903 --- /dev/null +++ b/playlet-lib/src/components/NavBar/ProfileIconButton.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/playlet-lib/src/components/ProfileView/ProfileView.bs b/playlet-lib/src/components/ProfileView/ProfileView.bs new file mode 100644 index 00000000..9b79515b --- /dev/null +++ b/playlet-lib/src/components/ProfileView/ProfileView.bs @@ -0,0 +1,160 @@ +import "pkg:/components/Navigation/Navigation.bs" +import "pkg:/source/utils/DisposableObserve.bs" +import "pkg:/source/utils/FocusManagement.bs" +import "pkg:/source/utils/StringUtils.bs" +import "pkg:/source/utils/Types.bs" + +function Init() + m.activateButton = m.top.findNode("activateButton") + m.logoutButton = m.top.findNode("logoutButton") + m.closeButton = m.top.findNode("closeButton") + m.buttonGroup = m.top.findNode("buttonGroup") + + DisposableObserveField(m.activateButton, "buttonSelected", FuncName(Activate)) + DisposableObserveField(m.logoutButton, "buttonSelected", FuncName(Logout)) + DisposableObserveField(m.closeButton, "buttonSelected", FuncName(Close)) +end function + +function OnNodeReady() + SetNavigation(m.activateButton, "down", m.logoutButton) + SetNavigation(m.logoutButton, "down", m.closeButton) + SetNavigation(m.closeButton, "up", m.logoutButton) + SetNavigation(m.logoutButton, "up", m.activateButton) + + DisposableObserveFieldScoped(m.profiles, "currentProfile", FuncName(OnCunrrentProfileChanged)) + DisposableObserveFieldScoped(m.profiles, "onProfileLogout", FuncName(OnProfileLogout)) +end function + +function OnContentSet() as void + content = m.top.content + if content = invalid + return + end if + + m.top.circlePosterInnerUri = "pkg:/images/white-circle.png" + m.top.circlePosterInnerBlendColor = content.color + username = content.username + m.top.username = username + if not StringUtils.IsNullOrEmpty(username) + m.top.letter = UCase(username.Left(1)) + else + m.top.letter = "" + end if + m.top.serverUrl = content.serverUrl + m.top.crownVisible = content.isSelected + UpdateActivateButton() +end function + +function OnFocusChange() as void + if not m.top.focus + return + end if + + if m.activateButton.focusable + NodeSetFocus(m.activateButton, true) + else + NodeSetFocus(m.logoutButton, true) + end if +end function + +function OnkeyEvent(key as string, press as boolean) as boolean + if NavigationKeyHandler(key, press).handled + return true + end if + + if key = "options" + ' A pass-through to the app controller, so it can toggle picture-in-picture + return false + end if + + if key = "back" and press + Close() + return true + end if + + return true +end function + +function Activate() as void + content = m.top.content + if content = invalid + return + end if + + profile = m.profiles.content.getChild(0).findNode(content.id) + if profile = invalid + return + end if + + m.top.content = invalid + m.profiles@.SetCurrentProfile(profile) + Close() +end function + +function Logout() as void + content = m.top.content + if content = invalid + return + end if + + m.top.content = invalid + m.profiles@.LogoutWithProfile(content) + Close() +end function + +function Close() + m.top.appController@.PopScreen() + m.top.dispose = true +end function + +function OnDispose() + DisposeObservers() + m.top.content = invalid +end function + +function OnCunrrentProfileChanged() as void + content = m.top.content + if content = invalid + return + end if + m.top.crownVisible = content.isSelected + UpdateActivateButton() +end function + +function OnProfileLogout() as void + content = m.top.content + if content = invalid + return + end if + + profile = m.profiles.content.getChild(0).findNode(content.id) + if profile = invalid + Close() + end if +end function + +function UpdateActivateButton() as void + content = m.top.content + if content = invalid + return + end if + + isSelected = content.isSelected + if isSelected + if m.activateButton.hasFocus() + NodeSetFocus(m.logoutButton, true) + end if + + parent = m.activateButton.getParent() + if parent <> invalid + m.buttonGroup.removeChild(m.activateButton) + end if + m.activateButton.focusable = false + else + parent = m.activateButton.getParent() + if parent = invalid + m.buttonGroup.insertChild(m.activateButton, 0) + end if + m.activateButton.focusable = true + end if +end function diff --git a/playlet-lib/src/components/ProfileView/ProfileView.xml b/playlet-lib/src/components/ProfileView/ProfileView.xml new file mode 100644 index 00000000..4620088f --- /dev/null +++ b/playlet-lib/src/components/ProfileView/ProfileView.xml @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/playlet-lib/src/components/ProfileView/ProfileViewUtils.bs b/playlet-lib/src/components/ProfileView/ProfileViewUtils.bs new file mode 100644 index 00000000..4f097a6d --- /dev/null +++ b/playlet-lib/src/components/ProfileView/ProfileViewUtils.bs @@ -0,0 +1,11 @@ +namespace ProfileViewUtils + + function Open(profile as object, appController as object) + profileView = CreateObject("roSGNode", "ProfileView") + + appController@.PushScreen(profileView) + profileView@.BindNode() + profileView.content = profile + end function + +end namespace diff --git a/playlet-lib/src/components/Screens/ProfileScreen/ProfileRowList/ProfileRowList.xml b/playlet-lib/src/components/Screens/ProfileScreen/ProfileRowList/ProfileRowList.xml new file mode 100644 index 00000000..fe1d56ab --- /dev/null +++ b/playlet-lib/src/components/Screens/ProfileScreen/ProfileRowList/ProfileRowList.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/playlet-lib/src/components/Screens/ProfileScreen/ProfileRowList/ProfileRowListCell.bs b/playlet-lib/src/components/Screens/ProfileScreen/ProfileRowList/ProfileRowListCell.bs new file mode 100644 index 00000000..4901afff --- /dev/null +++ b/playlet-lib/src/components/Screens/ProfileScreen/ProfileRowList/ProfileRowListCell.bs @@ -0,0 +1,68 @@ +import "pkg:/source/utils/StringUtils.bs" + +function Init() + m.normalFont = m.top.findNode("normalFont") + m.boldFont = m.top.findNode("boldFont") +end function + +function OnContentSet() as void + content = m.top.itemContent + if content = invalid + return + end if + + if content.type = "login" + m.top.circlePosterInnerUri = "pkg:/images/icons/user-200.png" + ' bs:disable-next-line LINT3023 + m.top.circlePosterInnerBlendColor = "#FFFFFFFF" + m.top.letter = "" + m.top.username = "Login" + m.top.serverUrl = "" + m.top.crownVisible = false + return + end if + + m.top.circlePosterInnerUri = "pkg:/images/white-circle.png" + m.top.circlePosterInnerBlendColor = content.color + username = content.username + m.top.username = username + if not StringUtils.IsNullOrEmpty(username) + m.top.letter = UCase(username.Left(1)) + else + m.top.letter = "" + end if + m.top.serverUrl = content.serverUrl + m.top.crownVisible = content.isSelected +end function + +function OnRowListHasFocus() + if not m.top.rowListHasFocus + m.top.animate = false + end if +end function + +function OnItemHasFocus() + m.top.animate = (m.top.itemHasFocus or m.top.focusPercent > 0.5) and m.top.rowListHasFocus +end function + +function OnFocusPercent() + if m.top.focusPercent > 0.5 and m.top.rowListHasFocus + m.top.animate = true + else + m.top.animate = false + end if +end function + +function OnAnimate() + animate = m.top.animate + m.top.shadowVisible = animate + m.top.serverLabelVisible = animate + m.top.circlePosterTranslation = [20, 20] + if animate + m.top.UsernameLabelFont = m.boldFont + m.top.animationControl = "start" + else + m.top.UsernameLabelFont = m.normalFont + m.top.animationControl = "stop" + end if +end function diff --git a/playlet-lib/src/components/Screens/ProfileScreen/ProfileRowList/ProfileRowListCell.xml b/playlet-lib/src/components/Screens/ProfileScreen/ProfileRowList/ProfileRowListCell.xml new file mode 100644 index 00000000..bd1b1cc4 --- /dev/null +++ b/playlet-lib/src/components/Screens/ProfileScreen/ProfileRowList/ProfileRowListCell.xml @@ -0,0 +1,106 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/playlet-lib/src/components/Screens/ProfileScreen/ProfileScreen.bs b/playlet-lib/src/components/Screens/ProfileScreen/ProfileScreen.bs new file mode 100644 index 00000000..376c7f52 --- /dev/null +++ b/playlet-lib/src/components/Screens/ProfileScreen/ProfileScreen.bs @@ -0,0 +1,63 @@ +import "pkg:/components/Dialog/DialogUtils.bs" +import "pkg:/components/Navigation/Navigation.bs" +import "pkg:/components/ProfileView/ProfileViewUtils.bs" +import "pkg:/source/utils/FocusManagement.bs" +import "pkg:/source/utils/Types.bs" + +function Init() + m.top.focusable = true + m.profileRowList = m.top.FindNode("ProfileRowList") +end function + +function OnNodeReady() + SetNavigation(invalid, "back", m.navBar) + SetNavigation(invalid, "left", m.navBar) + + m.profileRowList.content = m.profiles.content + m.profileRowList.observeFieldScoped("rowItemSelected", FuncName(OnRowItemSelected)) + m.profiles.observeFieldScoped("currentProfile", FuncName(OnCurrentProfileChanged)) +end function + +function OnFocusChange() as void + if not m.top.focus + return + end if + NodeSetFocus(m.profileRowList, true) +end function + +function OnkeyEvent(key as string, press as boolean) as boolean + if NavigationKeyHandler(key, press).handled + return true + end if + return false +end function + +function OnRowItemSelected() as void + index = m.profileRowList.rowItemSelected[1] + row = m.profileRowList.content.GetChild(0) + selectedProfile = row.GetChild(index) + if selectedProfile.type = "login" + dialog = CreateObject("roSGNode", "LoginDialog") + dialog@.BindNode() + m.top.getScene().dialog = dialog + return + end if + + ProfileViewUtils.Open(selectedProfile, m.appController) +end function + +function OnCurrentProfileChanged() as void + currentProfile = m.profiles.currentProfile + if currentProfile = invalid + return + end if + + row = m.profileRowList.content.GetChild(0) + allProfiles = row.getChildren(-1, 0) + for i = 0 to allProfiles.Count() - 1 + if currentProfile.id = allProfiles[i].id + m.profileRowList.jumpToRowItem = [0, i] + return + end if + end for +end function diff --git a/playlet-lib/src/components/Screens/ProfileScreen/ProfileScreen.xml b/playlet-lib/src/components/Screens/ProfileScreen/ProfileScreen.xml new file mode 100644 index 00000000..770ad9c9 --- /dev/null +++ b/playlet-lib/src/components/Screens/ProfileScreen/ProfileScreen.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/playlet-lib/src/components/Screens/RemoteScreen/GenerateQrCodeTask.bs b/playlet-lib/src/components/Screens/RemoteScreen/GenerateQrCodeTask.bs index ba22c1f3..aab01fa6 100644 --- a/playlet-lib/src/components/Screens/RemoteScreen/GenerateQrCodeTask.bs +++ b/playlet-lib/src/components/Screens/RemoteScreen/GenerateQrCodeTask.bs @@ -1,6 +1,8 @@ import "pkg:/source/QrCode/QrImage.bs" import "pkg:/source/utils/StringUtils.bs" +' TODO:P1 create a QRCode component that has a loading spinner while the QRCode is being generated +' It is slow and can take several seconds. @asynctask function GenerateQrCodeTask(input as object) poster = input.poster diff --git a/playlet-lib/src/components/Services/Invidious/Invidious.bs b/playlet-lib/src/components/Services/Invidious/Invidious.bs index 08da3450..9fecea2c 100644 --- a/playlet-lib/src/components/Services/Invidious/Invidious.bs +++ b/playlet-lib/src/components/Services/Invidious/Invidious.bs @@ -5,7 +5,6 @@ import "pkg:/source/AsyncTask/Tasks.bs" function Init() m.top.apiDefinitions = ParseJson(ReadAsciiFile("libpkg:/config/invidious_video_api.yaml")) m.service = new Invidious.InvidiousService(m.top) - m.top.authToken = m.service.GetAuthToken() end function function GetCurrentInstance(_unused as dynamic) as string @@ -16,10 +15,6 @@ function GetAuthorizeTokenLink(_unused as dynamic) as dynamic return m.service.GetAuthorizeTokenLink() end function -function SetAuthToken(token as string, instance as string, username as dynamic) - m.service.SetAuthToken(token, instance, username) -end function - function OnAuthTokenChange() as void m.top.refreshSubscribtions = true end function diff --git a/playlet-lib/src/components/Services/Invidious/Invidious.xml b/playlet-lib/src/components/Services/Invidious/Invidious.xml index 870d8297..3c45dfdc 100644 --- a/playlet-lib/src/components/Services/Invidious/Invidious.xml +++ b/playlet-lib/src/components/Services/Invidious/Invidious.xml @@ -3,6 +3,7 @@ + @@ -11,6 +12,5 @@ - \ No newline at end of file diff --git a/playlet-lib/src/components/Services/Invidious/InvidiousService.bs b/playlet-lib/src/components/Services/Invidious/InvidiousService.bs index 87ed331e..6b2b1ae1 100644 --- a/playlet-lib/src/components/Services/Invidious/InvidiousService.bs +++ b/playlet-lib/src/components/Services/Invidious/InvidiousService.bs @@ -37,15 +37,15 @@ namespace Invidious const ERROR_NOT_AUTHENTICATED = "Not authenticated" class InvidiousService - public node as object + public invidiousNode as object - function new(node as object) - m.node = node + function new(invidiousNode as object) + m.invidiousNode = invidiousNode end function function GetUserRegion() as string if m._userRegion = invalid - m._userRegion = m.node.applicationInfo@.GetUserCountryCode() + m._userRegion = m.invidiousNode.applicationInfo@.GetUserCountryCode() end if return m._userRegion end function @@ -58,7 +58,7 @@ namespace Invidious function GetInstance() as string if m.preferences = invalid - m.preferences = m.node.preferences + m.preferences = m.invidiousNode.preferences end if instance = m.preferences["invidious.instance"] if not StringUtils.IsNullOrEmpty(instance) @@ -73,7 +73,7 @@ namespace Invidious return end if - authToken = m.node.authToken + authToken = m.invidiousNode.authToken if authToken = invalid return end if @@ -149,7 +149,7 @@ namespace Invidious end function function GetPlaylist(playlistId as string, index = 0 as integer, cancellation = invalid as object) as object - authToken = m.node.authToken + authToken = m.invidiousNode.authToken if authToken = invalid instance = m.GetInstance() url = `${instance}${Invidious.PLAYLISTS_ENDPOINT}/${playlistId}` @@ -194,7 +194,7 @@ namespace Invidious feedSource = feedSources[feedSourcesIndex] if m.endpoints = invalid - m.endpoints = m.node.apiDefinitions + m.endpoints = m.invidiousNode.apiDefinitions end if endpoint = m.endpoints[feedSource.endpoint] @@ -231,7 +231,7 @@ namespace Invidious function MakeRequest(feedSource as object, additionalQueryParams = invalid as object, cancellation = invalid as object) as object if m.endpoints = invalid - m.endpoints = m.node.apiDefinitions + m.endpoints = m.invidiousNode.apiDefinitions end if endpoint = m.endpoints[feedSource.endpoint] @@ -246,8 +246,10 @@ namespace Invidious request = HttpClient.Get(instance + endpoint.url) + authToken = invalid + if endpoint.authenticated = true - authToken = m.node.authToken + authToken = m.invidiousNode.authToken if authToken = invalid return { success: false @@ -264,7 +266,7 @@ namespace Invidious if queryParam.default <> invalid if IsString(queryParam.type) and queryParam.type = "#ISO3166" if queryParam.default = "GetUserCountryCode" - request.QueryParam(queryParamKey, m.node.applicationInfo@.GetUserCountryCode()) + request.QueryParam(queryParamKey, m.GetUserRegion()) else request.QueryParam(queryParamKey, queryParam.default) end if @@ -305,23 +307,18 @@ namespace Invidious response = request.Await() - if m.responseHandlers = invalid - m.responseHandlers = { - DefaultHandler: m.DefaultHandler - AuthFeedHandler: m.AuthFeedHandler - PlaylistHandler: m.PlaylistHandler - VideoInfoHandler: m.VideoInfoHandler - PlaylistInfoHandler: m.PlaylistInfoHandler - ChannelInfoHandler: m.ChannelInfoHandler - ChannelVideosHandler: m.ChannelVideosHandler - ChannelPlaylistsHandler: m.ChannelPlaylistsHandler - WatchHistoryHandler: m.WatchHistoryHandler - } + responseHandler = invalid + if IsString(endpoint.responseHandler) and m.DoesExist(endpoint.responseHandler) + responseHandler = endpoint.responseHandler + else + responseHandler = "DefaultHandler" end if - responseHandler = endpoint.responseHandler <> invalid ? m.responseHandlers[endpoint.responseHandler] : m.responseHandlers["DefaultHandler"] - - result = responseHandler(m, feedSource, response) + result = m[responseHandler]({ + feedSource: feedSource + response: response + authToken: authToken + }) if response.IsSuccess() and result <> invalid return { @@ -336,7 +333,9 @@ namespace Invidious end if end function - function DefaultHandler(m as object, feedSource as object, response as object) as object + function DefaultHandler(context as object) as object + response = context.response + if response.StatusCode() = 200 json = response.Json() return { @@ -346,7 +345,9 @@ namespace Invidious return invalid end function - function PlaylistHandler(m as object, feedSource as object, response as object) as object + function PlaylistHandler(context as object) as object + response = context.response + if response.StatusCode() = 200 json = response.Json() return { @@ -356,7 +357,9 @@ namespace Invidious return invalid end function - function ChannelVideosHandler(m as object, feedSource as object, response as object) as object + function ChannelVideosHandler(context as object) as object + response = context.response + if response.StatusCode() = 200 json = response.Json() return { @@ -367,7 +370,9 @@ namespace Invidious return invalid end function - function ChannelPlaylistsHandler(m as object, feedSource as object, response as object) as object + function ChannelPlaylistsHandler(context as object) as object + response = context.response + if response.StatusCode() = 200 json = response.Json() return { @@ -378,7 +383,10 @@ namespace Invidious return invalid end function - function VideoInfoHandler(m as object, feedSource as object, response as object) as object + function VideoInfoHandler(context as object) as object + response = context.response + feedSource = context.feedSource + statusCode = response.StatusCode() if statusCode >= 500 ' In some cases, such as a video became private, or a live stream ended, @@ -406,7 +414,9 @@ namespace Invidious return invalid end function - function PlaylistInfoHandler(m as object, feedSource as object, response as object) as object + function PlaylistInfoHandler(context as object) as object + response = context.response + if response.StatusCode() = 200 json = response.Json() json.type = "playlist" @@ -417,7 +427,9 @@ namespace Invidious return invalid end function - function ChannelInfoHandler(m as object, feedSource as object, response as object) as object + function ChannelInfoHandler(context as object) as object + response = context.response + if response.StatusCode() = 200 json = response.Json() json.type = "channel" @@ -428,8 +440,11 @@ namespace Invidious return invalid end function - function AuthFeedHandler(m as object, feedSource as object, response as object) as object - m.DeleteExpiredToken(response) + function AuthFeedHandler(context as object) as object + response = context.response + authToken = context.authToken + + m.DeleteExpiredToken(response, authToken) if response.StatusCode() <> 200 return invalid @@ -455,8 +470,11 @@ namespace Invidious } end function - function WatchHistoryHandler(m as object, feedSource as object, response as object) as object - m.DeleteExpiredToken(response) + function WatchHistoryHandler(context as object) as object + response = context.response + authToken = context.authToken + + m.DeleteExpiredToken(response, authToken) if response.StatusCode() <> 200 return invalid @@ -480,53 +498,19 @@ namespace Invidious } end function - function DeleteExpiredToken(response as object) - if response.StatusCode() = 403 - LogWarn(`Invidious instance responded with 403: ${response.Text()}`) - LogWarn("Deleting Invidious token...") - m.DeleteAuthToken() + function DeleteExpiredToken(response as object, authToken as object) as void + if response.StatusCode() <> 403 + return end if - end function - function GetAuthToken() as object - tokenPayload = RegistryUtils.Read(RegistryUtils.INVIDIOUS_TOKEN) - if tokenPayload = invalid - return invalid + LogWarn(`Invidious instance responded with 403: ${response.Text()}`) + if not IsAssociativeArray(authToken) or not IsString(authToken.token) + LogWarn("No valid token to delete") + return end if - authToken = ParseJson(tokenPayload) - if authToken = invalid or authToken.instance = invalid or authToken.token = invalid - RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN) - return invalid - end if - if not m.VerifyTokenScope(authToken.token) - ' Right now we're probably in a UI thread, and we can't unregister the token - ' Without a Task - AsyncTask.Start(Tasks.InvidiousUnregisterTokenTask, { - invidious: m.node - authToken: authToken - }) - RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN) - message = `It looks like you are logged in to Invidious, but your access token does not have the required permissions. -For that reason, we have logged you out. Please log in again. -This can happen when Playlet is updated with new features. -We apologize for the inconvenience.` - DialogUtils.ShowDialog(message, "User logged out") - return invalid - end if - return authToken - end function - function SetAuthToken(token as string, instance as string, username as dynamic) - obj = { - token: token - instance: instance - username: username - } - - json = FormatJson(obj) - RegistryUtils.Write(RegistryUtils.INVIDIOUS_TOKEN, json) - - m.node.authToken = obj + LogInfo("Deleting Invidious token...") + m.invidiousNode.profiles@.LogoutWithAccessToken(authToken.token) end function function VerifyTokenScope(token as string) as boolean @@ -550,30 +534,14 @@ We apologize for the inconvenience.` return validScopes end function - function DeleteAuthToken() - m.node.authToken = invalid - RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN) - end function - - function Logout() as boolean - authToken = m.node.authToken - if authToken = invalid - return false - end if - - m.UnregisterToken(authToken) - m.DeleteAuthToken() - return true - end function - - function UnregisterToken(authToken as object) as void + function UnregisterToken(authToken as object) as object url = `${authToken.instance}${Invidious.AUTH_TOKENS_UNREGISTER}` request = HttpClient.Post(url, authToken.token) request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Header("Content-Type", "application/json") - request.Await() + return request.Await() end function function GetAuthorizeTokenLink() as dynamic @@ -581,7 +549,7 @@ We apologize for the inconvenience.` ' Make sure the host is not on https, because https cannot redirect to http, which is our local server invidiousHost = instance.Replace("https://", "http://") - address = m.node.webServer@.GetServerAddress() + address = m.invidiousNode.webServer@.GetServerAddress() if address = invalid return invalid end if @@ -594,7 +562,7 @@ We apologize for the inconvenience.` end function function GetSubscriptions(cancellation = invalid as object) as object - authToken = m.node.authToken + authToken = m.invidiousNode.authToken if authToken = invalid return invalid end if @@ -608,7 +576,7 @@ We apologize for the inconvenience.` end function function Subscribe(channelId as string, cancellation = invalid as object) as object - authToken = m.node.authToken + authToken = m.invidiousNode.authToken if authToken = invalid return invalid end if @@ -622,7 +590,7 @@ We apologize for the inconvenience.` end function function Unsubscribe(channelId as string, cancellation = invalid as object) as object - authToken = m.node.authToken + authToken = m.invidiousNode.authToken if authToken = invalid return invalid end if diff --git a/playlet-lib/src/components/Services/Invidious/InvidiousUnregisterTokenTask.bs b/playlet-lib/src/components/Services/Invidious/InvidiousUnregisterTokenTask.bs deleted file mode 100644 index 9322e594..00000000 --- a/playlet-lib/src/components/Services/Invidious/InvidiousUnregisterTokenTask.bs +++ /dev/null @@ -1,12 +0,0 @@ -import "InvidiousService.bs" - -@asynctask -function InvidiousUnregisterTokenTask(input as object) as object - invidiousNode = input.invidious - authToken = input.authToken - - service = new Invidious.InvidiousService(invidiousNode) - service.UnregisterToken(authToken) - - return invalid -end function diff --git a/playlet-lib/src/components/Services/Profiles/Profiles.bs b/playlet-lib/src/components/Services/Profiles/Profiles.bs new file mode 100644 index 00000000..0d1106b0 --- /dev/null +++ b/playlet-lib/src/components/Services/Profiles/Profiles.bs @@ -0,0 +1,331 @@ +import "pkg:/source/AsyncTask/AsyncTask.bs" +import "pkg:/source/AsyncTask/Tasks.bs" +import "pkg:/source/utils/ArrayUtils.bs" +import "pkg:/source/utils/ColorUtils.bs" +import "pkg:/source/utils/CryptoUtils.bs" +import "pkg:/source/utils/Logging.bs" +import "pkg:/source/utils/RegistryUtils.bs" +import "pkg:/source/utils/StringUtils.bs" + +' TODO:P1 add the ability to change color of profiles +function Init() + m.disableSavingToRegistry = false + content = m.top.findNode("ProfilesContent") + m.top.content = content + m.profilesContent = content.getChild(0) +end function + +function OnNodeReady() + LoadProfilesFromRegistry() +end function + +function LoadProfilesFromRegistry() + LogInfo("Loading profiles from registry...") + + ' Step 1: Load user profiles from registry + userProfiles = RegistryUtils.Read(RegistryUtils.USER_PROFILES) + + if userProfiles = invalid + userProfiles = { + profiles: [] + currentProfile: invalid + } + else + userProfiles = ParseJson(userProfiles) + end if + + ' Step 2: Migrate existing profiles to new format (if needed) + isDirty = MigrateExistingProfiles(userProfiles) + + ' Step 3: Save user preferences (if needed) + if isDirty + SaveUserProfilesToRegistry() + end if + + ' Step 4: Load user profiles into content nodes + profileNodes = [] + for each profile in userProfiles.profiles + profileNode = CreateObject("roSGNode", "ProfileContentNode") + profileNode.id = profile.id + profileNode.type = profile.type + profileNode.username = profile.username + profileNode.serverUrl = profile.serverUrl + profileNode.accessToken = profile.accessToken + profileNode.color = profile.color + + profileNodes.Push(profileNode) + end for + + m.profilesContent.insertChildren(profileNodes, 0) + + if not StringUtils.IsNullOrEmpty(userProfiles.currentProfile) + for each profileNode in profileNodes + if profileNode.id = userProfiles.currentProfile + ' Setting current profile will also save the profiles to registry + ' but we just saved the profiles + m.disableSavingToRegistry = true + SetCurrentProfile(profileNode) + m.disableSavingToRegistry = false + exit for + end if + end for + end if + + if profileNodes.Count() > 0 + AsyncTask.Start(Tasks.ProfilesVerifyTokensTask, { + profiles: m.top + invidious: m.invidious + profileNodes: profileNodes + }) + end if +end function + +function MigrateExistingProfiles(userProfiles as object) as boolean + tokenPayload = RegistryUtils.Read(RegistryUtils.INVIDIOUS_TOKEN) + if tokenPayload = invalid + return false + end if + + authToken = ParseJson(tokenPayload) + RegistryUtils.Delete(RegistryUtils.INVIDIOUS_TOKEN) + + if authToken = invalid or authToken.instance = invalid or authToken.token = invalid or authToken.username = invalid + return false + end if + + id = CreateProfileId(authToken.username, authToken.instance) + for each profile in userProfiles.profiles + if profile.id = id + return false + end if + end for + + profile = { + "id": id + "type": "invidious" + "username": authToken.username + "serverUrl": authToken.instance + "accessToken": authToken.token + "color": ColorUtils.RandomSoftColorHex() + } + + userProfiles.profiles.Unshift(profile) + if StringUtils.IsNullOrEmpty(userProfiles["currentProfile"]) + userProfiles["currentProfile"] = profile.id + end if + + return true +end function + +function SaveUserProfilesToRegistry() as void + if m.disableSavingToRegistry + return + end if + + userProfiles = GetProfilesDto(true) + + userProfiles.__version = m.top.__version + RegistryUtils.Write(RegistryUtils.USER_PROFILES, FormatJson(userProfiles)) +end function + +function GetProfilesDto(includeAccessToken as boolean) as object + userProfiles = { + "profiles": [] + "currentProfile": invalid + } + + profileNodes = m.profilesContent.getChildren(-1, 0) + + for each profileNode in profileNodes + if profileNode.type = "login" + continue for + end if + + color = profileNode.color + if IsInt(color) + ' Use hex color for web app + color = ColorUtils.IntToHex(color) + end if + + profile = { + "id": profileNode.id + "type": profileNode.type + "username": profileNode.username + "serverUrl": profileNode.serverUrl + "color": color + } + + if includeAccessToken + profile["accessToken"] = profileNode.accessToken + end if + + userProfiles.profiles.Push(profile) + end for + + currentProfile = m.top.currentProfile + if currentProfile <> invalid + userProfiles["currentProfile"] = currentProfile.id + end if + + return userProfiles +end function + +function LoginWithProfile(newProfile as object) + isNewProfile = true + if StringUtils.IsNullOrEmpty(newProfile.id) + newProfile.id = CreateProfileId(newProfile.username, newProfile.serverUrl) + end if + + existingProfile = invalid + profiles = m.profilesContent.getChildren(-1, 0) + for each profile in profiles + if profile.id = newProfile.id + existingProfile = profile + isNewProfile = false + exit for + end if + end for + + if not isNewProfile + ' Refresh token of existing profile + existingProfile.accessToken = newProfile.accessToken + newProfile = existingProfile + end if + + if isNewProfile + newProfile.color = ColorUtils.RandomSoftColorHex() + m.profilesContent.insertChild(newProfile, 0) + end if + SetCurrentProfile(newProfile) +end function + +function LogoutWithProfile(profile as object) as void + if profile = invalid + return + end if + + profile = m.profilesContent.findNode(profile.id) + if profile = invalid + return + end if + + m.profilesContent.removeChild(profile) + currentProfile = m.top.currentProfile + if currentProfile <> invalid and currentProfile.id = profile.id + SetCurrentProfile(invalid) + else + RefreshActiveProfileState(currentProfile) + end if + + m.top.onProfileLogout = true + + AsyncTask.Start(Tasks.ProfilesInvidiousUnregisterTokenTask, { + profiles: m.top + invidious: m.invidious + profileNodes: [profile] + }) +end function + +function LogoutWithProfiles(profiles as object) as void + if profiles = invalid or profiles.Count() = 0 + return + end if + + currentProfile = m.top.currentProfile + logoutFromCurrentProfile = false + onProfileLogout = false + for each profile in profiles + profileNode = m.profilesContent.findNode(profile.id) + if profileNode = invalid + continue for + end if + + m.profilesContent.removeChild(profileNode) + onProfileLogout = true + if currentProfile <> invalid and currentProfile.id = profile.id + logoutFromCurrentProfile = true + end if + end for + + if logoutFromCurrentProfile + SetCurrentProfile(invalid) + else + RefreshActiveProfileState(currentProfile) + end if + + if onProfileLogout + m.top.onProfileLogout = true + end if + + AsyncTask.Start(Tasks.ProfilesInvidiousUnregisterTokenTask, { + profiles: m.top + invidious: m.invidious + profileNodes: profiles + }) +end function + +function LogoutWithAccessToken(accessToken as dynamic) as void + if StringUtils.IsNullOrEmpty(accessToken) + return + end if + + ' We are not going to invalidate the token on the server + ' because we are likely dealing with an invalid token + ' in the first place. All we need to do is remove the + ' profile from the list of profiles. + + allProfiles = m.profilesContent.getChildren(-1, 0) + for each profile in allProfiles + if profile.accessToken = accessToken + m.profilesContent.removeChild(profile) + currentProfile = m.top.currentProfile + if currentProfile <> invalid and currentProfile.id = profile.id + SetCurrentProfile(invalid) + else + RefreshActiveProfileState(currentProfile) + end if + m.top.onProfileLogout = true + exit for + end if + end for +end function + +function SetCurrentProfile(newActiveProfile as object) as void + if newActiveProfile = invalid + RefreshActiveProfileState(invalid) + m.top.currentProfile = invalid + m.invidious.authToken = invalid + LogInfo("Current profile set to ") + SaveUserProfilesToRegistry() + return + end if + + RefreshActiveProfileState(newActiveProfile) + + m.top.currentProfile = newActiveProfile + m.invidious.authToken = { + token: newActiveProfile.accessToken + instance: newActiveProfile.serverUrl + username: newActiveProfile.username + } + LogInfo("Current profile set to", newActiveProfile.username, "@", newActiveProfile.serverUrl) + SaveUserProfilesToRegistry() +end function + +function RefreshActiveProfileState(activeProfile as object) as void + allProfiles = m.profilesContent.getChildren(-1, 0) + if activeProfile = invalid + for each profile in allProfiles + profile.isSelected = false + end for + return + end if + + for each profile in allProfiles + profile.isSelected = profile.id = activeProfile.id + end for +end function + +function CreateProfileId(username as string, serverUrl as string) as string + return "v1:" + CryptoUtils.GetMd5(username + serverUrl) +end function diff --git a/playlet-lib/src/components/Services/Profiles/Profiles.xml b/playlet-lib/src/components/Services/Profiles/Profiles.xml new file mode 100644 index 00000000..664c7fbc --- /dev/null +++ b/playlet-lib/src/components/Services/Profiles/Profiles.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/playlet-lib/src/components/Services/Profiles/ProfilesInvidiousUnregisterTokenTask.bs b/playlet-lib/src/components/Services/Profiles/ProfilesInvidiousUnregisterTokenTask.bs new file mode 100644 index 00000000..709dcc82 --- /dev/null +++ b/playlet-lib/src/components/Services/Profiles/ProfilesInvidiousUnregisterTokenTask.bs @@ -0,0 +1,22 @@ +import "pkg:/components/Services/Invidious/InvidiousService.bs" + +@asynctask +function ProfilesInvidiousUnregisterTokenTask(input as object) as object + profileContentNodes = input.profileNodes + invidiousNode = input.invidious + + service = new Invidious.InvidiousService(invidiousNode) + + for each profileNode in profileContentNodes + authToken = { + instance: profileNode.serverUrl + token: profileNode.accessToken + } + response = service.UnregisterToken(authToken) + if not response.IsSuccess() + LogWarn(`Failed to unregister token: ${response.ErrorMessage()}`) + end if + end for + + return invalid +end function diff --git a/playlet-lib/src/components/Services/Profiles/ProfilesVerifyTokensTask.bs b/playlet-lib/src/components/Services/Profiles/ProfilesVerifyTokensTask.bs new file mode 100644 index 00000000..608b5f3c --- /dev/null +++ b/playlet-lib/src/components/Services/Profiles/ProfilesVerifyTokensTask.bs @@ -0,0 +1,38 @@ +import "pkg:/components/Services/Invidious/InvidiousService.bs" + +@asynctask +function ProfilesVerifyTokensTask(input as object) as object + profilesNode = input.profiles + invidiousNode = input.invidious + profileContentNodes = input.profileNodes + + service = new Invidious.InvidiousService(invidiousNode) + invalidProfiles = [] + + for each profileNode in profileContentNodes + if not service.VerifyTokenScope(profileNode.accessToken) + invalidProfiles.push(profileNode) + end if + end for + + if invalidProfiles.Count() = 0 + return invalid + end if + + profilesNode@.LogoutWithProfiles(invalidProfiles) + + profileNames = [] + for each profileNode in invalidProfiles + profileNames.push(profileNode.username) + end for + profileNames = profileNames.join(", ") + + message = `It looks like you are logged in to Invidious, but do not have the required permissions. +For that reason, we have logged you out from the following profiles: ${profileNames} +Please log in again. +This can happen when Playlet is updated with new features. +We apologize for the inconvenience.` + DialogUtils.ShowDialog(message, "User logged out") + + return invalid +end function diff --git a/playlet-lib/src/components/VideoFeed/VideoRowCell/ActionRowCell.bs b/playlet-lib/src/components/VideoFeed/VideoRowCell/ActionRowCell.bs deleted file mode 100644 index f8066175..00000000 --- a/playlet-lib/src/components/VideoFeed/VideoRowCell/ActionRowCell.bs +++ /dev/null @@ -1,13 +0,0 @@ -function Init() - m.label = m.top.findNode("label") -end function - -function OnContentSet() as void - content = m.top.itemContent - - if content = invalid - return - end if - - m.label.text = content.title -end function diff --git a/playlet-lib/src/components/VideoFeed/VideoRowCell/ActionRowCell.xml b/playlet-lib/src/components/VideoFeed/VideoRowCell/ActionRowCell.xml deleted file mode 100644 index 5b693f73..00000000 --- a/playlet-lib/src/components/VideoFeed/VideoRowCell/ActionRowCell.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/playlet-lib/src/components/VideoFeed/VideoRowCell/RowCell.bs b/playlet-lib/src/components/VideoFeed/VideoRowCell/RowCell.bs index 64a3b184..9d790a48 100644 --- a/playlet-lib/src/components/VideoFeed/VideoRowCell/RowCell.bs +++ b/playlet-lib/src/components/VideoFeed/VideoRowCell/RowCell.bs @@ -8,7 +8,6 @@ function OnContentSet() as void "playlist": "playlistRowCellVisible" "channel": "channelRowCellVisible" "loading": "loadingRowCellVisible" - "action": "actionRowCellVisible" } contentProperties = { @@ -16,7 +15,6 @@ function OnContentSet() as void "playlist": "playlistRowCellItemContent" "channel": "channelRowCellItemContent" "loading": "loadingRowCellItemContent" - "action": "actionRowCellItemContent" } if content = invalid diff --git a/playlet-lib/src/components/VideoFeed/VideoRowCell/RowCell.xml b/playlet-lib/src/components/VideoFeed/VideoRowCell/RowCell.xml index 55248595..9e753d64 100644 --- a/playlet-lib/src/components/VideoFeed/VideoRowCell/RowCell.xml +++ b/playlet-lib/src/components/VideoFeed/VideoRowCell/RowCell.xml @@ -8,13 +8,11 @@ - - @@ -23,6 +21,5 @@ - \ No newline at end of file diff --git a/playlet-lib/src/components/VideoFeed/VideoRowList.bs b/playlet-lib/src/components/VideoFeed/VideoRowList.bs index 6e62f248..4dca10df 100644 --- a/playlet-lib/src/components/VideoFeed/VideoRowList.bs +++ b/playlet-lib/src/components/VideoFeed/VideoRowList.bs @@ -108,12 +108,8 @@ function OnRowItemSelected(index as object) as void authorId = rowItem.authorId LogInfo("Open channel: " + authorId) OpenChannel(rowItem) - else if rowItem.type = "action" - if rowItem.action = "LoginDialog" - dialog = CreateObject("roSGNode", "LoginDialog") - dialog@.BindNode() - m.top.getScene().dialog = dialog - end if + else + LogWarn("Unknown row item type:", rowItem.type) end if end function diff --git a/playlet-lib/src/components/VideoFeed/VideoRowListRowContentTask.bs b/playlet-lib/src/components/VideoFeed/VideoRowListRowContentTask.bs index feb23164..21142b76 100644 --- a/playlet-lib/src/components/VideoFeed/VideoRowListRowContentTask.bs +++ b/playlet-lib/src/components/VideoFeed/VideoRowListRowContentTask.bs @@ -2,6 +2,7 @@ import "pkg:/components/Dialog/DialogUtils.bs" import "pkg:/components/Services/Invidious/InvidiousService.bs" import "pkg:/components/Services/Invidious/InvidiousToContentNode.bs" +' TODO:P1 handle case where all feedSources are empty @asynctask function VideoRowListRowContentTask(input as object) as object try @@ -59,17 +60,13 @@ function VideoRowListRowContentTask(input as object) as object if not response.success if response.error = Invidious.ERROR_NOT_AUTHENTICATED - RemovePlaceHolderItems(feedContentNode) - actionNode = CreateObject("roSGNode", "ActionContentNode") - actionNode.title = `Login to view ${feedSource.title}` - actionNode.action = "LoginDialog" - - feedSource.state.loadState = FeedLoadState.Loaded - feedSources[feedSourcesIndex] = feedSource - feedContentNode.feedSources = feedSources - - feedContentNode.appendChild(actionNode) - feedContentNode.loadState = FeedLoadState.Loaded + if feedSources.Count() = 1 + parent = feedContentNode.getParent() + parent.removeChild(feedContentNode) + return { + success: true + } + end if continue while end if diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InvidiousRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InvidiousRouter.bs index 3637e0cf..6b1905f5 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InvidiousRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/InvidiousRouter.bs @@ -8,7 +8,9 @@ namespace Http function new(server as object) super() - m.invidiousNode = server.task.invidious + task = server.task + m.profilesNode = task.profiles + m.invidiousNode = task.invidious m.invidiousService = new Invidious.InvidiousService(m.invidiousNode) end function @@ -21,16 +23,6 @@ namespace Http return true end function - @get("/invidious/logout") - function Logout(context as object) as boolean - response = context.response - - m.invidiousService.Logout() - - response.Default(204, "OK") - return true - end function - @get("/invidious/token_callback") function OnTokenReceived(context as object) as boolean request = context.request @@ -42,7 +34,12 @@ namespace Http username = request.query["username"].DecodeUriComponent().DecodeUriComponent() referer = request.query["ref"].DecodeUriComponent() - m.invidiousNode@.SetAuthToken(token, referer, username) + profile = CreateObject("roSGNode", "ProfileContentNode") + profile.username = username + profile.accessToken = token + profile.serverUrl = referer + + m.profilesNode@.LoginWithProfile(profile) end if response.Redirect("/") return true diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/ProfilesRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/ProfilesRouter.bs new file mode 100644 index 00000000..9cb64ac9 --- /dev/null +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/ProfilesRouter.bs @@ -0,0 +1,73 @@ +namespace Http + + class ProfilesRouter extends HttpRouter + + function new(server as object) + super() + + m.profilesNode = server.task.profiles + m.profilesContent = m.profilesNode.content.getChild(0) + end function + + @get("/api/profiles") + function GetProfiles(context as object) as boolean + response = context.response + + profiles = m.profilesNode@.GetProfilesDto(false) + response.Json(profiles) + return true + end function + + @post("/api/profiles/activate") + function ActivateProfile(context as object) as boolean + request = context.request + response = context.response + + payload = request.Json() + if payload = invalid + response.Default(400, `Invalid JSON payload`) + return true + end if + + id = payload.id + if StringUtils.IsNullOrEmpty(id) + response.Default(400, "Missing profile id") + return true + end if + + profile = m.profilesContent.findNode(id) + if profile = invalid + response.Default(404, `Profile id "${id}" not found`) + return true + end if + + m.profilesNode@.SetCurrentProfile(profile) + response.Default(200, "Profile updated") + return true + end function + + @delete("/api/profiles") + function Logout(context as object) as boolean + request = context.request + response = context.response + + id = request.query.id + if StringUtils.IsNullOrEmpty(id) + response.Default(400, "Missing profile id") + return true + end if + + profile = m.profilesContent.findNode(id) + if profile = invalid + response.Default(404, `Profile id "${id}" not found`) + return true + end if + + m.profilesNode@.LogoutWithProfile(profile) + response.Default(200, "Profile logged out") + return true + end function + + end class + +end namespace diff --git a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/StateApiRouter.bs b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/StateApiRouter.bs index c3f5d5d3..281a5531 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/Middleware/StateApiRouter.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/Middleware/StateApiRouter.bs @@ -11,6 +11,7 @@ namespace Http m.applicationInfoNode = task.applicationInfo m.invidiousNode = task.invidious m.preferencesNode = task.preferences + m.profilesNode = task.profiles end function @get("/api/state") @@ -18,7 +19,7 @@ namespace Http request = context.request response = context.response - keys = ["app", "device", "invidious", "preferences"] + keys = ["app", "device", "invidious", "preferences", "profiles"] if request.query.DoesExist("key") keys = request.query["key"] @@ -27,9 +28,14 @@ namespace Http end if end if + keysDict = {} + for each key in keys + keysDict[key] = true + end for + state = {} - if ArrayUtils.IndexOfString(keys, "app") <> -1 + if keysDict["app"] = true appInfo = m.applicationInfoNode@.GetAppInfo() if appInfo.lib_version_latest = "N/A" @@ -46,25 +52,25 @@ namespace Http state["app"] = appInfo end if - if ArrayUtils.IndexOfString(keys, "device") <> -1 + if keysDict["device"] = true state["device"] = m.applicationInfoNode@.GetDeviceInfo() end if - if ArrayUtils.IndexOfString(keys, "invidious") <> -1 - authToken = m.invidiousNode.authToken + if keysDict["invidious"] = true state["invidious"] = { current_instance: m.invidiousNode@.GetCurrentInstance() auth_url: m.invidiousNode@.GetAuthorizeTokenLink() - logged_in: authToken <> invalid - logged_in_instance: authToken <> invalid ? authToken.instance : invalid - logged_in_username: authToken <> invalid ? authToken.username : invalid } end if - if ArrayUtils.IndexOfString(keys, "preferences") <> -1 + if keysDict["preferences"] = true state["preferences"] = m.preferencesNode@.GetUserPreferences() end if + if keysDict["profiles"] = true + state["profiles"] = m.profilesNode@.GetProfilesDto(false) + end if + response.Json(state) return true end function diff --git a/playlet-lib/src/components/Web/PlayletWebServer/PlayletWebServer.bs b/playlet-lib/src/components/Web/PlayletWebServer/PlayletWebServer.bs index bc3bd9b8..4d5d2bbe 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/PlayletWebServer.bs +++ b/playlet-lib/src/components/Web/PlayletWebServer/PlayletWebServer.bs @@ -7,6 +7,7 @@ import "pkg:/components/Web/PlayletWebServer/Middleware/HomeRouter.bs" import "pkg:/components/Web/PlayletWebServer/Middleware/InvidiousRouter.bs" import "pkg:/components/Web/PlayletWebServer/Middleware/PlayletLibUrlsRouter.bs" import "pkg:/components/Web/PlayletWebServer/Middleware/PreferencesRouter.bs" +import "pkg:/components/Web/PlayletWebServer/Middleware/ProfilesRouter.bs" import "pkg:/components/Web/PlayletWebServer/Middleware/RegistryRouter.bs" import "pkg:/components/Web/PlayletWebServer/Middleware/SearchHistoryRouter.bs" import "pkg:/components/Web/PlayletWebServer/Middleware/StateApiRouter.bs" @@ -41,6 +42,7 @@ function SetupRoutes(server as object) server.UseRouter(new Http.DashRouter(server)) server.UseRouter(new Http.PreferencesRouter(server)) server.UseRouter(new Http.InvidiousRouter(server)) + server.UseRouter(new Http.ProfilesRouter(server)) server.UseRouter(new Http.VideoQueueRouter(server)) server.UseRouter(new Http.BookmarksRouter(server)) server.UseRouter(new Http.HomeLayoutRouter(server)) diff --git a/playlet-lib/src/components/Web/PlayletWebServer/PlayletWebServer.xml b/playlet-lib/src/components/Web/PlayletWebServer/PlayletWebServer.xml index 1aac9059..d702117d 100644 --- a/playlet-lib/src/components/Web/PlayletWebServer/PlayletWebServer.xml +++ b/playlet-lib/src/components/Web/PlayletWebServer/PlayletWebServer.xml @@ -3,6 +3,7 @@ + diff --git a/playlet-lib/src/images/icons/crown.png b/playlet-lib/src/images/icons/crown.png new file mode 100644 index 00000000..ed2e829d Binary files /dev/null and b/playlet-lib/src/images/icons/crown.png differ diff --git a/playlet-lib/src/images/icons/crown.svg b/playlet-lib/src/images/icons/crown.svg new file mode 100644 index 00000000..3b4c7d30 --- /dev/null +++ b/playlet-lib/src/images/icons/crown.svg @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/playlet-lib/src/images/icons/crown.svg.meta.json5 b/playlet-lib/src/images/icons/crown.svg.meta.json5 new file mode 100644 index 00000000..4be403a7 --- /dev/null +++ b/playlet-lib/src/images/icons/crown.svg.meta.json5 @@ -0,0 +1,11 @@ +{ + inputHash: 'cb60a03d94432dc8c59e759b0b964fe0', + outputs: [ + { + outputFilePath: 'images/icons/crown.png', + outputHash: 'ae78dc598a50ae81eb18c0167d783121', + width: 80, + height: 80, + }, + ], +} \ No newline at end of file diff --git a/playlet-lib/src/images/icons/user-200.png b/playlet-lib/src/images/icons/user-200.png new file mode 100644 index 00000000..19c98a44 Binary files /dev/null and b/playlet-lib/src/images/icons/user-200.png differ diff --git a/playlet-lib/src/images/icons/user.png b/playlet-lib/src/images/icons/user.png index 27bd984d..b9db57a1 100644 Binary files a/playlet-lib/src/images/icons/user.png and b/playlet-lib/src/images/icons/user.png differ diff --git a/playlet-lib/src/images/icons/user.svg b/playlet-lib/src/images/icons/user.svg index d1a7e718..4246ec2d 100644 --- a/playlet-lib/src/images/icons/user.svg +++ b/playlet-lib/src/images/icons/user.svg @@ -1 +1,12 @@ - \ No newline at end of file + + + + + + + + + + + + \ No newline at end of file diff --git a/playlet-lib/src/images/icons/user.svg.meta.json5 b/playlet-lib/src/images/icons/user.svg.meta.json5 index d516493f..b2421269 100644 --- a/playlet-lib/src/images/icons/user.svg.meta.json5 +++ b/playlet-lib/src/images/icons/user.svg.meta.json5 @@ -1,11 +1,17 @@ { - inputHash: '9345dbe14b95ef513b0a5919226cd277', + inputHash: 'd05489dbec5e0e5b3b6889b41b033c38', outputs: [ { outputFilePath: 'images/icons/user.png', - outputHash: '5cda73aaa2eeaee05dd0c1705129eed2', - width: 80, - height: 80, + outputHash: '0c541921e88abe409a9ca047a6661683', + width: 64, + height: 64, + }, + { + outputFilePath: 'images/icons/user-200.png', + outputHash: '499cdc27460b66a5cef811620138c549', + width: 200, + height: 200, }, ], } \ No newline at end of file diff --git a/playlet-lib/src/source/utils/ArrayUtils.bs b/playlet-lib/src/source/utils/ArrayUtils.bs index cf0a872d..456c6f40 100644 --- a/playlet-lib/src/source/utils/ArrayUtils.bs +++ b/playlet-lib/src/source/utils/ArrayUtils.bs @@ -14,6 +14,18 @@ namespace ArrayUtils return -1 end function + function IndexOfNode(array as object, value as dynamic) as integer + if not IsNode(value) + return -1 + end if + for i = 0 to array.Count() - 1 + if value.isSameNode(array[i]) + return i + end if + end for + return -1 + end function + function Insert(array as object, value as dynamic, index as integer) as void if index = 0 array.Unshift(value) diff --git a/playlet-lib/src/source/utils/ColorUtils.bs b/playlet-lib/src/source/utils/ColorUtils.bs index 626eac51..63b69f65 100644 --- a/playlet-lib/src/source/utils/ColorUtils.bs +++ b/playlet-lib/src/source/utils/ColorUtils.bs @@ -7,25 +7,16 @@ namespace ColorUtils color = color.mid(1) end if - value = Val(color.mid(0, 2), 16) * 16777216 + Val(color.mid(2, 2), 16) * 65536 + Val(color.mid(4, 2), 16) * 256 - if color.Len() = 6 - value += 255 - else if color.Len() = 8 - value += Val(color.mid(6, 2), 16) - end if - - return value + return Val(color, 16) end function function IntToHex(color as integer) as string - hexDigits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] - hexString = "#" - - for i = 7 to 0 step -1 - hexString = hexString + hexDigits[(color >> (i * 4)) and &hF] + hex = UCase(StrI(color, 16)) + length = Len(hex) + for i = 0 to 7 - length + hex = "0" + hex end for - - return hexString + return "#" + hex end function function RgbaToInt(r as integer, g as integer, b as integer, a = 255 as integer) as integer @@ -40,4 +31,8 @@ namespace ColorUtils return RgbaToInt(Rnd(100) + 100, Rnd(100) + 100, Rnd(100) + 100) end function + function RandomSoftColorHex() as string + return IntToHex(RandomSoftColorInt()) + end function + end namespace diff --git a/playlet-lib/src/source/utils/ColorUtils.spec.bs b/playlet-lib/src/source/utils/ColorUtils.spec.bs index cd0523b8..bcc75e00 100644 --- a/playlet-lib/src/source/utils/ColorUtils.spec.bs +++ b/playlet-lib/src/source/utils/ColorUtils.spec.bs @@ -6,10 +6,10 @@ namespace Tests @describe("ColorUtils") @it("Converts from hex to int") - @params("#00d400B3", 13893811) - @params("#ffff00B3", -65357) - @params("#008a5cB3", 9067699) - @params("#cc00ffB3", -872349773) + @params("#00D400B3", 13893811) + @params("#FFFF00B3", -65357) + @params("#008A5CB3", 9067699) + @params("#CC00FFB3", -872349773) function _(hexColor as string, expectedInt as integer) m.assertEqual(ColorUtils.HexToInt(hexColor), expectedInt) end function diff --git a/playlet-lib/src/source/utils/RegistryUtils.bs b/playlet-lib/src/source/utils/RegistryUtils.bs index 4a54b1c7..ffa10fad 100644 --- a/playlet-lib/src/source/utils/RegistryUtils.bs +++ b/playlet-lib/src/source/utils/RegistryUtils.bs @@ -3,17 +3,18 @@ namespace RegistryUtils const DEFAULT_SECTION = "Playlet" const USER_PREFERENCES = "user_prefs" + const USER_PROFILES = "user_profiles" const SEARCH_HISTORY = "search_history" const PLAYLET_LIB_URLS = "playlet_lib_urls" const BOOKMARKS = "bookmarks" - const INVIDIOUS_TOKEN = "invidious_token" - const LAST_LOUNGE_DATA = "last_lounge_data" ' "invidious_instances" is deprecated, but we keep for migration purposes const INVIDIOUS_INSTANCES = "invidious_instances" + ' "invidious_token" is deprecated, but we keep for migration purposes + const INVIDIOUS_TOKEN = "invidious_token" function Read(key as string, sectionName = DEFAULT_SECTION as string) as dynamic section = CreateObject("roRegistrySection", sectionName) diff --git a/playlet-web/src/lib/Api/PlayletApi.ts b/playlet-web/src/lib/Api/PlayletApi.ts index 96bdb1c3..338890b9 100644 --- a/playlet-web/src/lib/Api/PlayletApi.ts +++ b/playlet-web/src/lib/Api/PlayletApi.ts @@ -45,8 +45,17 @@ export class PlayletApi { return await response; } - static async logout() { - await fetch(`${PlayletApi.host()}/invidious/logout`); + static async getProfiles() { + const response = await fetch(`${PlayletApi.host()}/api/profiles`); + return await response.json(); + } + + static async activateProfile(profileId) { + await this.postJson(`${PlayletApi.host()}/api/profiles/activate`, { id: profileId }); + } + + static async logout(profileId) { + return await fetch(`${PlayletApi.host()}/api/profiles?id=${profileId}`, { method: "DELETE" }); } static async playVideo(args) { diff --git a/playlet-web/src/lib/NavBar.svelte b/playlet-web/src/lib/NavBar.svelte index e9527a71..81f56b33 100644 --- a/playlet-web/src/lib/NavBar.svelte +++ b/playlet-web/src/lib/NavBar.svelte @@ -1,55 +1,48 @@ @@ -65,41 +58,18 @@ - {#if loggedIn && username} + {#if currentProfile && currentProfile.username} - {username} + {currentProfile.username} {/if} - - - - - - - - {#if loggedIn} - - - Logout - - - {:else} - - - Login to Invidious - - - {/if} - - + + + + + diff --git a/playlet-web/src/lib/ProfileAvatar.svelte b/playlet-web/src/lib/ProfileAvatar.svelte new file mode 100644 index 00000000..84ffb88d --- /dev/null +++ b/playlet-web/src/lib/ProfileAvatar.svelte @@ -0,0 +1,32 @@ + + + + {#if currentProfile && currentProfile.username} + + + {currentProfile.username.substring(0, 1).toUpperCase()} + + + {:else} + + + + {/if} + diff --git a/playlet-web/src/lib/ProfilesDialog.svelte b/playlet-web/src/lib/ProfilesDialog.svelte new file mode 100644 index 00000000..091c2939 --- /dev/null +++ b/playlet-web/src/lib/ProfilesDialog.svelte @@ -0,0 +1,136 @@ + + + + + + Profiles + + {#each profiles as profile} + + + + + + + {profile.username.substring(0, 1).toUpperCase()} + + + + + + {profile.username} + + + {profile.serverUrl} + + + + + {#if profile.id !== currentProfile?.id} + activate(profile.id)} + class="btn btn-primary m-1">Activate + {/if} + logout(profile.id)} + class="btn btn-primary m-1">Logout + + + {/each} + + + + Login to Invidious + {currentInstance} + + + Close + + + + + Close + + diff --git a/playlet-web/src/lib/Screens/InfoScreen.svelte b/playlet-web/src/lib/Screens/InfoScreen.svelte index ee28226c..3333162f 100644 --- a/playlet-web/src/lib/Screens/InfoScreen.svelte +++ b/playlet-web/src/lib/Screens/InfoScreen.svelte @@ -83,6 +83,7 @@ let deviceInfo = {}; let invidiousInfo = {}; let preferencesInfo = {}; + let profilesInfo = {}; const feedbackTitle = encodeURIComponent("[Feedback] Playlet"); let githubUrlIssue = "https://github.com/iBicha/playlet/issues/new"; let mailToUrl = "mailto:brahim.hadriche@gmail.com"; @@ -92,6 +93,7 @@ deviceInfo = value.device || {}; invidiousInfo = value.invidious || {}; preferencesInfo = value.preferences || {}; + profilesInfo = value.profiles || {}; githubUrlIssue = createGithubIssueUrl(); mailToUrl = createMailToUrl(); }); @@ -118,6 +120,11 @@ ${JSON.stringify(invidiousInfo, null, 2)} #### User preferences \`\`\` ${JSON.stringify(preferencesInfo, null, 2)} +\`\`\` + +#### Profiles +\`\`\` +${JSON.stringify(profilesInfo, null, 2)} \`\`\``; } diff --git a/playlet-web/src/lib/Types.ts b/playlet-web/src/lib/Types.ts index 8da878c2..b790ea7b 100644 --- a/playlet-web/src/lib/Types.ts +++ b/playlet-web/src/lib/Types.ts @@ -9,4 +9,5 @@ export type PlayletState = { device?: any, invidious?: any, preferences?: any, + profiles?: any, } diff --git a/playlet-web/src/lib/VideoFeed/VideoListRow.svelte b/playlet-web/src/lib/VideoFeed/VideoListRow.svelte index d6a02824..968c2749 100644 --- a/playlet-web/src/lib/VideoFeed/VideoListRow.svelte +++ b/playlet-web/src/lib/VideoFeed/VideoListRow.svelte @@ -84,7 +84,7 @@ playletStateStore.subscribe((value) => { invidiousApi.instance = value?.invidious?.current_instance; invidiousApi.userCountryCode = value?.device?.user_country_code ?? "US"; - invidiousApi.isLoggedIn = value.invidious?.logged_in ?? false; + invidiousApi.isLoggedIn = !!(value.profiles?.currentProfile ?? false); loadRow(); }); diff --git a/tools/bs-plugins/type-gen-plugin.ts b/tools/bs-plugins/type-gen-plugin.ts index 610cd579..538c7ca2 100644 --- a/tools/bs-plugins/type-gen-plugin.ts +++ b/tools/bs-plugins/type-gen-plugin.ts @@ -10,6 +10,7 @@ const types = [ { name: 'AssociativeArray', interface: 'ifAssociativeArray', type: 'object', defaultValue: '{}' }, { name: 'ByteArray', interface: 'ifByteArray', type: null, defaultValue: null }, { name: 'Function', interface: 'ifFunction', type: null, defaultValue: null }, + { name: 'Node', interface: 'ifSGNodeDict', type: null, defaultValue: null }, ]; const generatedCodeHeader = `' The rest of this file is generated by the TypeGenPlugin`