Merge branch 'gcf' into main

Signed-off-by: Katalina Okano <git@kat.cafe>
This commit is contained in:
41666 2020-12-05 03:11:12 -05:00
commit 156bd8f06e
364 changed files with 5234 additions and 22248 deletions

View file

@ -1,21 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "common",
srcs = [
"await-exit.go",
"envconfig.go",
"finders.go",
],
importpath = "github.com/roleypoly/roleypoly/src/common",
visibility = ["//visibility:public"],
)
go_test(
name = "common_test",
srcs = [
"envconfig_test.go",
"finders_test.go",
],
embed = [":common"],
)

View file

@ -1,18 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "bot",
srcs = [
"commandmux.go",
"scaffolding.go",
],
importpath = "github.com/roleypoly/roleypoly/src/common/bot",
visibility = ["//visibility:public"],
deps = [
"//src/common",
"@com_github_bwmarrin_discordgo//:discordgo",
"@com_github_dghubble_trie//:trie",
"@com_github_lampjaw_discordclient//:discordclient",
"@io_k8s_klog//:klog",
],
)

View file

@ -9,6 +9,7 @@ import (
// GetenvValue is a holder type for Getenv to translate any Getenv strings to real types
type GetenvValue struct {
key string
value string
}
@ -25,6 +26,7 @@ func Getenv(key string, defaultValue ...string) GetenvValue {
return GetenvValue{
value: strings.TrimSpace(value),
key: key,
}
}
@ -41,6 +43,15 @@ func (g GetenvValue) StringSlice(optionalDelimiter ...string) []string {
return strings.Split(g.value, delimiter)
}
// SafeURL removes any trailing slash
func (g GetenvValue) SafeURL() string {
if g.value[len(g.value)-1] == '/' {
return g.value[:len(g.value)-1]
}
return g.value
}
func (g GetenvValue) Bool() bool {
lowercaseValue := strings.ToLower(g.value)
if g.value == "1" || lowercaseValue == "true" || lowercaseValue == "yes" {
@ -63,3 +74,11 @@ func (g GetenvValue) Number() int {
func (g GetenvValue) JSON(target interface{}) error {
return json.Unmarshal([]byte(g.value), target)
}
func (g GetenvValue) OrFatal() GetenvValue {
if g.value == "" {
panic("Getenv value was empty and shouldn't be. key: " + g.key)
}
return g
}

View file

@ -2,8 +2,10 @@ package common_test
import (
"os"
"strings"
"testing"
"github.com/onsi/gomega"
"github.com/roleypoly/roleypoly/src/common"
)
@ -13,6 +15,8 @@ var (
"slice": "hello,world",
"slice_no_delim": "hello world",
"slice_set_delim": "hello|world",
"url": "https://google.com",
"url_trailing": "https://google.com/",
"number": "10005",
"number_bad": "abc123",
"bool": "true",
@ -60,6 +64,19 @@ func TestEnvconfigStringSliceSetDelimeter(t *testing.T) {
}
}
func TestEnvconfigSafeURL(t *testing.T) {
testUrl := common.Getenv("test__url").SafeURL()
if strings.HasSuffix(testUrl, "/") {
t.FailNow()
}
}
func TestEnvconfigSafeURLWithTrailing(t *testing.T) {
testUrl := common.Getenv("test__url_trailing").SafeURL()
if strings.HasSuffix(testUrl, "/") {
t.FailNow()
}
}
func TestEnvconfigNumber(t *testing.T) {
testNum := common.Getenv("test__number").Number()
if testNum != 10005 {
@ -121,3 +138,17 @@ func TestEnvconfigJSON(t *testing.T) {
t.FailNow()
}
}
func TestEnvconfigFatal(t *testing.T) {
O := gomega.NewWithT(t)
O.Expect(func() {
_ = common.Getenv("test__thing_that_doesnt_exist").OrFatal().String()
}).Should(gomega.Panic(), "Getenv without a value should panic")
}
func TestEnvconfigNotFatal(t *testing.T) {
O := gomega.NewWithT(t)
O.Expect(func() {
_ = common.Getenv("test__string").OrFatal().String()
}).ShouldNot(gomega.Panic(), "Getenv with a value should not panic")
}

View file

@ -0,0 +1,13 @@
export enum CategoryType {
SINGLE = 0,
MULTI,
}
export type Category = {
id: string;
name: string;
rolesList: string[];
hidden: boolean;
type: CategoryType;
position: number;
};

49
src/common/types/Guild.ts Normal file
View file

@ -0,0 +1,49 @@
import { Category } from './Category';
import { Role } from './Role';
import { Member } from './User';
export type Guild = {
id: string;
name: string;
icon: string;
ownerid: string;
membercount: number;
splash: string;
};
export type GuildRoles = {
id: string;
rolesList: Role[];
};
export type GuildData = {
id: string;
message: string;
categoriesList: Category[];
entitlementsList: string[];
};
export type PresentableGuild = {
id: string;
guild: Guild;
member: Member;
data: GuildData;
roles: GuildRoles;
};
export type GuildEnumeration = {
guildsList: PresentableGuild[];
};
export enum UserGuildPermissions {
User,
Manager,
Admin,
}
export type GuildSlug = {
id: string;
name: string;
icon: string;
permissionLevel: UserGuildPermissions;
};

15
src/common/types/Role.ts Normal file
View file

@ -0,0 +1,15 @@
export enum RoleSafety {
SAFE = 0,
HIGHERTHANBOT,
DANGEROUSPERMISSIONS,
}
export type Role = {
id: string;
name: string;
color: number;
permissions: number;
managed: boolean;
position: number;
safety: RoleSafety;
};

View file

@ -0,0 +1,18 @@
import { GuildSlug } from './Guild';
import { DiscordUser } from './User';
export type AuthTokenResponse = {
access_token: string;
token_type: 'Bearer';
expires_in: number;
refresh_token: string;
scope: string;
};
export type SessionData = {
/** sessionID is a KSUID */
sessionID: string;
tokens: AuthTokenResponse;
user: DiscordUser;
guilds: GuildSlug[];
};

20
src/common/types/User.go Normal file
View file

@ -0,0 +1,20 @@
package types
type DiscordUser struct {
ID string `json:"id,omitempty"`
Username string `json:"username,omitempty"`
Discriminator string `json:"discriminator,omitempty"`
Avatar string `json:"avatar,omitempty"`
Bot bool `json:"bot,omitempty"`
}
type Member struct {
GuildID string `json:"guildid,omitempty"`
Roles []string `json:"rolesList,omitempty"`
Nick string `json:"nick,omitempty"`
User DiscordUser `json:"user,omitempty"`
}
type RoleypolyUser struct {
DiscordUser DiscordUser `json:"discorduser,omitempty"`
}

18
src/common/types/User.ts Normal file
View file

@ -0,0 +1,18 @@
export type DiscordUser = {
id: string;
username: string;
discriminator: string;
avatar: string;
bot: boolean;
};
export type Member = {
guildid: string;
rolesList: string[];
nick: string;
user: DiscordUser;
};
export type RoleypolyUser = {
discorduser: DiscordUser;
};

View file

@ -0,0 +1,58 @@
import { Role } from '.';
export const demoData: Role[] = [
{
id: '557812805546541066',
name: 'a cute role ♡',
color: 0xd19494,
permissions: 0,
safety: 0,
managed: false,
position: 0,
},
{
id: '557812901717737472',
name: 'a vanity role ♡',
color: 0xd1d194,
permissions: 0,
safety: 0,
managed: false,
position: 0,
},
{
id: '557812915386843170',
name: 'a brave role ♡',
color: 0x94d194,
permissions: 0,
safety: 0,
managed: false,
position: 0,
},
{
id: '557824893241131029',
name: 'a proud role ♡',
color: 0x94d1d1,
permissions: 0,
safety: 0,
managed: false,
position: 0,
},
{
id: '557824994269200384',
name: 'a wonderful role ♡',
color: 0x9494d1,
permissions: 0,
safety: 0,
managed: false,
position: 0,
},
{
id: '557825026406088717',
name: 'a 日本語 role ♡',
color: 0xd194d1,
permissions: 0,
safety: 0,
managed: false,
position: 0,
},
];

View file

@ -0,0 +1,5 @@
export * from './Role';
export * from './Category';
export * from './Guild';
export * from './User';
export * from './Session';

View file

@ -0,0 +1,31 @@
package types
import "time"
// CreateSessionRequest is the payload to /create-session
type CreateSessionRequest struct {
AccessTokenResponse AccessTokenResponse
Fingerprint Fingerprint
}
type Fingerprint struct {
UserAgent string
ClientIP string
ForwardedFor string
}
type CreateSessionResponse struct {
SessionID string
}
type SessionData struct {
SessionID string
Fingerprint Fingerprint
AccessTokens AccessTokenResponse
UserData UserData
}
type UserData struct {
DataExpires time.Time
UserID string
}

View file

@ -0,0 +1,241 @@
import {
Category,
DiscordUser,
Guild,
GuildData,
GuildEnumeration,
GuildRoles,
Member,
Role,
RoleSafety,
RoleypolyUser,
CategoryType,
} from '.';
export const roleCategory: Role[] = [
{
id: 'aaa',
permissions: 0,
name: 'She/Her',
color: 0xffc0cb,
position: 1,
managed: false,
safety: RoleSafety.SAFE,
},
{
id: 'bbb',
permissions: 0,
name: 'He/Him',
color: 0xc0ebff,
position: 2,
managed: false,
safety: RoleSafety.SAFE,
},
{
id: 'ccc',
permissions: 0,
name: 'They/Them',
color: 0xc0ffd5,
position: 3,
managed: false,
safety: RoleSafety.SAFE,
},
{
id: 'ddd',
permissions: 0,
name: 'Reee',
color: 0xff0000,
position: 4,
managed: false,
safety: RoleSafety.SAFE,
},
{
id: 'eee',
permissions: 0,
name: 'black but actually bravely default',
color: 0x000000,
position: 5,
managed: false,
safety: RoleSafety.SAFE,
},
{
id: 'fff',
permissions: 0,
name: 'b̻͌̆̽ͣ̃ͭ̊l͚̥͙̔ͨ̊aͥć͕k͎̟͍͕ͥ̋ͯ̓̈̉̋i͛̄̔͂̚̚҉̳͈͔̖̼̮ṣ̤̗̝͊̌͆h͈̭̰͔̥̯ͅ',
color: 0x1,
position: 6,
managed: false,
safety: RoleSafety.SAFE,
},
{
id: 'unsafe1',
permissions: 0,
name: 'too high',
color: 0xff0088,
position: 7,
managed: false,
safety: RoleSafety.HIGHERTHANBOT,
},
{
id: 'unsafe2',
permissions: 0x00000008 | 0x10000000,
name: 'too strong',
color: 0x00ff88,
position: 8,
managed: false,
safety: RoleSafety.DANGEROUSPERMISSIONS,
},
];
export const mockCategory: Category = {
id: 'aaa',
name: 'Mock',
rolesList: roleCategory.map((x) => x.id),
hidden: false,
type: CategoryType.MULTI,
position: 0,
};
export const roleCategory2: Role[] = [
{
id: 'ddd2',
permissions: 0,
name: 'red',
color: 0xff0000,
position: 9,
managed: false,
safety: RoleSafety.SAFE,
},
{
id: 'eee2',
permissions: 0,
name: 'green',
color: 0x00ff00,
position: 10,
managed: false,
safety: RoleSafety.SAFE,
},
];
export const mockCategorySingle: Category = {
id: 'bbb',
name: 'Mock Single 岡野',
rolesList: roleCategory2.map((x) => x.id),
hidden: false,
type: CategoryType.SINGLE,
position: 0,
};
export const guildRoles: GuildRoles = {
id: 'aaa',
rolesList: [...roleCategory, ...roleCategory2],
};
export const roleWikiData = {
aaa: 'Typically used by feminine-identifying people',
bbb: 'Typically used by masculine-identifying people',
ccc: 'Typically used to refer to all people as a singular neutral.',
};
export const guild: Guild = {
name: 'emoji megaporium',
id: 'aaa',
icon:
'https://cdn.discordapp.com/icons/421896162539470888/3372fd895ed913b55616c5e49cd50e60.png?size=256',
ownerid: 'bbb',
membercount: 23453,
splash: '',
};
export const guildMap: { [x: string]: Guild } = {
'emoji megaporium': guild,
Roleypoly: {
name: 'Roleypoly',
id: 'aaa',
icon:
'https://cdn.discordapp.com/icons/203493697696956418/ff08d36f5aee1ff48f8377b65d031ab0.png?size=256',
ownerid: 'bbb',
membercount: 23453,
splash: '',
},
'chamber of secrets': {
name: 'chamber of secrets',
id: 'aaa',
icon: '',
ownerid: 'bbb',
membercount: 23453,
splash: '',
},
Eclipse: {
name: 'Eclipse',
id: 'aaa',
icon:
'https://cdn.discordapp.com/icons/408821059161423873/49dfdd8b2456e2977e80a8b577b19c0d.png?size=256',
ownerid: 'bbb',
membercount: 23453,
splash: '',
},
};
export const guildData: GuildData = {
id: 'aaa',
message: 'henlo worl!!',
categoriesList: [mockCategory, mockCategorySingle],
entitlementsList: [],
};
export const user: DiscordUser = {
id: '123',
username: 'okano cat',
discriminator: '3266',
avatar:
'https://cdn.discordapp.com/avatars/62601275618889728/b1292bb974557337702cb941fc038085.png',
bot: false,
};
export const member: Member = {
guildid: 'aaa',
rolesList: ['aaa', 'eee', 'unsafe2', 'ddd2'],
nick: 'okano cat',
user: user,
};
export const rpUser: RoleypolyUser = {
discorduser: user,
};
export const guildEnum: GuildEnumeration = {
guildsList: [
{
id: 'aaa',
guild: guildMap['emoji megaporium'],
member,
data: guildData,
roles: guildRoles,
},
{
id: 'bbb',
guild: guildMap['Roleypoly'],
member: {
...member,
rolesList: ['unsafe2'],
},
data: guildData,
roles: guildRoles,
},
{
id: 'ccc',
guild: guildMap['chamber of secrets'],
member,
data: guildData,
roles: guildRoles,
},
{
id: 'ddd',
guild: guildMap['Eclipse'],
member,
data: guildData,
roles: guildRoles,
},
],
};

View file

@ -0,0 +1,10 @@
package types
// AccessTokenResponse is the response for Discord's OAuth token grant flow
type AccessTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
}

View file

@ -1,21 +0,0 @@
load("//hack/bazel/js:react.bzl", "react_library")
load("//hack/bazel/js:jest.bzl", "jest_test")
package(default_visibility = ["//visibility:public"])
react_library(
name = "utils",
deps = [
"chroma-js",
"//src/rpc/shared",
"@types/chroma-js",
],
)
jest_test(
src = ":utils",
deps = [
"//src/design-system/shared-types",
"//src/rpc/shared",
],
)

View file

@ -1,8 +1,8 @@
import { hasPermission, permissions, hasPermissionOrAdmin } from './hasPermission';
import { Role } from 'roleypoly/src/rpc/shared';
import { guildRoles } from 'roleypoly/src/design-system/shared-types/storyData';
import { Role } from 'roleypoly/common/types';
import { guildRoles } from 'roleypoly/common/types/storyData';
const roles: Role.AsObject[] = [
const roles: Role[] = [
{
...guildRoles.rolesList[0],
permissions: permissions.ADMINISTRATOR,

View file

@ -1,14 +1,16 @@
import { Role } from 'roleypoly/src/rpc/shared';
import { Role } from '../types';
export const hasPermission = (roles: Role.AsObject[], permission: number): boolean => {
const aggregateRoles = roles.reduce((acc, role) => acc | role.permissions, 0);
return (aggregateRoles & permission) === permission;
export const evaluatePermission = (haystack: number, needle: number): boolean => {
return (haystack & needle) === needle;
};
export const hasPermissionOrAdmin = (
roles: Role.AsObject[],
permission: number
): boolean => hasPermission(roles, permission | permissions.ADMINISTRATOR);
export const hasPermission = (roles: Role[], permission: number): boolean => {
const aggregateRoles = roles.reduce((acc, role) => acc | role.permissions, 0);
return evaluatePermission(aggregateRoles, permission);
};
export const hasPermissionOrAdmin = (roles: Role[], permission: number): boolean =>
hasPermission(roles, permission | permissions.ADMINISTRATOR);
export const permissions = {
CREATE_INSTANT_INVITE: 0x1,

View file

@ -0,0 +1 @@
export const isBrowser = () => typeof window !== 'undefined';

View file

@ -1,9 +0,0 @@
import { DiscordUser } from 'roleypoly/src/rpc/shared';
import { user } from 'roleypoly/src/design-system/shared-types/storyData';
import { AsObjectToProto } from './protoReflection';
it('converts a RoleypolyUser.AsObject back to protobuf', () => {
const proto = AsObjectToProto(DiscordUser, user);
expect(proto.toObject()).toMatchObject(user);
});

View file

@ -1,47 +0,0 @@
import * as pbjs from 'google-protobuf';
// Protobuf Message itself
type GenericObject<T extends pbjs.Message> = T;
// Message's "setter" call
type ProtoFunction<T extends pbjs.Message, U extends ReturnType<T['toObject']>> = (
value: U[keyof U]
) => void;
/**
* AsObjectToProto does the opposite of ProtoMessage.toObject().
* This function turns regular JS objects back into their source protobuf message type,
* with the help us copious amounts of reflection.
* @param protoClass A protobuf message class
* @param input A JS object that corresponds to the protobuf message class.
*/
export const AsObjectToProto = <T extends pbjs.Message>(
protoClass: { new (): T },
input: ReturnType<T['toObject']>
): GenericObject<T> => {
// First, we create the message itself
const proto = new protoClass();
// We want the keys from the message, this will give us the setter names we need.
const protoKeys = Object.getOwnPropertyNames((proto as any).__proto__);
// Loop over the input data keys
for (let inputKey in input) {
// As we loop, find the setter function for the key
const setCallName = protoKeys.find(
(key) => `set${inputKey.toLowerCase()}` === key.toLowerCase()
) as keyof typeof proto;
// If we encounter a key without a place to go, we silently ignore it.
if (!setCallName) {
continue;
}
// But, if it all succeeds, we call the setter with the JS object's value.
((proto[setCallName] as unknown) as ProtoFunction<T, typeof input>)(
input[inputKey]
);
}
return proto;
};

View file

@ -1,7 +0,0 @@
load("//hack/bazel/js:react.bzl", "react_library")
package(default_visibility = ["//visibility:public"])
react_library(
name = "withContext",
)

View file

@ -1,19 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "version",
srcs = ["version.go"],
importpath = "github.com/roleypoly/roleypoly/src/common/version",
visibility = ["//visibility:public"],
x_defs = {
"GitCommit": "{STABLE_GIT_COMMIT}",
"GitBranch": "{STABLE_GIT_BRANCH}",
"BuildDate": "{BUILD_DATE}",
},
)
go_test(
name = "version_test",
srcs = ["version_test.go"],
embed = [":version"],
)