mirror of https://git.sr.ht/~ashkeel/strimertul
refactor: preparatory code for re-introducing custom account for chat responses
This commit is contained in:
parent
decccb9fed
commit
07e3a00990
24
app.go
24
app.go
|
@ -241,12 +241,26 @@ func (a *App) GetKilovoltBind() string {
|
|||
return a.httpServer.Config.Get().Bind
|
||||
}
|
||||
|
||||
func (a *App) GetTwitchAuthURL() string {
|
||||
return twitch.GetAuthorizationURL(a.twitchManager.Client().API)
|
||||
func (a *App) GetTwitchAuthURL(state string) string {
|
||||
return twitch.GetAuthorizationURL(a.twitchManager.Client().API, state)
|
||||
}
|
||||
|
||||
func (a *App) GetTwitchLoggedUser() (helix.User, error) {
|
||||
return a.twitchManager.Client().GetLoggedUser()
|
||||
func (a *App) GetTwitchLoggedUser(key string) (helix.User, error) {
|
||||
userClient, err := twitch.GetUserClient(a.db, key, false)
|
||||
if err != nil {
|
||||
return helix.User{}, err
|
||||
}
|
||||
|
||||
users, err := userClient.GetUsers(&helix.UsersParams{})
|
||||
if err != nil {
|
||||
return helix.User{}, err
|
||||
}
|
||||
|
||||
if len(users.Data.Users) < 1 {
|
||||
return helix.User{}, errors.New("no users found")
|
||||
}
|
||||
|
||||
return users.Data.Users[0], nil
|
||||
}
|
||||
|
||||
func (a *App) GetLastLogs() []log.Entry {
|
||||
|
@ -341,7 +355,7 @@ func (a *App) interactiveAuth(client kv.Client, message map[string]any) bool {
|
|||
|
||||
func (a *App) showFatalError(err error, text string, fields ...any) {
|
||||
if err != nil {
|
||||
fields = append(fields, log.Error(err), slog.String("Z", string(debug.Stack())))
|
||||
fields = append(fields, log.ErrorSkip(err, 2), slog.String("Z", string(debug.Stack())))
|
||||
slog.Error(text, fields...)
|
||||
runtime.EventsEmit(a.ctx, "fatalError")
|
||||
a.isFatalError.Set(true)
|
||||
|
|
|
@ -543,7 +543,7 @@ function ProblemList() {
|
|||
};
|
||||
void kv.subscribeKey('twitch/auth-keys', onKeyChange);
|
||||
|
||||
const url = await GetTwitchAuthURL();
|
||||
const url = await GetTwitchAuthURL('stream');
|
||||
BrowserOpenURL(url);
|
||||
};
|
||||
|
||||
|
|
|
@ -450,15 +450,13 @@ function TwitchEventsStep() {
|
|||
const { t } = useTranslation();
|
||||
const [userStatus, setUserStatus] = useState<helix.User | SyncError>(null);
|
||||
const [twitchConfig, setTwitchConfig] = useModule(modules.twitchConfig);
|
||||
const [botConfig, setBotConfig] = useModule(modules.twitchChatConfig);
|
||||
const [uiConfig, setUiConfig] = useModule(modules.uiConfig);
|
||||
const [authKeys, setAuthKeys] = useState<TwitchCredentials>(null);
|
||||
const kv = useSelector((state: RootState) => state.api.client);
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const getUserInfo = async () => {
|
||||
try {
|
||||
const res = await GetTwitchLoggedUser();
|
||||
const res = await GetTwitchLoggedUser('twitch/auth-keys');
|
||||
setUserStatus(res);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
|
@ -467,7 +465,7 @@ function TwitchEventsStep() {
|
|||
};
|
||||
|
||||
const startAuthFlow = async () => {
|
||||
const url = await GetTwitchAuthURL();
|
||||
const url = await GetTwitchAuthURL('stream');
|
||||
BrowserOpenURL(url);
|
||||
};
|
||||
|
||||
|
@ -477,16 +475,6 @@ function TwitchEventsStep() {
|
|||
await dispatch(
|
||||
setTwitchConfig({
|
||||
...twitchConfig,
|
||||
enable_bot: true,
|
||||
}),
|
||||
);
|
||||
await dispatch(
|
||||
setBotConfig({
|
||||
...botConfig,
|
||||
username: userStatus.login,
|
||||
oauth: `oauth:${authKeys.access_token}`,
|
||||
channel: userStatus.login,
|
||||
chat_history: 5,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
@ -503,17 +491,10 @@ function TwitchEventsStep() {
|
|||
// Get user info
|
||||
void getUserInfo();
|
||||
|
||||
const onKeyChange = (newValue: string) => {
|
||||
setAuthKeys(JSON.parse(newValue) as TwitchCredentials);
|
||||
const onKeyChange = () => {
|
||||
void getUserInfo();
|
||||
};
|
||||
|
||||
void kv.getKey('twitch/auth-keys').then((auth) => {
|
||||
if (auth) {
|
||||
setAuthKeys(JSON.parse(auth) as TwitchCredentials);
|
||||
}
|
||||
});
|
||||
|
||||
void kv.subscribeKey('twitch/auth-keys', onKeyChange);
|
||||
return () => {
|
||||
void kv.unsubscribeKey('twitch/auth-keys', onKeyChange);
|
||||
|
|
|
@ -53,54 +53,6 @@ const Step = styled('li', {
|
|||
},
|
||||
});
|
||||
|
||||
function TwitchChatSettings() {
|
||||
const [chatConfig, setChatConfig, loadStatus] = useModule(
|
||||
modules.twitchChatConfig,
|
||||
);
|
||||
const [twitchConfig, setTwitchConfig] = useModule(modules.twitchConfig);
|
||||
const status = useStatus(loadStatus.save);
|
||||
const dispatch = useAppDispatch();
|
||||
const { t } = useTranslation();
|
||||
const disabled = status?.type === 'pending';
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={(ev) => {
|
||||
void dispatch(setTwitchConfig(twitchConfig));
|
||||
void dispatch(setChatConfig(chatConfig));
|
||||
ev.preventDefault();
|
||||
}}
|
||||
>
|
||||
<SectionHeader>
|
||||
{t('pages.twitch-settings.bot-chat-header')}
|
||||
</SectionHeader>
|
||||
<Field size="fullWidth">
|
||||
<Label htmlFor="bot-chat-history">
|
||||
{t('pages.twitch-settings.bot-chat-cooldown-tip')}
|
||||
</Label>
|
||||
<InputBox
|
||||
type="number"
|
||||
id="bot-chat-history"
|
||||
required={true}
|
||||
disabled={disabled}
|
||||
defaultValue={
|
||||
chatConfig ? chatConfig.command_cooldown ?? 2 : undefined
|
||||
}
|
||||
onChange={(ev) =>
|
||||
dispatch(
|
||||
apiReducer.actions.twitchChatConfigChanged({
|
||||
...chatConfig,
|
||||
command_cooldown: parseInt(ev.target.value, 10),
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<SaveButton status={status} />
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
type TestResult = { open: boolean; error?: Error };
|
||||
|
||||
function TwitchAPISettings() {
|
||||
|
@ -275,25 +227,63 @@ const TwitchPic = styled('img', {
|
|||
});
|
||||
const TwitchName = styled('p', { fontWeight: 'bold' });
|
||||
|
||||
function TwitchEventSubSettings() {
|
||||
async function startAuthFlow(target: string) {
|
||||
const url = await GetTwitchAuthURL(target);
|
||||
BrowserOpenURL(url);
|
||||
}
|
||||
|
||||
function TwitchUserBlock({ authKey }: { authKey: string }) {
|
||||
const { t } = useTranslation();
|
||||
const [userStatus, setUserStatus] = useState<helix.User | SyncError>(null);
|
||||
const [user, setUser] = useState<helix.User | SyncError>(null);
|
||||
const kv = useAppSelector((state) => state.api.client);
|
||||
|
||||
const getUserInfo = async () => {
|
||||
try {
|
||||
const res = await GetTwitchLoggedUser();
|
||||
setUserStatus(res);
|
||||
const res = await GetTwitchLoggedUser(authKey);
|
||||
setUser(res);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
setUserStatus({ ok: false, error: (e as Error).message });
|
||||
setUser({ ok: false, error: (e as Error).message });
|
||||
}
|
||||
};
|
||||
|
||||
const startAuthFlow = async () => {
|
||||
const url = await GetTwitchAuthURL();
|
||||
BrowserOpenURL(url);
|
||||
};
|
||||
useEffect(() => {
|
||||
// Get user info
|
||||
void getUserInfo();
|
||||
|
||||
const onKeyChange = () => {
|
||||
void getUserInfo();
|
||||
};
|
||||
void kv.subscribeKey(authKey, onKeyChange);
|
||||
return () => {
|
||||
void kv.unsubscribeKey(authKey, onKeyChange);
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (user !== null) {
|
||||
if ('id' in user) {
|
||||
return (
|
||||
<TwitchUser>
|
||||
<TextBlock>
|
||||
{t('pages.twitch-settings.events.authenticated-as')}
|
||||
</TextBlock>
|
||||
<TwitchPic
|
||||
src={user.profile_image_url}
|
||||
alt={t('pages.twitch-settings.events.profile-picture')}
|
||||
/>
|
||||
<TwitchName>{user.display_name}</TwitchName>
|
||||
</TwitchUser>
|
||||
);
|
||||
}
|
||||
return <span>{t('pages.twitch-settings.events.err-no-user')}</span>;
|
||||
}
|
||||
|
||||
return <i>{t('pages.twitch-settings.events.loading-data')}</i>;
|
||||
}
|
||||
|
||||
function TwitchEventSubSettings() {
|
||||
const { t } = useTranslation();
|
||||
const kv = useAppSelector((state) => state.api.client);
|
||||
|
||||
const sendFakeEvent = async (event: keyof typeof eventsubTests) => {
|
||||
const data = eventsubTests[event];
|
||||
|
@ -307,47 +297,13 @@ function TwitchEventSubSettings() {
|
|||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// Get user info
|
||||
void getUserInfo();
|
||||
|
||||
const onKeyChange = () => {
|
||||
void getUserInfo();
|
||||
};
|
||||
void kv.subscribeKey('twitch/auth-keys', onKeyChange);
|
||||
return () => {
|
||||
void kv.unsubscribeKey('twitch/auth-keys', onKeyChange);
|
||||
};
|
||||
}, []);
|
||||
|
||||
let userBlock = <i>{t('pages.twitch-settings.events.loading-data')}</i>;
|
||||
if (userStatus !== null) {
|
||||
if ('id' in userStatus) {
|
||||
userBlock = (
|
||||
<>
|
||||
<TwitchUser>
|
||||
<TextBlock>
|
||||
{t('pages.twitch-settings.events.authenticated-as')}
|
||||
</TextBlock>
|
||||
<TwitchPic
|
||||
src={userStatus.profile_image_url}
|
||||
alt={t('pages.twitch-settings.events.profile-picture')}
|
||||
/>
|
||||
<TwitchName>{userStatus.display_name}</TwitchName>
|
||||
</TwitchUser>
|
||||
</>
|
||||
);
|
||||
} else {
|
||||
userBlock = <span>{t('pages.twitch-settings.events.err-no-user')}</span>;
|
||||
}
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<TextBlock>{t('pages.twitch-settings.events.auth-message')}</TextBlock>
|
||||
<Button
|
||||
variation="primary"
|
||||
onClick={() => {
|
||||
void startAuthFlow();
|
||||
void startAuthFlow('stream');
|
||||
}}
|
||||
>
|
||||
<ExternalLinkIcon /> {t('pages.twitch-settings.events.auth-button')}
|
||||
|
@ -355,7 +311,7 @@ function TwitchEventSubSettings() {
|
|||
<SectionHeader>
|
||||
{t('pages.twitch-settings.events.current-status')}
|
||||
</SectionHeader>
|
||||
{userBlock}
|
||||
<TwitchUserBlock authKey={'twitch/auth-keys'} />
|
||||
<SectionHeader>
|
||||
{t('pages.twitch-settings.events.sim-events')}
|
||||
</SectionHeader>
|
||||
|
@ -375,6 +331,54 @@ function TwitchEventSubSettings() {
|
|||
);
|
||||
}
|
||||
|
||||
function TwitchChatSettings() {
|
||||
const [chatConfig, setChatConfig, loadStatus] = useModule(
|
||||
modules.twitchChatConfig,
|
||||
);
|
||||
const [twitchConfig, setTwitchConfig] = useModule(modules.twitchConfig);
|
||||
const status = useStatus(loadStatus.save);
|
||||
const dispatch = useAppDispatch();
|
||||
const { t } = useTranslation();
|
||||
const disabled = status?.type === 'pending';
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={(ev) => {
|
||||
void dispatch(setTwitchConfig(twitchConfig));
|
||||
void dispatch(setChatConfig(chatConfig));
|
||||
ev.preventDefault();
|
||||
}}
|
||||
>
|
||||
<SectionHeader>
|
||||
{t('pages.twitch-settings.bot-chat-header')}
|
||||
</SectionHeader>
|
||||
<Field size="fullWidth">
|
||||
<Label htmlFor="bot-chat-history">
|
||||
{t('pages.twitch-settings.bot-chat-cooldown-tip')}
|
||||
</Label>
|
||||
<InputBox
|
||||
type="number"
|
||||
id="bot-chat-history"
|
||||
required={true}
|
||||
disabled={disabled}
|
||||
defaultValue={
|
||||
chatConfig ? chatConfig.command_cooldown ?? 2 : undefined
|
||||
}
|
||||
onChange={(ev) =>
|
||||
dispatch(
|
||||
apiReducer.actions.twitchChatConfigChanged({
|
||||
...chatConfig,
|
||||
command_cooldown: parseInt(ev.target.value, 10),
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<SaveButton status={status} />
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export default function TwitchSettingsPage(): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const [twitchConfig, setTwitchConfig] = useModule(modules.twitchConfig);
|
||||
|
|
|
@ -19,9 +19,9 @@ export function GetLastLogs():Promise<Array<log.Entry>>;
|
|||
|
||||
export function GetProblems():Promise<Array<main.Problem>>;
|
||||
|
||||
export function GetTwitchAuthURL():Promise<string>;
|
||||
export function GetTwitchAuthURL(arg1:string):Promise<string>;
|
||||
|
||||
export function GetTwitchLoggedUser():Promise<helix.User>;
|
||||
export function GetTwitchLoggedUser(arg1:string):Promise<helix.User>;
|
||||
|
||||
export function IsFatalError():Promise<boolean>;
|
||||
|
||||
|
|
|
@ -30,12 +30,12 @@ export function GetProblems() {
|
|||
return window['go']['main']['App']['GetProblems']();
|
||||
}
|
||||
|
||||
export function GetTwitchAuthURL() {
|
||||
return window['go']['main']['App']['GetTwitchAuthURL']();
|
||||
export function GetTwitchAuthURL(arg1) {
|
||||
return window['go']['main']['App']['GetTwitchAuthURL'](arg1);
|
||||
}
|
||||
|
||||
export function GetTwitchLoggedUser() {
|
||||
return window['go']['main']['App']['GetTwitchLoggedUser']();
|
||||
export function GetTwitchLoggedUser(arg1) {
|
||||
return window['go']['main']['App']['GetTwitchLoggedUser'](arg1);
|
||||
}
|
||||
|
||||
export function IsFatalError() {
|
||||
|
|
|
@ -7,7 +7,11 @@ import (
|
|||
)
|
||||
|
||||
func Error(err error) slog.Attr {
|
||||
pc, filename, line, _ := runtime.Caller(1)
|
||||
return ErrorSkip(err, 2)
|
||||
}
|
||||
|
||||
func ErrorSkip(err error, skip int) slog.Attr {
|
||||
pc, filename, line, _ := runtime.Caller(skip)
|
||||
|
||||
return slog.Group("error",
|
||||
slog.String("message", err.Error()),
|
||||
|
|
|
@ -125,8 +125,9 @@ func NewManager(ctx context.Context, db database.Database, twitchManager *twitch
|
|||
loyalty.SetBanList(config.BanList)
|
||||
|
||||
// Start twitch handler
|
||||
if twitchManager.Client() != nil {
|
||||
loyalty.twitchIntegration = setupTwitchIntegration(loyaltyContext, loyalty, twitchManager.Client().Chat)
|
||||
twitchClient := twitchManager.Client()
|
||||
if twitchClient != nil && twitchClient.Chat != nil {
|
||||
loyalty.twitchIntegration = setupTwitchIntegration(loyaltyContext, loyalty, twitchClient.Chat)
|
||||
}
|
||||
|
||||
return loyalty, nil
|
||||
|
|
|
@ -25,16 +25,16 @@ type AuthResponse struct {
|
|||
Time time.Time
|
||||
}
|
||||
|
||||
func GetUserClient(db database.Database, forceRefresh bool) (*helix.Client, error) {
|
||||
func GetUserClient(db database.Database, keyPath string, forceRefresh bool) (*helix.Client, error) {
|
||||
var authResp AuthResponse
|
||||
if err := db.GetJSON(AuthKey, &authResp); err != nil {
|
||||
if err := db.GetJSON(keyPath, &authResp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Handle token expiration
|
||||
if forceRefresh || time.Now().After(authResp.Time.Add(time.Duration(authResp.ExpiresIn)*time.Second)) {
|
||||
// Refresh tokens
|
||||
api, err := GetHelixAPI(db)
|
||||
api, err := GetHelixAPI(db, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -49,30 +49,31 @@ func GetUserClient(db database.Database, forceRefresh bool) (*helix.Client, erro
|
|||
authResp.Time = time.Now().Add(time.Duration(refreshed.Data.ExpiresIn) * time.Second)
|
||||
|
||||
// Save new token pair
|
||||
err = db.PutJSON(AuthKey, authResp)
|
||||
err = db.PutJSON(keyPath, authResp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
config, err := GetConfig(db)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return helix.NewClient(&helix.Options{
|
||||
ClientID: config.APIClientID,
|
||||
ClientSecret: config.APIClientSecret,
|
||||
UserAccessToken: authResp.AccessToken,
|
||||
})
|
||||
return GetHelixAPI(db, authResp.AccessToken)
|
||||
}
|
||||
|
||||
func GetHelixAPI(db database.Database) (*helix.Client, error) {
|
||||
func GetHelixAPI(db database.Database, userToken string) (*helix.Client, error) {
|
||||
config, err := GetConfig(db)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// If a user token is provided, create a user client
|
||||
if userToken != "" {
|
||||
return helix.NewClient(&helix.Options{
|
||||
ClientID: config.APIClientID,
|
||||
ClientSecret: config.APIClientSecret,
|
||||
UserAccessToken: userToken,
|
||||
})
|
||||
}
|
||||
|
||||
// If no user token is provided, create an app client
|
||||
baseurl, err := baseURL(db)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
|
@ -4,6 +4,7 @@ const (
|
|||
ActivityKey = "twitch/chat/activity"
|
||||
CustomCommandsKey = "twitch/chat/custom-commands"
|
||||
WriteMessageRPC = "twitch/chat/@send-message"
|
||||
CustomAccountKey = "twitch/chat/chatter-account"
|
||||
)
|
||||
|
||||
type ResponseType string
|
||||
|
|
|
@ -39,11 +39,20 @@ type Module struct {
|
|||
}
|
||||
|
||||
func Setup(ctx context.Context, db database.Database, api *helix.Client, user helix.User, logger *slog.Logger, templater template.Engine) *Module {
|
||||
customUserClient, customUserInfo, err := GetCustomUser(db)
|
||||
if err != nil {
|
||||
if !errors.Is(err, database.ErrEmptyKey) {
|
||||
logger.Error("Failed to get custom user, falling back to streamer account", log.Error(err))
|
||||
}
|
||||
customUserClient = api
|
||||
customUserInfo = user
|
||||
}
|
||||
|
||||
mod := &Module{
|
||||
ctx: ctx,
|
||||
db: db,
|
||||
api: api,
|
||||
user: user,
|
||||
api: customUserClient,
|
||||
user: customUserInfo,
|
||||
logger: logger,
|
||||
templater: templater,
|
||||
lastMessage: sync.NewRWSync(time.Now()),
|
||||
|
@ -236,7 +245,7 @@ func (mod *Module) UnregisterCommand(name string) {
|
|||
func (mod *Module) GetChatters() (users []string) {
|
||||
cursor := ""
|
||||
for {
|
||||
userClient, err := twitch.GetUserClient(mod.db, false)
|
||||
userClient, err := twitch.GetUserClient(mod.db, twitch.AuthKey, false)
|
||||
if err != nil {
|
||||
slog.Error("Could not get user api client for list of chatters", log.Error(err))
|
||||
return
|
||||
|
@ -260,3 +269,19 @@ func (mod *Module) GetChatters() (users []string) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
func GetCustomUser(db database.Database) (*helix.Client, helix.User, error) {
|
||||
userClient, err := twitch.GetUserClient(db, CustomAccountKey, true)
|
||||
if err != nil {
|
||||
return nil, helix.User{}, err
|
||||
}
|
||||
users, err := userClient.GetUsers(&helix.UsersParams{})
|
||||
if err != nil {
|
||||
return nil, helix.User{}, err
|
||||
}
|
||||
if len(users.Data.Users) < 1 {
|
||||
return nil, helix.User{}, errors.New("no users found")
|
||||
}
|
||||
|
||||
return userClient, users.Data.Users[0], nil
|
||||
}
|
||||
|
|
|
@ -5,6 +5,8 @@ import (
|
|||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.sr.ht/~ashkeel/strimertul/twitch/chat"
|
||||
|
||||
"git.sr.ht/~ashkeel/strimertul/twitch"
|
||||
|
||||
"github.com/nicklaw5/helix/v2"
|
||||
|
@ -15,7 +17,7 @@ func (c *Client) GetLoggedUser() (helix.User, error) {
|
|||
return c.User, nil
|
||||
}
|
||||
|
||||
client, err := twitch.GetUserClient(c.DB, false)
|
||||
client, err := twitch.GetUserClient(c.DB, twitch.AuthKey, false)
|
||||
if err != nil {
|
||||
return helix.User{}, fmt.Errorf("failed getting API client for user: %w", err)
|
||||
}
|
||||
|
@ -48,7 +50,15 @@ func (c *Client) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|||
return
|
||||
}
|
||||
|
||||
err = c.DB.PutJSON(twitch.AuthKey, twitch.AuthResponse{
|
||||
// Check scope to see which credentials are we getting (stream/chat)
|
||||
state := req.URL.Query().Get("state")
|
||||
key := twitch.AuthKey
|
||||
switch state {
|
||||
case "chat":
|
||||
key = chat.CustomAccountKey
|
||||
}
|
||||
|
||||
err = c.DB.PutJSON(key, twitch.AuthResponse{
|
||||
AccessToken: userTokenResponse.Data.AccessToken,
|
||||
RefreshToken: userTokenResponse.Data.RefreshToken,
|
||||
ExpiresIn: userTokenResponse.Data.ExpiresIn,
|
||||
|
@ -59,6 +69,7 @@ func (c *Client) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|||
http.Error(w, "error saving auth data for user: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Add("Content-Type", "text/html")
|
||||
_, _ = fmt.Fprintf(w, `<html><body><h2>All done, you can close me now!</h2><script>window.close();</script></body></html>`)
|
||||
}
|
||||
|
|
|
@ -97,7 +97,6 @@ type Client struct {
|
|||
eventSub *eventsub.Client
|
||||
server *webserver.WebServer
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
|
||||
restart chan bool
|
||||
streamOnline *sync.RWSync[bool]
|
||||
|
@ -120,35 +119,14 @@ func newClient(ctx context.Context, config twitch.Config, db database.Database,
|
|||
}
|
||||
|
||||
var err error
|
||||
client.API, err = twitch.GetHelixAPI(db)
|
||||
client.API, err = twitch.GetHelixAPI(db, "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create twitch client: %w", err)
|
||||
}
|
||||
|
||||
server.RegisterRoute(twitch.CallbackRoute, client)
|
||||
|
||||
if userClient, err := twitch.GetUserClient(db, true); err == nil {
|
||||
users, err := userClient.GetUsers(&helix.UsersParams{})
|
||||
if err != nil {
|
||||
client.Logger.Error("Failed looking up user", log.Error(err))
|
||||
} else if len(users.Data.Users) < 1 {
|
||||
client.Logger.Error("No users found, please authenticate in Twitch configuration -> Events")
|
||||
} else {
|
||||
client.Logger.Info("Twitch user identified", slog.String("user", users.Data.Users[0].ID))
|
||||
client.User = users.Data.Users[0]
|
||||
client.eventSub, err = eventsub.Setup(ctx, userClient, client.User, db, client.Logger)
|
||||
if err != nil {
|
||||
client.Logger.Error("Failed to setup EventSub", log.Error(err))
|
||||
}
|
||||
|
||||
tpl := client.GetTemplateEngine()
|
||||
client.Chat = chat.Setup(ctx, db, userClient, client.User, client.Logger, tpl)
|
||||
client.Alerts = alerts.Setup(ctx, db, client.Logger, tpl)
|
||||
client.Timers = timers.Setup(ctx, db, client.Logger)
|
||||
}
|
||||
} else {
|
||||
client.Logger.Warn("Twitch user not identified, this will break most features")
|
||||
}
|
||||
client.initializeEventSubUserFeatures()
|
||||
|
||||
go client.runStatusPoll()
|
||||
|
||||
|
@ -160,6 +138,36 @@ func newClient(ctx context.Context, config twitch.Config, db database.Database,
|
|||
return client, nil
|
||||
}
|
||||
|
||||
func (c *Client) initializeEventSubUserFeatures() {
|
||||
userClient, err := twitch.GetUserClient(c.DB, twitch.AuthKey, true)
|
||||
if err != nil {
|
||||
c.Logger.Warn("Twitch user not identified, this will break most features")
|
||||
return
|
||||
}
|
||||
users, err := userClient.GetUsers(&helix.UsersParams{})
|
||||
if err != nil {
|
||||
c.Logger.Error("Failed looking up user", log.Error(err))
|
||||
return
|
||||
}
|
||||
if len(users.Data.Users) < 1 {
|
||||
c.Logger.Error("No users found, please authenticate in Twitch configuration -> Events")
|
||||
return
|
||||
}
|
||||
c.Logger.Info("Twitch user identified", slog.String("user", users.Data.Users[0].ID))
|
||||
c.User = users.Data.Users[0]
|
||||
|
||||
c.eventSub, err = eventsub.Setup(c.ctx, userClient, c.User, c.DB, c.Logger)
|
||||
if err != nil {
|
||||
c.Logger.Error("Failed to setup EventSub", log.Error(err))
|
||||
return
|
||||
}
|
||||
|
||||
tpl := c.GetTemplateEngine()
|
||||
c.Chat = chat.Setup(c.ctx, c.DB, userClient, c.User, c.Logger, tpl)
|
||||
c.Alerts = alerts.Setup(c.ctx, c.DB, c.Logger, tpl)
|
||||
c.Timers = timers.Setup(c.ctx, c.DB, c.Logger)
|
||||
}
|
||||
|
||||
func (c *Client) runStatusPoll() {
|
||||
c.Logger.Info("Started polling for stream status")
|
||||
for {
|
||||
|
|
|
@ -48,12 +48,14 @@ func CheckScopes(db database.Database) (bool, error) {
|
|||
return slices.Equal(scopes, authResp.Scope), nil
|
||||
}
|
||||
|
||||
func GetAuthorizationURL(api *helix.Client) string {
|
||||
func GetAuthorizationURL(api *helix.Client, state string) string {
|
||||
if api == nil {
|
||||
return "twitch-not-configured"
|
||||
}
|
||||
return api.GetAuthorizationURL(&helix.AuthorizationURLParams{
|
||||
ResponseType: "code",
|
||||
Scopes: scopes,
|
||||
State: state,
|
||||
ForceVerify: true,
|
||||
})
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue