diff --git a/2fa.go b/2fa.go new file mode 100644 index 0000000..1690e0e --- /dev/null +++ b/2fa.go @@ -0,0 +1,9 @@ +package tdproto + +// RecoveryStatus: +const ( + Unknown2fa = "unknown" + Unconfirmed2fa = "unconfirmed" + Confirmed2fa = "confirmed" + Declined2fa = "declined" +) diff --git a/CHANGELOG b/CHANGELOG index 0719da8..b6a204a 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,9 @@ +v.2.0.0 + - websocket events moved to tdevents package + - PaginatedXXX structs moved to tdapi + - IconData now always not nullable + - server.roster event removed + v.1.46.3 - more docs added diff --git a/codegen/api_paths/task.go b/codegen/api_paths/task.go index 81ae388..0c56dfb 100644 --- a/codegen/api_paths/task.go +++ b/codegen/api_paths/task.go @@ -1,36 +1,37 @@ package api_paths import ( - "github.com/tada-team/tdproto/tdapi" + "github.com/tada-team/tdproto/tdforms" + "github.com/tada-team/tdproto/tdquery" ) var TaskPaths = []PathSpec{ { Path: "/api/v4/teams/{team_id}/tasks", Post: &OperationSpec{ - Request: tdapi.Task{}, - Response: tdapi.Task{}, + Request: tdforms.Task{}, + Response: tdforms.Task{}, Description: "Create new task", }, Get: &OperationSpec{ - QueryStruct: tdapi.TaskFilter{}, - Response: []tdapi.Task{}, + QueryStruct: tdquery.Tasks{}, + Response: []tdforms.Task{}, Description: "Get the list of tasks", }, }, { Path: "/api/v4/teams/{team_id}/tasks/{task_id}", Get: &OperationSpec{ - Response: tdapi.Task{}, + Response: tdforms.Task{}, Description: "Get task", }, Post: &OperationSpec{ - Request: tdapi.Task{}, - Response: tdapi.Task{}, + Request: tdforms.Task{}, + Response: tdforms.Task{}, Description: "Update task", }, Delete: &OperationSpec{ - Response: tdapi.Task{}, + Response: tdforms.Task{}, Description: "Delete task", }, }, diff --git a/codegen/dart/main.go b/codegen/dart/main.go index ebc6461..ee40017 100644 --- a/codegen/dart/main.go +++ b/codegen/dart/main.go @@ -12,9 +12,11 @@ import ( "github.com/tada-team/tdproto/codegen" ) -const libPathPrefix = "./lib/" -const enumsPathPrefix = "./src/enums" -const modelsPathPrefix = "./src/models" +const ( + libPathPrefix = "./lib/" + enumsPathPrefix = "./src/enums" + modelsPathPrefix = "./src/models" +) var dartTypeMap = map[string]string{ "string": "String", @@ -127,12 +129,8 @@ func lowercaseFirstOrAll(input string) string { return strings.ToLower(input) } -func writeFileFromTemplate(fileName string, template *template.Template, data interface{}, useExclusive bool) error { - - fileFlags := os.O_WRONLY | os.O_CREATE - if useExclusive { - fileFlags |= os.O_EXCL - } +func renderToFile(fileName string, template *template.Template, data interface{}) error { + fileFlags := os.O_WRONLY | os.O_CREATE | os.O_EXCL file, err := os.OpenFile(fileName, fileFlags, 0o640) if err != nil { @@ -160,7 +158,7 @@ func generateDart(tdprotoInfo *codegen.TdPackage, baseLibPath string) error { enumFilePath := path.Join(enumsPathPrefix, fmt.Sprintf("%s.dart", enumFileName)) libInfo.GeneratedEnums = append(libInfo.GeneratedEnums, enumFilePath) - err := writeFileFromTemplate(path.Join(baseLibPath, enumFilePath), dartEnumTemplate, tdEnum, true) + err := renderToFile(path.Join(baseLibPath, enumFilePath), dartEnumTemplate, tdEnum) if err != nil { return err } @@ -179,13 +177,13 @@ func generateDart(tdprotoInfo *codegen.TdPackage, baseLibPath string) error { return nil } - err = writeFileFromTemplate(path.Join(baseLibPath, dartClassFilePath), dartClassTemplate, dartClass, true) + err = renderToFile(path.Join(baseLibPath, dartClassFilePath), dartClassTemplate, dartClass) if err != nil { return err } } - err := writeFileFromTemplate(path.Join(baseLibPath, "./tdproto_dart.dart"), dartLibTemplate, libInfo, true) + err := renderToFile(path.Join(baseLibPath, "./tdproto_dart.dart"), dartLibTemplate, libInfo) if err != nil { return err } @@ -298,7 +296,7 @@ func main() { flag.Parse() var dartLibPath string - switch len_args := len(flag.Args()); len_args { + switch lenArgs := len(flag.Args()); lenArgs { case 0: newTempDir, err := os.MkdirTemp("", "tdproto_dart") if err != nil { @@ -309,7 +307,7 @@ func main() { case 1: dartLibPath = flag.Arg(0) default: - panic(fmt.Errorf("expected zero or one argument got %d", len_args)) + panic(fmt.Errorf("expected zero or one argument got %d", lenArgs)) } err = createDirectoryStructure(dartLibPath) diff --git a/codegen/inspect.go b/codegen/inspect.go index 7aef9a1..b75a92d 100644 --- a/codegen/inspect.go +++ b/codegen/inspect.go @@ -51,23 +51,26 @@ type TdStructField struct { IsList bool IsOmitEmpty bool IsNotSerialized bool + PackageName string } type TdStruct struct { - Name string - Help string - Fields []TdStructField - ReadOnly bool - AnonnymousFields []string - FileName string + Name string + Help string + Fields []TdStructField + ReadOnly bool + AnonymousFields []string + FileName string + PackageName string } type TdType struct { - Name string - Help string - IsArray bool - BaseType string - Filename string + Name string + Help string + IsArray bool + BaseType string + Filename string + PackageName string } type TdMapType struct { @@ -76,31 +79,36 @@ type TdMapType struct { KeyTypeStr string ValueTypeStr string Filename string + PackageName string } type TdPackage struct { - TdStructs map[string]TdStruct - TdTypes map[string]TdType - TdEvents map[string]string - TdMapTypes map[string]TdMapType - TdConsts []TdConstFields - TdQueries map[string]TdQuery + TdStructs map[string]TdStruct + TdTypes map[string]TdType + TdEvents map[string]string + TdMapTypes map[string]TdMapType + TdConstants []TdConstFields + TdQueries map[string]TdQuery + Name string } type TdProto struct { TdForms *TdPackage TdModels *TdPackage + TdEvents *TdPackage + TdQuery *TdPackage } type TdEnum struct { - Name string - Values []string + Name string + Values []string + PackageName string } func (i TdPackage) GetEnums() []TdEnum { constMap := make(map[string][]string) - for _, aConst := range i.TdConsts { + for _, aConst := range i.TdConstants { constType := aConst.Type constValue := aConst.Value @@ -112,8 +120,9 @@ func (i TdPackage) GetEnums() []TdEnum { for key, value := range constMap { listOfEnums = append(listOfEnums, TdEnum{ - Name: key, - Values: value, + Name: key, + Values: value, + PackageName: i.Name, }) } @@ -140,12 +149,12 @@ func (tds TdStruct) IsEventParams(tdInfo *TdPackage) bool { } func (tds TdStruct) GetStructAnonymousStructs(tdInfo *TdPackage) []TdStruct { - anonymousStructs := make([]TdStruct, len(tds.AnonnymousFields)) - for i, anonymousStructName := range tds.AnonnymousFields { + anonymousStructs := make([]TdStruct, len(tds.AnonymousFields)) + for i, anonymousStructName := range tds.AnonymousFields { anonymousStructs[i] = tdInfo.TdStructs[anonymousStructName] } - // TODO: Deep copy Fields and AnonnymousFields + // TODO: Deep copy Fields and AnonymousFields return anonymousStructs } @@ -164,164 +173,49 @@ func (tds TdStruct) GetAllJsonFields(tdInfo *TdPackage) []TdStructField { func ParseTdproto() (infoToFill *TdProto, err error) { infoToFill = new(TdProto) - tdprotoFileSet := token.NewFileSet() - - tdModelsPackage := new(TdPackage) - tdModelsPackage.TdEvents = make(map[string]string) - tdModelsPackage.TdStructs = make(map[string]TdStruct) - tdModelsPackage.TdTypes = make(map[string]TdType) - tdModelsPackage.TdMapTypes = make(map[string]TdMapType) - tdModelsPackage.TdQueries = make(map[string]TdQuery) - - infoToFill.TdModels = tdModelsPackage - - tdprotoNameToAstMap, err := extractTdprotoAst(tdprotoFileSet) - if err != nil { - return nil, err - } - - tdprotoAst := tdprotoNameToAstMap["tdproto"] - err = parseTdprotoAst(tdprotoAst, tdModelsPackage, nil) - if err != nil { - return nil, err - } - - tdapiFileSet := token.NewFileSet() - tdapiNameToAstMap, err := extractTdapiAst(tdapiFileSet) - if err != nil { - return nil, err - } - - tdFormsPackage := new(TdPackage) - tdFormsPackage.TdEvents = make(map[string]string) - tdFormsPackage.TdStructs = make(map[string]TdStruct) - tdFormsPackage.TdTypes = make(map[string]TdType) - tdFormsPackage.TdMapTypes = make(map[string]TdMapType) - - infoToFill.TdForms = tdFormsPackage - - err = parseTdprotoAst(tdapiNameToAstMap["tdapi"], tdFormsPackage, - &map[string]string{ - "task": "", - "my_reactions": "", - "resp": "", - "err": "", - "sharplinks": "", - "easy_api": "", - "botcommands": "", - }, - ) - if err != nil { - return nil, err - } - - // Cherry picking - // Task - err = cherryPickStruct(tdModelsPackage, tdFormsPackage, "Task") - if err != nil { - return nil, err - } - // TaskFilter query - err = cherryPickQuery(tdModelsPackage, tdFormsPackage, "TaskFilter") - if err != nil { - return nil, err - } - // MyReactions - err = cherryPickStruct(tdModelsPackage, tdFormsPackage, "MyReactions") - if err != nil { - return nil, err - } - - // Resp - err = cherryPickStruct(tdModelsPackage, tdFormsPackage, "Resp") - if err != nil { - return nil, err - } - - // Err - err = cherryPickTypeAlias(tdModelsPackage, tdFormsPackage, "Err") + allPackages := make(map[string]*ast.Package) + err = extractTdprotoAst(&allPackages) if err != nil { - return nil, err + return infoToFill, err } - // EasyApiMessage - err = cherryPickStruct(tdModelsPackage, tdFormsPackage, "EasyApiMessage") + err = createTdProtoPackage(&infoToFill.TdModels, "tdproto", allPackages) if err != nil { - return nil, err + return infoToFill, err } - // SharpLink - err = cherryPickStruct(tdModelsPackage, tdFormsPackage, "SharpLink") + err = createTdProtoPackage(&infoToFill.TdForms, "tdforms", allPackages) if err != nil { - return nil, err + return infoToFill, err } - // SharpLinks - err = cherryPickTypeAlias(tdModelsPackage, tdFormsPackage, "SharpLinks") + err = createTdProtoPackage(&infoToFill.TdEvents, "tdevents", allPackages) if err != nil { - return nil, err + return infoToFill, err } - // SharpLinkMeta - err = cherryPickStruct(tdModelsPackage, tdFormsPackage, "SharpLinkMeta") + err = createTdProtoPackage(&infoToFill.TdQuery, "tdquery", allPackages) if err != nil { - return nil, err - } - - // BotCommand - err = cherryPickStruct(tdModelsPackage, tdFormsPackage, "BotCommand") - if err != nil { - return nil, err - } - - // BotCommands - err = cherryPickTypeAlias(tdModelsPackage, tdFormsPackage, "BotCommands") - if err != nil { - return nil, err + return infoToFill, err } return infoToFill, nil } -func cherryPickTypeAlias(tdproto *TdPackage, tdapi *TdPackage, name string) error { - - pickObject, ok := tdapi.TdTypes[name] - if !ok { - return fmt.Errorf("failed to cherry pick query %s", name) - } - tdproto.TdTypes[name] = pickObject - - return nil -} - -func cherryPickQuery(tdproto *TdPackage, tdapi *TdPackage, name string) error { +func createTdProtoPackage(packageSlot **TdPackage, packageName string, allPackagesAst map[string]*ast.Package) error { + *packageSlot = new(TdPackage) + (*packageSlot).TdEvents = make(map[string]string) + (*packageSlot).TdStructs = make(map[string]TdStruct) + (*packageSlot).TdTypes = make(map[string]TdType) + (*packageSlot).TdMapTypes = make(map[string]TdMapType) + (*packageSlot).TdQueries = make(map[string]TdQuery) + (*packageSlot).Name = packageName - pickObject, ok := tdapi.TdStructs[name] - if !ok { - return fmt.Errorf("failed to cherry pick query %s", name) - } - - var newQuery TdQuery - - newQuery.Help = pickObject.Help - newQuery.ParamsNamesAndHelp = make(map[string]string) - newQuery.Name = name - for _, field := range pickObject.Fields { - newQuery.ParamsNamesAndHelp[field.SchemaName] = field.Help - } - - tdproto.TdQueries[name] = newQuery - - return nil -} - -func cherryPickStruct(tdproto *TdPackage, tdapi *TdPackage, name string) error { - - pickObject, ok := tdapi.TdStructs[name] - if !ok { - return fmt.Errorf("failed to cherry pick struct %s", name) + tdprotoAst := allPackagesAst[packageName] + err := parseTdprotoAst(tdprotoAst, *packageSlot, nil) + if err != nil { + return err } - tdproto.TdStructs[name] = pickObject return nil } @@ -387,12 +281,12 @@ func parseFunctionDeclaration(infoToFill *TdPackage, functionDeclaration *ast.Fu } returnStatementAst := functionDeclaration.Body.List[0].(*ast.ReturnStmt) - returnStatemetExpression, ok := returnStatementAst.Results[0].(*ast.BasicLit) + returnStatementExpression, ok := returnStatementAst.Results[0].(*ast.BasicLit) if !ok { return nil } - eventName := strings.Trim(returnStatemetExpression.Value, "\"") + eventName := strings.Trim(returnStatementExpression.Value, "\"") typeIdent := functionDeclaration.Recv.List[0].Type.(*ast.Ident) typeEventBelongsTo := typeIdent.Obj.Name @@ -453,13 +347,15 @@ func parseTypeDeclaration(infoToFill *TdPackage, genDeclaration *ast.GenDecl, de func parseMapTypeDeclaration(infoToFill *TdPackage, declarationSpec *ast.TypeSpec, mapAst *ast.MapType, helpString string, fileName string) error { typeName := declarationSpec.Name.Name + var keyPackageName, keyTypeStr string - keyTypeStr, err := parseExprToString(mapAst.Key) + err := parseExprToString(mapAst.Key, &keyPackageName, &keyTypeStr) if err != nil { return err } - valueTypeStr, err := parseExprToString(mapAst.Value) + var valuePackageName, valueTypeStr string + err = parseExprToString(mapAst.Value, &valuePackageName, &valueTypeStr) if err != nil { return err } @@ -470,6 +366,7 @@ func parseMapTypeDeclaration(infoToFill *TdPackage, declarationSpec *ast.TypeSpe ValueTypeStr: valueTypeStr, Help: helpString, Filename: fileName, + PackageName: infoToFill.Name, } return nil @@ -480,11 +377,12 @@ func parseArrayTypeDefinition(infoToFill *TdPackage, declarationSpec *ast.TypeSp arrayExpressionAst := arrayAst.Elt.(*ast.Ident) arrayTypeStr := arrayExpressionAst.Name infoToFill.TdTypes[typeName] = TdType{ - Name: typeName, - BaseType: arrayTypeStr, - IsArray: true, - Help: helpString, - Filename: fileName, + Name: typeName, + BaseType: arrayTypeStr, + IsArray: true, + Help: helpString, + Filename: fileName, + PackageName: infoToFill.Name, } return nil } @@ -492,10 +390,11 @@ func parseArrayTypeDefinition(infoToFill *TdPackage, declarationSpec *ast.TypeSp func parseTypeDefinition(infoToFill *TdPackage, declarationSpec *ast.TypeSpec, typeIndent *ast.Ident, helpString string, fileName string) error { typeName := declarationSpec.Name.Name infoToFill.TdTypes[typeName] = TdType{ - Name: typeName, - BaseType: typeIndent.Name, - Help: helpString, - Filename: fileName, + Name: typeName, + BaseType: typeIndent.Name, + Help: helpString, + Filename: fileName, + PackageName: infoToFill.Name, } return nil } @@ -588,6 +487,7 @@ func parseStructDefinitionInfo(infoToFill *TdPackage, declarationSpec *ast.TypeS isList := false isPointer := false fieldTypeStr := "" + fieldPackageName := "" keyTypeStr := "" switch fieldTypeAst := field.Type.(type) { @@ -602,7 +502,7 @@ func parseStructDefinitionInfo(infoToFill *TdPackage, declarationSpec *ast.TypeS case *ast.InterfaceType: fieldTypeStr = "interface{}" case *ast.SelectorExpr: - fieldTypeStr = parseSelectorAst(arrayTypeAst) + fieldPackageName, fieldTypeStr = parseSelectorAst(arrayTypeAst) default: return fmt.Errorf("unknown array type %#v", arrayTypeAst) } @@ -623,22 +523,22 @@ func parseStructDefinitionInfo(infoToFill *TdPackage, declarationSpec *ast.TypeS // TODO: Implement pointers to maps continue case *ast.SelectorExpr: - fieldTypeStr = parseSelectorAst(pointedType) + fieldPackageName, fieldTypeStr = parseSelectorAst(pointedType) default: return fmt.Errorf("unknown pointer field of %s type %#v", structName, pointedType) } case *ast.SelectorExpr: - fieldTypeStr = parseSelectorAst(fieldTypeAst) + fieldPackageName, fieldTypeStr = parseSelectorAst(fieldTypeAst) case *ast.InterfaceType: fieldTypeStr = "interface{}" case *ast.MapType: var err error - keyTypeStr, err = parseExprToString(fieldTypeAst.Key) + err = parseExprToString(fieldTypeAst.Key, &fieldPackageName, &fieldTypeStr) if err != nil { return err } - fieldTypeStr, err = parseExprToString(fieldTypeAst.Value) + err = parseExprToString(fieldTypeAst.Value, &fieldPackageName, &fieldTypeStr) if err != nil { return err } @@ -653,6 +553,10 @@ func parseStructDefinitionInfo(infoToFill *TdPackage, declarationSpec *ast.TypeS _, isPrimitive := GolangPrimitiveTypes[fieldTypeStr] + if fieldPackageName == "" && !isPrimitive { + fieldPackageName = infoToFill.Name + } + fieldsList = append(fieldsList, TdStructField{ Name: fieldName, IsReadOnly: isReadOnly, @@ -666,16 +570,18 @@ func parseStructDefinitionInfo(infoToFill *TdPackage, declarationSpec *ast.TypeS IsPrimitive: isPrimitive, IsNotSerialized: isNotSerialized, Help: fieldDoc, + PackageName: fieldPackageName, }) } infoToFill.TdStructs[structName] = TdStruct{ - Help: helpString, - ReadOnly: isReadOnly, - Name: structName, - Fields: fieldsList, - AnonnymousFields: anonymousFieldsList, - FileName: fileName, + Help: helpString, + ReadOnly: isReadOnly, + Name: structName, + Fields: fieldsList, + AnonymousFields: anonymousFieldsList, + FileName: fileName, + PackageName: infoToFill.Name, } return nil @@ -710,7 +616,7 @@ func parseConstDeclaration(infoToFill *TdPackage, genDeclaration *ast.GenDecl) e return fmt.Errorf("could not extract constant value %+v", valueSpec.Values[0]) } - infoToFill.TdConsts = append(infoToFill.TdConsts, TdConstFields{ + infoToFill.TdConstants = append(infoToFill.TdConstants, TdConstFields{ Name: constName, Type: constTypeName, Value: constValue.Value, @@ -721,46 +627,62 @@ func parseConstDeclaration(infoToFill *TdPackage, genDeclaration *ast.GenDecl) e return nil } -func parseExprToString(expr interface{}) (string, error) { +func parseExprToString(expr interface{}, packageName *string, expression *string) error { switch exprType := expr.(type) { case *ast.SelectorExpr: - return parseSelectorAst(exprType), nil + (*packageName), (*expression) = parseSelectorAst(exprType) + return nil case *ast.Ident: - return exprType.Name, nil + *packageName = "" + *expression = exprType.Name + return nil case *ast.InterfaceType: - return "interface{}", nil + *packageName = "" + *expression = "interface{}" + return nil case *ast.StarExpr: - return parseStarAst(exprType) + err := parseStarAst(exprType, packageName, expression) + if err != nil { + return err + } + return nil } - return "", fmt.Errorf("cannot parse expression %#v", expr) + return fmt.Errorf("cannot parse expression %#v", expr) } -func parseStarAst(starAst *ast.StarExpr) (string, error) { - pointedType, err := parseExprToString(starAst.X) +func parseStarAst(starAst *ast.StarExpr, packageName *string, expression *string) error { + err := parseExprToString(starAst.X, packageName, expression) if err != nil { - return "", err + return err } - return pointedType, nil + return nil } -func parseSelectorAst(selectorNode *ast.SelectorExpr) string { - expresionIdent := selectorNode.X.(*ast.Ident) - expressionStr := expresionIdent.Name - if expressionStr == "tdproto" { // HACK: when tdapi references tdproto - return selectorNode.Sel.Name - } - return expressionStr + "." + selectorNode.Sel.Name -} +func parseSelectorAst(selectorNode *ast.SelectorExpr) (string, string) { + expressionIdent := selectorNode.X.(*ast.Ident) + expressionStr := expressionIdent.Name -func extractTdprotoAst(fileSet *token.FileSet) (map[string]*ast.Package, error) { - tdProtoPath := tdproto.SourceDir() - return parser.ParseDir(fileSet, tdProtoPath, nil, parser.ParseComments) + return expressionStr, selectorNode.Sel.Name } -func extractTdapiAst(fileSet *token.FileSet) (map[string]*ast.Package, error) { +func extractTdprotoAst(packages *map[string]*ast.Package) error { + tdProtoPath := tdproto.SourceDir() - return parser.ParseDir(fileSet, path.Join(tdProtoPath, "tdapi"), nil, parser.ParseComments) + + for _, packageName := range []string{"", "tdforms", "tdevents", "tdquery"} { + fileSet := token.NewFileSet() + pkgs, err := parser.ParseDir(fileSet, path.Join(tdProtoPath, packageName), nil, parser.ParseComments) + if err != nil { + return err + } + + for key, value := range pkgs { + (*packages)[key] = value + } + } + + return nil } func cleanHelp(s string) string { diff --git a/codegen/inspect2.go b/codegen/inspect2.go new file mode 100644 index 0000000..ad729f1 --- /dev/null +++ b/codegen/inspect2.go @@ -0,0 +1,537 @@ +package codegen + +import ( + "fmt" + "go/ast" + "go/token" + "path" + "reflect" + "strings" +) + +const StringTypeName = "string" + +var golangePrimitiveToKind = map[string]reflect.Kind{ + "string": reflect.String, +} + +type TdPrimitive struct { + PrimitiveType reflect.Kind +} + +type TdRefrence struct { + Package string + Name string +} + +type TdElement struct { + PackageName string + FileName string + Help string +} + +type TdConstant struct { + TdElement + ConstValue string + ConstType interface{} +} + +type TdType2 struct { + TdElement + Type interface{} +} + +type TdTypeArray struct { + TdElement + ArrayType interface{} +} + +type TdTypeMap struct { + TdElement + KeyTypeStr string + KeyTypePackage string + ValueTypeStr string + ValueTypePackage string +} + +type TdStruct2 struct { + TdElement + Fields []TdStructField2 + AnonymousFields []string + TypeName string +} + +type TdStructField2 struct { + TdElement + FieldName string + TypeName string + JsonName string + SchemaName string + IsPrimitive bool + IsReadOnly bool + IsPointer bool + IsOmitEmpty bool + IsNotSerialized bool +} + +type TdPackage2 map[string]interface{} +type TdProto2 map[string]TdPackage2 + +type ParserState struct { + CurrentFile string + CurrentPackageName string + CurrentPackageMap *TdPackage2 +} + +func ParseTdproto2(infoToFill *TdProto2) error { + + allPackages := make(map[string]*ast.Package) + err := extractTdprotoAst(&allPackages) + if err != nil { + return err + } + + for packageName, packageAst := range allPackages { + newPackageMap := make(TdPackage2) + (*infoToFill)[packageName] = newPackageMap + err := parseAst(packageName, &newPackageMap, packageAst) + if err != nil { + return err + } + } + + return nil +} + +func parseAst(packageName string, packageMap *TdPackage2, packageAst *ast.Package) error { + for fileName, fileAst := range packageAst.Files { + + basePath := path.Base(fileName) + basePathNoExt := strings.TrimRight(basePath, path.Ext(basePath)) + + err := parseFileAst(ParserState{ + CurrentFile: basePathNoExt, + CurrentPackageName: packageName, + CurrentPackageMap: packageMap, + }, fileAst) + if err != nil { + return err + } + } + + return nil +} + +func parseFileAst(parser ParserState, fileAst *ast.File) error { + for _, declaration := range fileAst.Decls { + switch declarationType := declaration.(type) { + case *ast.GenDecl: + err := parseGenericDeclaration(parser, declarationType) + if err != nil { + return err + } + + } + + } + + return nil +} + +func parseGenericDeclaration(parser ParserState, genDeclaration *ast.GenDecl) error { + switch genDeclaration.Tok { + case token.CONST: + return parseConstDeclaration2(parser, genDeclaration) + case token.TYPE: + for _, aSpec := range genDeclaration.Specs { + aTypeSpec := aSpec.(*ast.TypeSpec) + err := parseTypeDeclaration2(parser, genDeclaration, aTypeSpec) + if err != nil { + return err + } + } + } + + return nil +} + +func parseConstDeclaration2(parser ParserState, genDeclaration *ast.GenDecl) error { + for _, spec := range genDeclaration.Specs { + valueSpec, ok := spec.(*ast.ValueSpec) + if !ok { + return fmt.Errorf("expected const spec got %+v", spec) + } + + if len(valueSpec.Names) != 1 { + return fmt.Errorf("expected one constant name got %+v", valueSpec.Names) + } + + var constKind reflect.Kind + + constName := valueSpec.Names[0].Name + + constTypeName := fmt.Sprintf("%s", valueSpec.Type) + if constTypeName == "" || valueSpec.Type == nil { + constKind = reflect.String + } + + if len(valueSpec.Values) != 1 { + return fmt.Errorf("expected one constant value got %+v", valueSpec.Values) + } + + var constValue string + + switch constExpr := valueSpec.Values[0]; constExpr.(type) { + case *ast.BasicLit: + constValue = constExpr.(*ast.BasicLit).Value + case *ast.CallExpr: + callExpr := constExpr.(*ast.CallExpr) + constTypeName = callExpr.Fun.(*ast.Ident).Name + constValue = callExpr.Fun.(*ast.Ident).Obj.Kind.String() + } + + if !ok { + return fmt.Errorf("could not extract constant value %+v", valueSpec.Values[0]) + } + + var constType interface{} + + if constKind != 0 { + constType = TdPrimitive{ + PrimitiveType: constKind, + } + } else { + constType = TdRefrence{ + Package: parser.CurrentPackageName, + Name: constTypeName, + } + } + + (*parser.CurrentPackageMap)[constName] = TdConstant{ + TdElement: TdElement{ + PackageName: parser.CurrentPackageName, + FileName: parser.CurrentFile, + Help: cleanHelp(valueSpec.Doc.Text()), + }, + ConstValue: constValue, + ConstType: constType, + } + + } + + return nil +} + +func parseTypeDeclaration2(parser ParserState, genDeclaration *ast.GenDecl, declarationSpec *ast.TypeSpec) error { + + helpString := cleanHelp(genDeclaration.Doc.Text()) + + switch typeAst := declarationSpec.Type.(type) { + case *ast.Ident: + err := parseTypeDefinition2(parser, declarationSpec, typeAst, helpString) + if err != nil { + return err + } + case *ast.StructType: + err := parseStructDefinition(parser, declarationSpec, typeAst, helpString) + if err != nil { + return err + } + case *ast.ArrayType: + err := parseArrayDefinition2(parser, declarationSpec, typeAst, helpString) + if err != nil { + return err + } + case *ast.MapType: + err := parseMapTypeDefinition(parser, declarationSpec, typeAst, helpString) + if err != nil { + return nil + } + default: + errorLogger.Printf("WARN: Not implemented type declaration %#v in file %s", typeAst, parser.CurrentFile) + } + + return nil +} + +func parseTypeDefinition2(parser ParserState, declarationSpec *ast.TypeSpec, typeIndent *ast.Ident, helpString string) error { + + typeName := declarationSpec.Name.Name + typeTypeName := typeIndent.Name + + typeKind, isPrimitive := golangePrimitiveToKind[typeTypeName] + + var typeType interface{} + if isPrimitive { + typeType = TdPrimitive{ + PrimitiveType: typeKind, + } + } else { + typeType = TdRefrence{ + Package: parser.CurrentPackageName, + Name: typeTypeName, + } + } + + (*parser.CurrentPackageMap)[typeName] = TdType2{ + TdElement: TdElement{ + + Help: helpString, + FileName: parser.CurrentFile, + PackageName: parser.CurrentPackageName, + }, + Type: typeType, + } + + return nil +} + +func parseArrayDefinition2(parser ParserState, declarationSpec *ast.TypeSpec, arrayAst *ast.ArrayType, helpString string) error { + typeName := declarationSpec.Name.Name + arrayExpressionAst := arrayAst.Elt.(*ast.Ident) + arrayTypeStr := arrayExpressionAst.Name + + typeKind, isPrimitive := golangePrimitiveToKind[arrayTypeStr] + + var arrayType interface{} + if isPrimitive { + arrayType = TdPrimitive{ + PrimitiveType: typeKind, + } + } else { + arrayType = TdRefrence{ + Package: parser.CurrentPackageName, + Name: arrayTypeStr, + } + } + + (*parser.CurrentPackageMap)[typeName] = TdTypeArray{ + TdElement: TdElement{ + + Help: helpString, + FileName: parser.CurrentFile, + PackageName: parser.CurrentPackageName, + }, + ArrayType: arrayType, + } + + return nil +} + +func parseMapTypeDefinition(parser ParserState, declarationSpec *ast.TypeSpec, mapAst *ast.MapType, helpString string) error { + typeName := declarationSpec.Name.Name + var keyPackageName, keyTypeStr string + + err := parseExprToString(mapAst.Key, &keyPackageName, &keyTypeStr) + if err != nil { + return err + } + + var valuePackageName, valueTypeStr string + err = parseExprToString(mapAst.Value, &valuePackageName, &valueTypeStr) + if err != nil { + return err + } + + (*parser.CurrentPackageMap)[typeName] = TdTypeMap{ + TdElement: TdElement{ + + Help: helpString, + FileName: parser.CurrentFile, + PackageName: parser.CurrentPackageName, + }, + KeyTypeStr: keyTypeStr, + KeyTypePackage: keyPackageName, + ValueTypeStr: valueTypeStr, + ValueTypePackage: valuePackageName, + } + + return nil +} + +func parseStructDefinition(parser ParserState, declarationSpec *ast.TypeSpec, structInfo *ast.StructType, helpString string) error { + structName := declarationSpec.Name.Name + + if helpString == "" { + errorLogger.Printf("WARN: TdStruct %s missing a doc string in file %s", structName, parser.CurrentFile) + } + + if strings.HasPrefix(strings.ToLower(helpString), "deprecated") { + return nil + } + + var fieldsList []TdStructField2 + var anonymousFieldsList []string + + for _, field := range structInfo.Fields.List { + switch len(field.Names) { + case 0: + anonymousIdent := field.Type.(*ast.Ident) + anonymousFieldName := anonymousIdent.Name + anonymousFieldsList = append(anonymousFieldsList, anonymousFieldName) + continue + case 1: + default: + return fmt.Errorf("unexpected struct %s field name amount of %d", structName, len(field.Names)) + } + + fieldName := field.Names[0].Name + isOmitEmpty := false + isReadOnly := false + isNotSerialized := false + jsonName := fieldName + fieldDoc := cleanHelp(field.Doc.Text()) + var schemaName string + + if field.Tag != nil { + structTags := reflect.StructTag(strings.Trim(field.Tag.Value, "`")) + + var jsonTags []string + if jsonTagsStr, ok := structTags.Lookup("json"); ok { + jsonTags = strings.Split(jsonTagsStr, ",") + } + + for i, aTag := range jsonTags { + if i == 0 { + if aTag == "-" { + isNotSerialized = true + } + + jsonName = aTag + } else { + if aTag == "omitempty" { + isOmitEmpty = true + } else { + return fmt.Errorf("unknown json tag %s", aTag) + } + } + } + + var tdprotoTags []string + tdprotoTagsStr, ok := structTags.Lookup("tdproto") + if ok { + tdprotoTags = strings.Split(tdprotoTagsStr, ",") + } + + for _, aTag := range tdprotoTags { + if aTag == "readonly" { + isReadOnly = true + } else { + return fmt.Errorf("unknown tdproto tag %s", aTag) + } + } + + var schemaTags []string + schemaTagsStr, ok := structTags.Lookup("schema") + if ok { + schemaTags = strings.Split(schemaTagsStr, ",") + } + + for _, sTag := range schemaTags { + schemaName = sTag + } + } + + // isList := false + isPointer := false + fieldTypeStr := "" + fieldPackageName := "" + // keyTypeStr := "" + + switch fieldTypeAst := field.Type.(type) { + case *ast.Ident: + fieldTypeStr = fieldTypeAst.Name + case *ast.ArrayType: + // isList = true + + switch arrayTypeAst := fieldTypeAst.Elt.(type) { + case *ast.Ident: + fieldTypeStr = arrayTypeAst.Name + case *ast.InterfaceType: + fieldTypeStr = "interface{}" + case *ast.SelectorExpr: + fieldPackageName, fieldTypeStr = parseSelectorAst(arrayTypeAst) + default: + return fmt.Errorf("unknown array type %#v", arrayTypeAst) + } + + case *ast.StarExpr: + isPointer = true + + switch pointedType := fieldTypeAst.X.(type) { + case *ast.Ident: + fieldTypeStr = pointedType.Name + case *ast.ArrayType: + // isList = true + + arrayExprAst := pointedType.Elt.(*ast.Ident) + + fieldTypeStr = arrayExprAst.Name + case *ast.MapType: + // TODO: Implement pointers to maps + continue + case *ast.SelectorExpr: + fieldPackageName, fieldTypeStr = parseSelectorAst(pointedType) + default: + return fmt.Errorf("unknown pointer field of %s type %#v", structName, pointedType) + } + + case *ast.SelectorExpr: + fieldPackageName, fieldTypeStr = parseSelectorAst(fieldTypeAst) + case *ast.InterfaceType: + fieldTypeStr = "interface{}" + case *ast.MapType: + var err error + err = parseExprToString(fieldTypeAst.Key, &fieldPackageName, &fieldTypeStr) + if err != nil { + return err + } + err = parseExprToString(fieldTypeAst.Value, &fieldPackageName, &fieldTypeStr) + if err != nil { + return err + } + default: + return fmt.Errorf("unknown field of %s type %#v", structName, fieldTypeAst) + } + + if fieldTypeStr == "" { + return fmt.Errorf("empty field name %s of %s", structName, fieldName) + + } + + _, isPrimitive := GolangPrimitiveTypes[fieldTypeStr] + + if fieldPackageName == "" && !isPrimitive { + fieldPackageName = parser.CurrentPackageName + } + + fieldsList = append(fieldsList, TdStructField2{ + TdElement: TdElement{ + Help: fieldDoc, + PackageName: fieldPackageName, + FileName: parser.CurrentFile, + }, + FieldName: fieldName, + IsReadOnly: isReadOnly, + IsOmitEmpty: isOmitEmpty, + JsonName: jsonName, + SchemaName: schemaName, + IsPointer: isPointer, + IsPrimitive: isPrimitive, + IsNotSerialized: isNotSerialized, + }) + } + + (*parser.CurrentPackageMap)[structName] = TdStruct2{ + TdElement: TdElement{ + Help: helpString, + PackageName: parser.CurrentPackageName, + FileName: parser.CurrentFile, + }, + TypeName: structName, + Fields: fieldsList, + AnonymousFields: anonymousFieldsList, + } + + return nil +} diff --git a/codegen/inspect_test.go b/codegen/inspect_test.go index 641f08c..f13b1cf 100644 --- a/codegen/inspect_test.go +++ b/codegen/inspect_test.go @@ -4,10 +4,12 @@ import ( "testing" ) -func TestParsing(t *testing.T) { - _, err := ParseTdproto() +func TestParsing2(t *testing.T) { + tdproto := make(TdProto2) + + err := ParseTdproto2(&tdproto) if err != nil { - t.Error(err) + t.Fatal(err) } } diff --git a/codegen/sphinx/events/main.go b/codegen/sphinx/events/main.go index 5fe67d1..3971fb7 100644 --- a/codegen/sphinx/events/main.go +++ b/codegen/sphinx/events/main.go @@ -16,7 +16,7 @@ func main() { panic(err) } - clientEvents, serverEvents, err := generateRstServerEvents(tdprotoInfo.TdModels) + clientEvents, serverEvents, err := generateRstServerEvents(tdprotoInfo) if err != nil { panic(err) } @@ -39,17 +39,16 @@ type rstEvent struct { Fields []rstEventField } -func generateRstServerEvents(tdprotoInfo *codegen.TdPackage) (clientEvents []rstEvent, serverEvents []rstEvent, err error) { - for eventStructName, eventStr := range tdprotoInfo.TdEvents { +func generateRstServerEvents(tdprotoInfo *codegen.TdProto) (clientEvents []rstEvent, serverEvents []rstEvent, err error) { + for eventStructName, eventStr := range tdprotoInfo.TdEvents.TdEvents { eventExample, ok := eventExampleStr[eventStr] if !ok { eventExample = "" } - originalStruct, ok := tdprotoInfo.TdStructs[eventStructName] + originalStruct, ok := tdprotoInfo.TdEvents.TdStructs[eventStructName] if !ok { - fmt.Fprintf(os.Stderr, "Failed to find struct %s of event %s.\n", eventStructName, eventStr) - continue + return clientEvents, serverEvents, fmt.Errorf("failed to find struct %s of event %s", eventStructName, eventStr) } eventExampleFormatted := strings.ReplaceAll(eventExample, "\n", "\n ") @@ -64,16 +63,26 @@ func generateRstServerEvents(tdprotoInfo *codegen.TdPackage) (clientEvents []rst var paramsStruct codegen.TdStruct for _, originalField := range originalStruct.Fields { - if originalField.Name == "Params" { - paramsStruct, ok = tdprotoInfo.TdStructs[originalField.TypeStr] - if !ok { - fmt.Fprintf(os.Stderr, "Failed to find parameter type %s of event %s.\n", originalField.TypeStr, eventStructName) - continue - } + if originalField.Name != "Params" { + continue } + switch originalField.PackageName { + case "tdevents": + paramsStruct, ok = tdprotoInfo.TdEvents.TdStructs[originalField.TypeStr] + case "tdproto": + paramsStruct, ok = tdprotoInfo.TdModels.TdStructs[originalField.TypeStr] + default: + ok = false + } + + if !ok { + fmt.Fprintf(os.Stderr, "Failed to find struct %s of event %s.\n", eventStructName, eventStr) + continue + } + } - for _, paramField := range paramsStruct.GetAllJsonFields(tdprotoInfo) { + for _, paramField := range paramsStruct.GetAllJsonFields(tdprotoInfo.TdEvents) { fieldHelp := paramField.Help if fieldHelp == "" { fieldHelp = "DOCUMENTATION MISSING" diff --git a/codegen/sphinx/json_index/main.go b/codegen/sphinx/json_index/main.go index 4a6f3a0..7e8b317 100644 --- a/codegen/sphinx/json_index/main.go +++ b/codegen/sphinx/json_index/main.go @@ -17,7 +17,12 @@ func main() { panic(err) } - err = generateRstJson(tdprotoInfo.TdModels) + err = generateRstJson(tdprotoInfo.TdModels, "tdmodels") + if err != nil { + panic(err) + } + + err = generateRstJson(tdprotoInfo.TdForms, "tdforms") if err != nil { panic(err) } @@ -58,9 +63,17 @@ type rstJsonStruct struct { Fields []rstJsonField } +type rstEnum struct { + codegen.TdEnum +} + +type rstType struct { + codegen.TdType +} + var jsonTemplate = template.Must(template.New("rstJson").Parse(` .. tdproto:struct:: {{.TdStruct.Name}} - :tdpackage: tdmodels + :tdpackage: {{.PackageName}} {{.TdStruct.Help}} {{range $field := .Fields}} @@ -69,7 +82,7 @@ var jsonTemplate = template.Must(template.New("rstJson").Parse(` var enumTemplate = template.Must(template.New("rstEnum").Parse(` .. tdproto:enum:: {{.Name}} - :tdpackage: tdmodels + :tdpackage: {{.PackageName}} **Possible values**: {{range $value := .Values}} @@ -79,7 +92,7 @@ var enumTemplate = template.Must(template.New("rstEnum").Parse(` var typeAliasTemplate = template.Must(template.New("rstType").Parse(` .. tdproto:type:: {{.Name}} - :tdpackage: tdmodels + :tdpackage: {{.PackageName}} {{if .Help}} {{.Help}} @@ -109,46 +122,58 @@ func isEventStruct(structName string, tdprotoInfo *codegen.TdPackage) bool { return isEvent } -func generateRstJson(tdprotoInfo *codegen.TdPackage) error { +func generateEnumsRst(enumsList []codegen.TdEnum, tdPackageName string, enumedTypeAliases *map[string]string) error { - enumedTypeAliases := make(map[string]string) + fmt.Fprintf(os.Stdout, "\n%s enums index\n============================\n", tdPackageName) - fmt.Fprintln(os.Stdout, "\nEnums index\n============================") - enumsList := tdprotoInfo.GetEnums() sort.Slice(enumsList, func(i, j int) bool { return strings.ToLower(enumsList[i].Name) < strings.ToLower(enumsList[j].Name) }) for _, enum := range enumsList { - err := enumTemplate.Execute(os.Stdout, enum) + err := enumTemplate.Execute(os.Stdout, rstEnum{ + TdEnum: enum, + }) if err != nil { return err } - enumedTypeAliases[enum.Name] = "" + (*enumedTypeAliases)[enum.Name] = "" } - fmt.Fprintln(os.Stdout, "\nType aliases\n============================") + return nil +} + +func generateTypeAliasesRst(tdPackage *codegen.TdPackage, tdPackageName string, enumedTypeAliases *map[string]string) error { + + fmt.Fprintf(os.Stdout, "\n%s type aliases\n============================\n", tdPackageName) var typesList []codegen.TdType - for _, someType := range tdprotoInfo.TdTypes { + for _, someType := range tdPackage.TdTypes { typesList = append(typesList, someType) } sort.Slice(typesList, func(i, j int) bool { return strings.ToLower(typesList[i].Name) < strings.ToLower(typesList[j].Name) }) for _, typeAlias := range typesList { - _, isEnumed := enumedTypeAliases[typeAlias.Name] + _, isEnumed := (*enumedTypeAliases)[typeAlias.Name] if isEnumed { continue } - err := typeAliasTemplate.Execute(os.Stdout, typeAlias) + err := typeAliasTemplate.Execute(os.Stdout, rstType{ + TdType: typeAlias, + }) if err != nil { return err } } + return nil +} + +func generateStructsRst(tdPackage *codegen.TdPackage, tdPackageName string, enumedTypeAliases *map[string]string) error { + var jsonObjects []rstJsonStruct - for _, tdStruct := range tdprotoInfo.TdStructs { + for _, tdStruct := range tdPackage.TdStructs { if tdStruct.Help == "" { // Do not print structures without help continue @@ -159,11 +184,11 @@ func generateRstJson(tdprotoInfo *codegen.TdPackage) error { continue } - if isEventStruct(tdStruct.Name, tdprotoInfo) { + if isEventStruct(tdStruct.Name, tdPackage) { continue } - if tdStruct.IsEventParams(tdprotoInfo) { + if tdStruct.IsEventParams(tdPackage) { continue } @@ -173,7 +198,7 @@ func generateRstJson(tdprotoInfo *codegen.TdPackage) error { fieldMissingHelp := false - for _, field := range tdStruct.GetAllJsonFields(tdprotoInfo) { + for _, field := range tdStruct.GetAllJsonFields(tdPackage) { if field.IsNotSerialized { continue } @@ -215,7 +240,7 @@ func generateRstJson(tdprotoInfo *codegen.TdPackage) error { return strings.ToLower(jsonObjects[i].Name) < strings.ToLower(jsonObjects[j].Name) }) - fmt.Fprintln(os.Stdout, "\nJSON objects index\n============================") + fmt.Fprintf(os.Stdout, "\n%s JSON objects index\n============================\n", tdPackageName) for _, object := range jsonObjects { err := jsonTemplate.Execute(os.Stdout, object) @@ -224,9 +249,13 @@ func generateRstJson(tdprotoInfo *codegen.TdPackage) error { } } - fmt.Fprintln(os.Stdout, "\nHTTP Queries\n============================") + return nil +} + +func generateQueryRst(tdPackage *codegen.TdPackage, tdPackageName string) error { + fmt.Fprintf(os.Stdout, "\n%s HTTP Queries\n============================\n", tdPackageName) - for _, query := range tdprotoInfo.TdQueries { + for _, query := range tdPackage.TdQueries { err := httpQueryTemplate.Execute(os.Stdout, query) if err != nil { return err @@ -235,3 +264,38 @@ func generateRstJson(tdprotoInfo *codegen.TdPackage) error { return nil } + +func generateRstJson(tdPackage *codegen.TdPackage, tdPackageName string) error { + + enumedTypeAliases := make(map[string]string) + enumsList := tdPackage.GetEnums() + + if len(enumsList) > 0 { + err := generateEnumsRst(enumsList, tdPackageName, &enumedTypeAliases) + if err != nil { + return err + } + } + + if len(tdPackage.TdTypes) > 0 { + err := generateTypeAliasesRst(tdPackage, tdPackageName, &enumedTypeAliases) + if err != nil { + return err + } + } + if len(tdPackage.TdStructs) > 0 { + err := generateStructsRst(tdPackage, tdPackageName, &enumedTypeAliases) + if err != nil { + return err + } + } + + if len(tdPackage.TdQueries) > 0 { + err := generateQueryRst(tdPackage, tdPackageName) + if err != nil { + return err + } + } + + return nil +} diff --git a/codegen/typescript/main.go b/codegen/typescript/main.go index bc8d679..ac1fe7a 100644 --- a/codegen/typescript/main.go +++ b/codegen/typescript/main.go @@ -29,7 +29,7 @@ var tsTypesMap = map[string]string{ "bool": "boolean", "interface{}": "any", "ISODateTimeString": "string", - "time.Time": "string", + "Time": "string", "UiSettings": "UiSettings", } diff --git a/paginated.go b/paginated.go deleted file mode 100644 index 4cf7525..0000000 --- a/paginated.go +++ /dev/null @@ -1,39 +0,0 @@ -package tdproto - -// Paginated chats -type PaginatedChats struct { - Contacts []Contact `json:"contacts,omitempty"` - Objects []Chat `json:"objects"` - Count int `json:"count"` - Limit int `json:"limit"` - Offset int `json:"offset"` -} - -// Paginated messages -type PaginatedMessages struct { - Objects []Message `json:"objects"` - Count int `json:"count"` - Limit int `json:"limit"` - Offset int `json:"offset"` -} - -// Paginated contacts -type PaginatedContacts struct { - Objects []Contact `json:"objects"` - Count int `json:"count"` - Limit int `json:"limit"` - Offset int `json:"offset"` -} - -// Chat messages -type ChatMessages struct { - Messages []Message `json:"messages"` -} - -// Paginated UploadShortMessage -type PaginatedUploadShortMessages struct { - Objects []UploadShortMessage `json:"objects"` - Count int `json:"count"` - Limit int `json:"limit"` - Offset int `json:"offset"` -} diff --git a/server_roster.go b/server_roster.go deleted file mode 100644 index 0f4e5b1..0000000 --- a/server_roster.go +++ /dev/null @@ -1,16 +0,0 @@ -package tdproto - -// deprecated -func NewServerRoster(roster Roster) (r ServerRoster) { - r.Name = r.GetName() - r.Params = roster - return r -} - -// deprecated -type ServerRoster struct { - BaseEvent - Params Roster `json:"params"` -} - -func (p ServerRoster) GetName() string { return "server.roster" } diff --git a/tdapi/auth.go b/tdapi/auth.go deleted file mode 100644 index dfe59f0..0000000 --- a/tdapi/auth.go +++ /dev/null @@ -1,105 +0,0 @@ -package tdapi - -import "github.com/tada-team/tdproto" - -// RecoveryStatus: -const ( - Unknown2fa = "unknown" - Unconfirmed2fa = "unconfirmed" - Confirmed2fa = "confirmed" - Declined2fa = "declined" -) - -type Auth struct { - Token string `json:"token,omitempty"` - Me tdproto.UserWithMe `json:"me"` - Required2fa bool `json:"required2fa"` - Recovery2fa bool `json:"recovery2fa"` - Method2fa string `json:"method2fa"` -} - -type Auth2faSettingsResponse struct { - Enabled bool `json:"enabled"` - RecoveryStatus string `json:"recovery_status"` -} - -type Auth2faMailRecovery struct { - CodeValidUntil tdproto.ISODateTimeString `json:"code_valid_until"` - NextCodeAt tdproto.ISODateTimeString `json:"next_code_at"` - CodeLength int `json:"code_length"` - Email string `json:"email"` -} - -type Auth2faSettingsMailValidation struct { - Enabled bool `json:"enabled"` - RecoveryStatus string `json:"recovery_status"` - CodeValidUntil tdproto.ISODateTimeString `json:"code_valid_until"` - NextCodeAt string `json:"next_code_at"` - CodeLength int `json:"code_length"` -} - -type basicPasswordUpdate struct { - NewPassword string `json:"new_password"` - NewPasswordRepeat string `json:"new_password_repeat"` - Hint string `json:"hint"` -} - -type basicToken struct { - Token string `json:"token"` -} - -type basicPassword struct { - Password string `json:"password"` -} - -type basicEmail struct { - Email string `json:"email"` -} - -type basicCode struct { - Code string `json:"code"` -} - -type Auth2faForm struct { - basicToken - basicPassword -} - -type Create2faPasswordForm struct { - basicPasswordUpdate -} - -type Update2faPasswordForm struct { - basicPasswordUpdate - basicPassword -} - -type Internal2faPasswordForm struct { - basicPassword -} - -type SendMail2faConfirmForm struct { - basicPassword - basicEmail -} - -type ConfirmMail2faForm struct { - basicPassword - basicCode - basicEmail -} - -type AuthToken2faForm struct { - basicToken -} - -type AuthCheckCode2faForm struct { - basicToken - basicCode -} - -type AuthPasswordRecovery2faForm struct { - basicPasswordUpdate - basicToken - basicCode -} diff --git a/tdapi/main.go b/tdapi/main.go deleted file mode 100644 index 0083e04..0000000 --- a/tdapi/main.go +++ /dev/null @@ -1,16 +0,0 @@ -package tdapi - -type PathSpec struct { - Input interface{} - Output interface{} -} - -var Paths = make(map[string]PathSpec) - -func registerPath(path string, spec PathSpec) { - - if _, ok := Paths[path]; ok { - panic("path already registered") - } - Paths[path] = spec -} diff --git a/tdapi/mixins.go b/tdapi/mixins.go deleted file mode 100644 index d4de080..0000000 --- a/tdapi/mixins.go +++ /dev/null @@ -1,11 +0,0 @@ -package tdapi - -type Paginator struct { - Limit int `schema:"limit"` - Offset int `schema:"offset"` -} - -type UserParams struct { - Lang string `schema:"lang"` - Timezone string `schema:"timezone"` -} diff --git a/tdapi/releases.go b/tdapi/releases.go deleted file mode 100644 index 6827b21..0000000 --- a/tdapi/releases.go +++ /dev/null @@ -1,10 +0,0 @@ -package tdapi - -import "github.com/tada-team/tdproto" - -type ReleasesResp struct { - Android []tdproto.Dist `json:"android,omitempty"` - Linux []tdproto.Dist `json:"linux,omitempty"` - Mac []tdproto.Dist `json:"mac,omitempty"` - Win []tdproto.Dist `json:"win,omitempty"` -} diff --git a/tdapi/resp.go b/tdapi/resp.go deleted file mode 100644 index 151feea..0000000 --- a/tdapi/resp.go +++ /dev/null @@ -1,27 +0,0 @@ -package tdapi - -import "github.com/tada-team/tdproto" - -// Server response -type Resp struct { - // Request status - Ok bool `json:"ok"` - - // Result only if ok is true) - Result interface{} `json:"result,omitempty"` - - // Error (only if ok is false) - Error Err `json:"error,omitempty"` - - // Error (only if ok is false and Error is 'InvalidData') - Details map[string]string `json:"details,omitempty"` - - // Reason (only if ok is false and Error is `AccessDenied`) - Reason string `json:"reason,omitempty"` - - // Reason markup (only if ok is false and Error is `AccessDenied`) - Markup []tdproto.MarkupEntity `json:"markup,omitempty"` - - // Server side work time - DebugTime string `json:"_time,omitempty"` -} diff --git a/tdapi/task.go b/tdapi/task.go deleted file mode 100644 index 5f1e75c..0000000 --- a/tdapi/task.go +++ /dev/null @@ -1,130 +0,0 @@ -package tdapi - -import "github.com/tada-team/tdproto" - -// Task -type Task struct { - // Custom task color - CustomColorIndex *uint16 `json:"custom_color_index,omitempty"` - - // Task description - Description string `json:"description,omitempty"` - - // Task tags - Tags []string `json:"tags,omitempty"` - - // Task section UID - SectionUid string `json:"section,omitempty"` - - // User who follow the task - Observers []tdproto.JID `json:"observers,omitempty"` // TODO: rename to "followers" - - // Items of the task - Items []string `json:"items,omitempty"` - - // User who was assigned the task - Assignee tdproto.JID `json:"assignee,omitempty"` - - // Deadline time, if any - Deadline tdproto.ISODateTimeString `json:"deadline,omitempty"` - - // Is task or group public for non-guests - Public bool `json:"public,omitempty"` - - // Fire a reminder at this time - RemindAt tdproto.ISODateTimeString `json:"remind_at,omitempty"` - - // Task status - TaskStatus string `json:"task_status,omitempty"` - - // Task importance - Importance *int `json:"importance,omitempty"` - - // Task urgency - Urgency *int `json:"urgency,omitempty"` - - // Task complexity - Complexity *int `json:"complexity,omitempty"` - - // Time spent - SpentTime *int `json:"spent_time,omitempty"` - - // Linked messages - LinkedMessages []string `json:"linked_messages,omitempty"` // TODO: Message object - - // Task uploads - Uploads []string `json:"uploads,omitempty"` -} - -// Query parameters for listing messages -type TaskFilter struct { - UserParams - Paginator - - //* ?sort = [ "created" | "-created" | "last_message" | "-last_message" | "deadline" | "-deadline" ] - Sort string `schema:"sort"` - - //* ?task_status = new,done | new | any - TaskStatus string `schema:"task_status"` - - //* ?exclude_task_status = new,done | new | any - ExcludeTaskStatus string `schema:"exclude_task_status"` - - //* ?num=num1,num2,num3... - Num string `schema:"num"` - - //* ?observer=jid,jid // TODO: rename to ?follower= - Observer string `schema:"observer"` - - //* ?member=jid,jid - Member string `schema:"member"` - - //* ?assignee=jid,jid - Assignee string `schema:"assignee"` - - //* ?owner=jid,jid - Owner string `schema:"owner"` - - //* ?section=[ uid,uid... | "-" ] - Section string `schema:"section"` // TODO: rename to ?project= - - //* ?tag=[ tag,tag,tag... | "-" ] - Tag string `schema:"tag"` - - //* ?q= - Q string `schema:"q"` - - //* ?public=true|false - Public string `schema:"public"` - - //* ?deadline_gte= - DeadlineGTE string `schema:"deadline_gte"` - - //* ?deadline_lte= - DeadlineLTE string `schema:"deadline_lte"` - - //* ?done_gte= - DoneGTE string `schema:"done_gte"` - - //* ?done_lte= - DoneLTE string `schema:"done_lte"` - - //* ?created_gte= - CreatedGTE string `schema:"created_gte"` - - //* ?created_lte= - CreatedLTE string `schema:"created_lte"` - - //* ?short=true|false - Short string `schema:"short"` - - // gentime great than group/chat - GentimeGT int64 `schema:"gentime_gt"` -} - -// Task cards colors -type TaskColors struct { - // Color list - Colors []tdproto.TaskColor `json:"colors"` -} - diff --git a/tdapi/timezones.go b/tdapi/timezones.go deleted file mode 100644 index c667be5..0000000 --- a/tdapi/timezones.go +++ /dev/null @@ -1,6 +0,0 @@ -package tdapi - -type TimezonesResp struct { - // List of timezones - Timezones []string `json:"timezones"` -} diff --git a/tdevents/Readme.md b/tdevents/Readme.md new file mode 100644 index 0000000..d639157 --- /dev/null +++ b/tdevents/Readme.md @@ -0,0 +1 @@ +Websocket events. diff --git a/client_activity.go b/tdevents/client_activity.go similarity index 96% rename from client_activity.go rename to tdevents/client_activity.go index 8b206a8..63f0a8e 100644 --- a/client_activity.go +++ b/tdevents/client_activity.go @@ -1,4 +1,4 @@ -package tdproto +package tdevents func NewClientActivity(afk bool) (r ClientActivity) { r.Name = r.GetName() diff --git a/client_call_buzz.go b/tdevents/client_call_buzz.go similarity index 69% rename from client_call_buzz.go rename to tdevents/client_call_buzz.go index 24ac226..7b0be1e 100644 --- a/client_call_buzz.go +++ b/tdevents/client_call_buzz.go @@ -1,6 +1,7 @@ -package tdproto +package tdevents + +import "github.com/tada-team/tdproto" -// deprecated: use http api type ClientCallBuzz struct { BaseEvent Params clientCallBuzzParams `json:"params"` @@ -11,8 +12,8 @@ func (p ClientCallBuzz) GetName() string { return "client.call.buzz" } // Call buzzing type clientCallBuzzParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // List of call participants. Empty value means all participants in call - Members []JID `json:"members,omitempty"` + Members []tdproto.JID `json:"members,omitempty"` } diff --git a/client_call_buzzcancel.go b/tdevents/client_call_buzzcancel.go similarity index 78% rename from client_call_buzzcancel.go rename to tdevents/client_call_buzzcancel.go index 4c63ab4..1af8859 100644 --- a/client_call_buzzcancel.go +++ b/tdevents/client_call_buzzcancel.go @@ -1,4 +1,6 @@ -package tdproto +package tdevents + +import "github.com/tada-team/tdproto" // Call buzzing cancelled type ClientCallBuzzCancel struct { @@ -11,5 +13,5 @@ func (p ClientCallBuzzCancel) GetName() string { return "client.call.buzzcancel" // Params of the client.call.buzzcancel event type clientCallBuzzCancelParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` } diff --git a/client_call_leave.go b/tdevents/client_call_leave.go similarity index 79% rename from client_call_leave.go rename to tdevents/client_call_leave.go index 459de34..8927b44 100644 --- a/client_call_leave.go +++ b/tdevents/client_call_leave.go @@ -1,4 +1,6 @@ -package tdproto +package tdevents + +import "github.com/tada-team/tdproto" // Leave call type ClientCallLeave struct { @@ -11,7 +13,7 @@ func (p ClientCallLeave) GetName() string { return "client.call.leave" } // Params of the client.call.leave event type clientCallLeaveParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Reason, if any Reason string `json:"reason,omitempty"` diff --git a/client_call_muteall.go b/tdevents/client_call_muteall.go similarity index 78% rename from client_call_muteall.go rename to tdevents/client_call_muteall.go index 37b31ce..7163205 100644 --- a/client_call_muteall.go +++ b/tdevents/client_call_muteall.go @@ -1,4 +1,6 @@ -package tdproto +package tdevents + +import "github.com/tada-team/tdproto" // Mute all other call participants type ClientCallMuteAll struct { @@ -11,5 +13,5 @@ func (p ClientCallMuteAll) GetName() string { return "client.call.muteall" } // Params of the client.call.muteall event type clientCallMuteAllParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` } diff --git a/client_call_offer.go b/tdevents/client_call_offer.go similarity index 84% rename from client_call_offer.go rename to tdevents/client_call_offer.go index 29fc377..84d7404 100644 --- a/client_call_offer.go +++ b/tdevents/client_call_offer.go @@ -1,4 +1,6 @@ -package tdproto +package tdevents + +import "github.com/tada-team/tdproto" // Start a call type ClientCallOffer struct { @@ -11,7 +13,7 @@ func (p ClientCallOffer) GetName() string { return "client.call.offer" } // Params of the client.call.offer event type clientCallOfferParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Mute state Muted bool `json:"muted"` diff --git a/client_call_reject.go b/tdevents/client_call_reject.go similarity index 80% rename from client_call_reject.go rename to tdevents/client_call_reject.go index 12b48b7..fc167e1 100644 --- a/client_call_reject.go +++ b/tdevents/client_call_reject.go @@ -1,4 +1,6 @@ -package tdproto +package tdevents + +import "github.com/tada-team/tdproto" // Reject the call type ClientCallReject struct { @@ -11,7 +13,7 @@ func (p ClientCallReject) GetName() string { return "client.call.reject" } // Params of the client.call.reject event type clientCallRejectParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Reason, if any Reason string `json:"reason,omitempty"` diff --git a/client_call_sdp.go b/tdevents/client_call_sdp.go similarity index 77% rename from client_call_sdp.go rename to tdevents/client_call_sdp.go index b7f2b51..180d16a 100644 --- a/client_call_sdp.go +++ b/tdevents/client_call_sdp.go @@ -1,4 +1,6 @@ -package tdproto +package tdevents + +import "github.com/tada-team/tdproto" // For exchange Session Description with server when client's Local Session Description is changed type ClientCallSdp struct { @@ -11,11 +13,11 @@ func (p ClientCallSdp) GetName() string { return "client.call.sdp" } // Params of the client.call.sdp event type clientCallSdpParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Call id Uid string `json:"uid"` // SDP data - JSEP JSEP `json:"jsep"` + JSEP tdproto.JSEP `json:"jsep"` } diff --git a/client_call_sound.go b/tdevents/client_call_sound.go similarity index 79% rename from client_call_sound.go rename to tdevents/client_call_sound.go index a3a9a6f..007b666 100644 --- a/client_call_sound.go +++ b/tdevents/client_call_sound.go @@ -1,4 +1,6 @@ -package tdproto +package tdevents + +import "github.com/tada-team/tdproto" // Change mute state in call type ClientCallSound struct { @@ -11,7 +13,7 @@ func (p ClientCallSound) GetName() string { return "client.call.sound" } // Params of the client.call.sound event type clientCallSoundParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Mute state Muted bool `json:"muted"` diff --git a/client_call_trickle.go b/tdevents/client_call_trickle.go similarity index 85% rename from client_call_trickle.go rename to tdevents/client_call_trickle.go index f3719c4..9feccbc 100644 --- a/client_call_trickle.go +++ b/tdevents/client_call_trickle.go @@ -1,4 +1,6 @@ -package tdproto +package tdevents + +import "github.com/tada-team/tdproto" // Send trickle candidate for webrtc connection type ClientCallTrickle struct { @@ -11,7 +13,7 @@ func (p ClientCallTrickle) GetName() string { return "client.call.trickle" } // Params of client.call.trickle event type clientCallTrickleParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Trickle candidate Candidate string `json:"candidate"` diff --git a/client_chat_composing.go b/tdevents/client_chat_composing.go similarity index 78% rename from client_chat_composing.go rename to tdevents/client_chat_composing.go index cf1e0a3..829f159 100644 --- a/client_chat_composing.go +++ b/tdevents/client_chat_composing.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewClientChatComposing(jid JID, composing bool, draft *string) (r ClientChatComposing) { +import "github.com/tada-team/tdproto" + +func NewClientChatComposing(jid tdproto.JID, composing bool, draft *string) (r ClientChatComposing) { r.Name = r.GetName() r.Params.Jid = jid r.Params.Composing = composing @@ -19,7 +21,7 @@ func (p ClientChatComposing) GetName() string { return "client.chat.composing" } // Params of the client.chat.composing event type clientChatComposingParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // true = audiomessage, false = text typing IsAudio bool `json:"is_audio,omitempty"` diff --git a/client_chat_lastread.go b/tdevents/client_chat_lastread.go similarity index 76% rename from client_chat_lastread.go rename to tdevents/client_chat_lastread.go index 6807076..7647e29 100644 --- a/client_chat_lastread.go +++ b/tdevents/client_chat_lastread.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewClientChatLastread(jid JID, messageId *string) (r ClientChatLastread) { +import "github.com/tada-team/tdproto" + +func NewClientChatLastread(jid tdproto.JID, messageId *string) (r ClientChatLastread) { r.Name = r.GetName() r.ConfirmId = ConfirmId() r.Params.Jid = jid @@ -19,7 +21,7 @@ func (p ClientChatLastread) GetName() string { return "client.chat.lastread" } // Params of the client.chat.lastread event type clientChatLastreadParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Last read message id. Omitted = last message in chat LastReadMessageId *string `json:"last_read_message_id,omitempty"` diff --git a/client_confirm.go b/tdevents/client_confirm.go similarity index 96% rename from client_confirm.go rename to tdevents/client_confirm.go index 169e0a7..105e456 100644 --- a/client_confirm.go +++ b/tdevents/client_confirm.go @@ -1,4 +1,4 @@ -package tdproto +package tdevents func NewClientConfirm(confirmId string) (r ClientConfirm) { r.Name = r.GetName() diff --git a/client_message_deleted.go b/tdevents/client_message_deleted.go similarity index 96% rename from client_message_deleted.go rename to tdevents/client_message_deleted.go index 3356a0b..4657bd6 100644 --- a/client_message_deleted.go +++ b/tdevents/client_message_deleted.go @@ -1,4 +1,4 @@ -package tdproto +package tdevents func NewClientMessageDeleted(messageId string) (r ClientMessageDeleted) { r.Name = r.GetName() diff --git a/client_message_updated.go b/tdevents/client_message_updated.go similarity index 90% rename from client_message_updated.go rename to tdevents/client_message_updated.go index e995b18..95f0026 100644 --- a/client_message_updated.go +++ b/tdevents/client_message_updated.go @@ -1,4 +1,6 @@ -package tdproto +package tdevents + +import "github.com/tada-team/tdproto" func NewClientMessageUpdated(p ClientMessageUpdatedParams) (r ClientMessageUpdated) { r.Name = r.GetName() @@ -18,10 +20,10 @@ func (p ClientMessageUpdated) GetName() string { return "client.message.updated" // Params of the client.message.updated event type ClientMessageUpdatedParams struct { // Chat, task or contact jid. Required. - To JID `json:"to"` + To tdproto.JID `json:"to"` // Message content. Required. - Content MessageContent `json:"content"` + Content tdproto.MessageContent `json:"content"` // Uid created by client. Recommended. MessageId string `json:"message_id,omitempty"` diff --git a/client_ping.go b/tdevents/client_ping.go similarity index 93% rename from client_ping.go rename to tdevents/client_ping.go index 9c01251..9e5fa84 100644 --- a/client_ping.go +++ b/tdevents/client_ping.go @@ -1,4 +1,4 @@ -package tdproto +package tdevents func NewClientPing() (r ClientPing) { r.Name = r.GetName() diff --git a/tdevents/confirm_id.go b/tdevents/confirm_id.go new file mode 100644 index 0000000..e4822ad --- /dev/null +++ b/tdevents/confirm_id.go @@ -0,0 +1,29 @@ +package tdevents + +import ( + "crypto/rand" + "log" +) + +func ConfirmId() string { + return randomSymbols(12, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") +} + +func randomSymbols(n int, letters string) string { + bytes, err := randomBytes(n) + if err != nil { + log.Panicln("random bytes fail:", err) + } + for i, b := range bytes { + bytes[i] = letters[b%byte(len(letters))] + } + return string(bytes) +} + +func randomBytes(n int) ([]byte, error) { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + return nil, err + } + return b, nil +} diff --git a/event.go b/tdevents/event.go similarity index 97% rename from event.go rename to tdevents/event.go index 32425d0..05b4639 100644 --- a/event.go +++ b/tdevents/event.go @@ -1,4 +1,4 @@ -package tdproto +package tdevents // Base of all events type BaseEvent struct { diff --git a/server_call_answer.go b/tdevents/server_call_answer.go similarity index 74% rename from server_call_answer.go rename to tdevents/server_call_answer.go index 19adf03..ed39e61 100644 --- a/server_call_answer.go +++ b/tdevents/server_call_answer.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerCallAnswer(jid JID, sdp string, onliners []CallOnliner, uid string) (r ServerCallAnswer) { +import "github.com/tada-team/tdproto" + +func NewServerCallAnswer(jid tdproto.JID, sdp string, onliners []tdproto.CallOnliner, uid string) (r ServerCallAnswer) { r.Name = r.GetName() r.Params.Jid = jid r.Params.JSEP.Type = "answer" @@ -21,16 +23,16 @@ func (p ServerCallAnswer) GetName() string { return "server.call.answer" } // Params of the server.call.answer event type serverCallAnswerParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // List of ICE candidates (when trickle = false) Candidates []serverCallAnswerCandidate `json:"candidates,omitempty"` // Current call participants - Onliners []CallOnliner `json:"onliners,omitempty"` + Onliners []tdproto.CallOnliner `json:"onliners,omitempty"` // SDP data - JSEP JSEP `json:"jsep"` + JSEP tdproto.JSEP `json:"jsep"` // Call id Uid string `json:"uid"` diff --git a/server_call_buzz.go b/tdevents/server_call_buzz.go similarity index 69% rename from server_call_buzz.go rename to tdevents/server_call_buzz.go index a046a11..5525a7e 100644 --- a/server_call_buzz.go +++ b/tdevents/server_call_buzz.go @@ -1,10 +1,12 @@ -package tdproto +package tdevents import ( "time" + + "github.com/tada-team/tdproto" ) -func NewServerCallBuzz(teamShort TeamShort, chatShort ChatShort, actorShort ContactShort, uid string, timeout time.Duration) (r ServerCallBuzz) { +func NewServerCallBuzz(teamShort tdproto.TeamShort, chatShort tdproto.ChatShort, actorShort tdproto.ContactShort, uid string, timeout time.Duration) (r ServerCallBuzz) { r.Name = r.GetName() r.Params.TeamShort = teamShort r.Params.ChatShort = chatShort @@ -29,22 +31,22 @@ func (p ServerCallBuzz) GetName() string { return "server.call.buzz" } // Params of the server.call.buzz event type serverCallBuzzParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Chat icons - Icons IconData `json:"icons"` + Icons tdproto.IconData `json:"icons"` // Chat title DisplayName string `json:"display_name"` // Short team information - TeamShort TeamShort `json:"teaminfo"` + TeamShort tdproto.TeamShort `json:"teaminfo"` // Short chat information - ChatShort ChatShort `json:"chat"` + ChatShort tdproto.ChatShort `json:"chat"` // Short call creator information - ActorShort ContactShort `json:"actor"` + ActorShort tdproto.ContactShort `json:"actor"` // Call id Uid string `json:"uid"` diff --git a/server_call_buzzcancel.go b/tdevents/server_call_buzzcancel.go similarity index 72% rename from server_call_buzzcancel.go rename to tdevents/server_call_buzzcancel.go index ea2e6ab..ed6fbbb 100644 --- a/server_call_buzzcancel.go +++ b/tdevents/server_call_buzzcancel.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerCallBuzzcancel(chat JID, teamUid string, uid string) (r ServerCallBuzzcancel) { +import "github.com/tada-team/tdproto" + +func NewServerCallBuzzcancel(chat tdproto.JID, teamUid string, uid string) (r ServerCallBuzzcancel) { r.Name = r.GetName() r.Params.Jid = chat r.Params.Team = teamUid @@ -19,7 +21,7 @@ func (p ServerCallBuzzcancel) GetName() string { return "server.call.buzzcancel" // Params of the server.call.buzzcancel event type serverCallBuzzcancelParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Team id Team string `json:"team"` diff --git a/server_call_checkfingerprint.go b/tdevents/server_call_checkfingerprint.go similarity index 96% rename from server_call_checkfingerprint.go rename to tdevents/server_call_checkfingerprint.go index a8cabfd..93a74e1 100644 --- a/server_call_checkfingerprint.go +++ b/tdevents/server_call_checkfingerprint.go @@ -1,4 +1,4 @@ -package tdproto +package tdevents func NewServerCallCheckFingerprint(fingerprint string) (r ServerCallCheckFingerprint) { r.Name = r.GetName() diff --git a/server_call_leave.go b/tdevents/server_call_leave.go similarity index 71% rename from server_call_leave.go rename to tdevents/server_call_leave.go index 7d22368..94c2896 100644 --- a/server_call_leave.go +++ b/tdevents/server_call_leave.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerCallLeave(jid JID, uid string) (r ServerCallLeave) { +import "github.com/tada-team/tdproto" + +func NewServerCallLeave(jid tdproto.JID, uid string) (r ServerCallLeave) { r.Name = r.GetName() r.Params.Jid = jid r.Params.Uid = uid @@ -18,7 +20,7 @@ func (p ServerCallLeave) GetName() string { return "server.call.leave" } // Params of the server.call.leave event type serverCallLeaveParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Call uid Uid string `json:"uid"` diff --git a/server_call_muteall.go b/tdevents/server_call_muteall.go similarity index 72% rename from server_call_muteall.go rename to tdevents/server_call_muteall.go index 383793b..2f938e7 100644 --- a/server_call_muteall.go +++ b/tdevents/server_call_muteall.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerCallMuteall(jid JID, muted bool) (r ServerCallMuteall) { +import "github.com/tada-team/tdproto" + +func NewServerCallMuteall(jid tdproto.JID, muted bool) (r ServerCallMuteall) { r.Name = r.GetName() r.Params.Jid = jid r.Params.Muted = muted @@ -18,7 +20,7 @@ func (p ServerCallMuteall) GetName() string { return "server.call.muteall" } // Params of the server.call.muteall event type serverCallMuteallParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Mute state Muted bool `json:"muted"` diff --git a/server_call_reject.go b/tdevents/server_call_reject.go similarity index 72% rename from server_call_reject.go rename to tdevents/server_call_reject.go index f5143c0..f62dbcc 100644 --- a/server_call_reject.go +++ b/tdevents/server_call_reject.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerCallReject(jid JID, reason string, uid string) (r ServerCallReject) { +import "github.com/tada-team/tdproto" + +func NewServerCallReject(jid tdproto.JID, reason string, uid string) (r ServerCallReject) { r.Name = r.GetName() r.Params.Jid = jid r.Params.Reason = reason @@ -19,7 +21,7 @@ func (p ServerCallReject) GetName() string { return "server.call.reject" } // Params of the server.call.reject event type serverCallRejectParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Call id Uid string `json:"uid"` diff --git a/server_call_restart.go b/tdevents/server_call_restart.go similarity index 72% rename from server_call_restart.go rename to tdevents/server_call_restart.go index 5192b3a..32e1b5f 100644 --- a/server_call_restart.go +++ b/tdevents/server_call_restart.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerCallRestart(chat JID, teamUid string, uid string) (r ServerCallRestart) { +import "github.com/tada-team/tdproto" + +func NewServerCallRestart(chat tdproto.JID, teamUid string, uid string) (r ServerCallRestart) { r.Name = r.GetName() r.Params.Jid = chat r.Params.Team = teamUid @@ -19,7 +21,7 @@ func (p ServerCallRestart) GetName() string { return "server.call.restart" } // Params of the server.call.restart event type serverCallRestartParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Call id Uid string `json:"uid"` diff --git a/server_call_sdp.go b/tdevents/server_call_sdp.go similarity index 72% rename from server_call_sdp.go rename to tdevents/server_call_sdp.go index 4d29189..294366a 100644 --- a/server_call_sdp.go +++ b/tdevents/server_call_sdp.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerCallSdp(jid JID, uid, sdpType, sdp string) (r ServerCallSdp) { +import "github.com/tada-team/tdproto" + +func NewServerCallSdp(jid tdproto.JID, uid, sdpType, sdp string) (r ServerCallSdp) { r.Name = r.GetName() r.Params.Jid = jid r.Params.JSEP.Type = sdpType @@ -20,11 +22,11 @@ func (p ServerCallSdp) GetName() string { return "server.call.sdp" } // Params of the server.call.sdp event type serverCallSdpParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Call id Uid string `json:"uid"` // SDP data - JSEP JSEP `json:"jsep"` + JSEP tdproto.JSEP `json:"jsep"` } diff --git a/server_call_sound.go b/tdevents/server_call_sound.go similarity index 72% rename from server_call_sound.go rename to tdevents/server_call_sound.go index 230e718..e5c48a1 100644 --- a/server_call_sound.go +++ b/tdevents/server_call_sound.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerCallSound(jid JID, muted bool) (r ServerCallSound) { +import "github.com/tada-team/tdproto" + +func NewServerCallSound(jid tdproto.JID, muted bool) (r ServerCallSound) { r.Name = r.GetName() r.Params.Jid = jid r.Params.Muted = muted @@ -18,7 +20,7 @@ func (p ServerCallSound) GetName() string { return "server.call.sound" } // Params of the server.call.sound event type ServerCallSoundParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Mute state Muted bool `json:"muted"` diff --git a/server_call_state.go b/tdevents/server_call_state.go similarity index 52% rename from server_call_state.go rename to tdevents/server_call_state.go index 8879a3b..f7823d1 100644 --- a/server_call_state.go +++ b/tdevents/server_call_state.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerCallState(callEvent CallEvent) (r ServerCallState) { +import "github.com/tada-team/tdproto" + +func NewServerCallState(callEvent tdproto.CallEvent) (r ServerCallState) { r.Name = r.GetName() r.Params = callEvent return @@ -9,7 +11,7 @@ func NewServerCallState(callEvent CallEvent) (r ServerCallState) { // Call information type ServerCallState struct { BaseEvent - Params CallEvent `json:"params"` + Params tdproto.CallEvent `json:"params"` } func (p ServerCallState) GetName() string { return "server.call.state" } diff --git a/server_call_talking.go b/tdevents/server_call_talking.go similarity index 69% rename from server_call_talking.go rename to tdevents/server_call_talking.go index 5e807b6..362eb6e 100644 --- a/server_call_talking.go +++ b/tdevents/server_call_talking.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerCallTalking(talking bool, chat, actor JID) (r ServerCallTalking) { +import "github.com/tada-team/tdproto" + +func NewServerCallTalking(talking bool, chat, actor tdproto.JID) (r ServerCallTalking) { r.Name = r.GetName() r.Params.Jid = chat r.Params.Actor = actor @@ -19,10 +21,10 @@ func (p ServerCallTalking) GetName() string { return "server.call.talking" } // Params of the server.call.talking event type serverCallTalkingParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Actor id - Actor JID `json:"actor"` + Actor tdproto.JID `json:"actor"` // Is talking Talking bool `json:"talking"` diff --git a/server_chat_composing.go b/tdevents/server_chat_composing.go similarity index 77% rename from server_chat_composing.go rename to tdevents/server_chat_composing.go index 545220c..f249794 100644 --- a/server_chat_composing.go +++ b/tdevents/server_chat_composing.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerChatComposing(composing, isAudio bool, chat, actor JID) (r ServerChatComposing) { +import "github.com/tada-team/tdproto" + +func NewServerChatComposing(composing, isAudio bool, chat, actor tdproto.JID) (r ServerChatComposing) { r.Name = r.GetName() r.Params.Jid = chat r.Params.Actor = actor @@ -20,10 +22,10 @@ func (p ServerChatComposing) GetName() string { return "server.chat.composing" } // Params of the server.chat.composing event type serverChatComposingParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Actor id - Actor JID `json:"actor"` + Actor tdproto.JID `json:"actor"` // true = start typing / audio recording, false = stop Composing bool `json:"composing"` @@ -32,5 +34,5 @@ type serverChatComposingParams struct { IsAudio bool `json:"is_audio,omitempty"` // Composing event max lifetime - ValidUntil ISODateTimeString `json:"valid_until,omitempty"` + ValidUntil tdproto.ISODateTimeString `json:"valid_until,omitempty"` } diff --git a/server_chat_deleted.go b/tdevents/server_chat_deleted.go similarity index 58% rename from server_chat_deleted.go rename to tdevents/server_chat_deleted.go index 2cd540d..a421633 100644 --- a/server_chat_deleted.go +++ b/tdevents/server_chat_deleted.go @@ -1,11 +1,13 @@ -package tdproto +package tdevents -func NewServerChatDeleted(chat DeletedChat, teamUnread *TeamUnread, badge uint) (r ServerChatDeleted) { +import "github.com/tada-team/tdproto" + +func NewServerChatDeleted(chat tdproto.DeletedChat, teamUnread *tdproto.TeamUnread, badge uint) (r ServerChatDeleted) { chat.IsArchive = true - chat.Gentime = Gentime() + chat.Gentime = tdproto.Gentime() r.Name = r.GetName() - r.Params.Chats = []DeletedChat{chat} + r.Params.Chats = []tdproto.DeletedChat{chat} r.Params.TeamUnread = teamUnread r.Params.Badge = badge return r @@ -22,10 +24,10 @@ func (p ServerChatDeleted) GetName() string { return "server.chat.deleted" } // Params of the server.chat.deleted event type serverChatDeletedParams struct { // List of deleted chats - Chats []DeletedChat `json:"chats"` + Chats []tdproto.DeletedChat `json:"chats"` // Current team counters - TeamUnread *TeamUnread `json:"team_unread"` + TeamUnread *tdproto.TeamUnread `json:"team_unread"` // Total number of unreads Badge uint `json:"badge"` diff --git a/server_chat_draft.go b/tdevents/server_chat_draft.go similarity index 76% rename from server_chat_draft.go rename to tdevents/server_chat_draft.go index e3d8078..318e546 100644 --- a/server_chat_draft.go +++ b/tdevents/server_chat_draft.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerChatDraft(jid JID, draft string, gentime int64) (r ServerChatDraft) { +import "github.com/tada-team/tdproto" + +func NewServerChatDraft(jid tdproto.JID, draft string, gentime int64) (r ServerChatDraft) { r.Name = r.GetName() r.Params.Jid = jid r.Params.Draft = draft @@ -19,7 +21,7 @@ func (p ServerChatDraft) GetName() string { return "server.chat.draft" } // Params of the server.chat.draft event type serverChatDraftParams struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Draft text Draft string `json:"draft"` diff --git a/server_chat_lastread.go b/tdevents/server_chat_lastread.go similarity index 59% rename from server_chat_lastread.go rename to tdevents/server_chat_lastread.go index aefb2b2..08a930d 100644 --- a/server_chat_lastread.go +++ b/tdevents/server_chat_lastread.go @@ -1,8 +1,10 @@ -package tdproto +package tdevents -func NewServerChatLastread(counters ChatCounters, teamUnread *TeamUnread, badge uint) (r ServerChatLastread) { +import "github.com/tada-team/tdproto" + +func NewServerChatLastread(counters tdproto.ChatCounters, teamUnread *tdproto.TeamUnread, badge uint) (r ServerChatLastread) { r.Name = r.GetName() - r.Params.Chats = []ChatCounters{counters} + r.Params.Chats = []tdproto.ChatCounters{counters} r.Params.TeamUnread = teamUnread r.Params.Badge = badge return r @@ -19,10 +21,10 @@ func (p ServerChatLastread) GetName() string { return "server.chat.lastread" } // Params of the server.chat.lastread event type serverChatLastreadParams struct { // Chat counters - Chats []ChatCounters `json:"chats"` + Chats []tdproto.ChatCounters `json:"chats"` // Current team counters - TeamUnread *TeamUnread `json:"team_unread"` + TeamUnread *tdproto.TeamUnread `json:"team_unread"` // Total number of unreads Badge uint `json:"badge"` diff --git a/server_chat_updated.go b/tdevents/server_chat_updated.go similarity index 58% rename from server_chat_updated.go rename to tdevents/server_chat_updated.go index dce883d..5604d4a 100644 --- a/server_chat_updated.go +++ b/tdevents/server_chat_updated.go @@ -1,10 +1,8 @@ -package tdproto +package tdevents -func NewServerChatUpdated(chat Chat, teamUnread *TeamUnread, badge uint) (r ServerChatUpdated) { - return NewServerChatsUpdated([]Chat{chat}, teamUnread, badge) -} +import "github.com/tada-team/tdproto" -func NewServerChatsUpdated(chats []Chat, teamUnread *TeamUnread, badge uint) (r ServerChatUpdated) { +func NewServerChatUpdated(chats []tdproto.Chat, teamUnread *tdproto.TeamUnread, badge uint) (r ServerChatUpdated) { r.Name = r.GetName() r.Params.Chats = chats r.Params.TeamUnread = teamUnread @@ -23,10 +21,10 @@ func (p ServerChatUpdated) GetName() string { return "server.chat.updated" } // Params of the server.chat.updated event type serverChatUpdatedParams struct { // Chat counters - Chats []Chat `json:"chats"` + Chats []tdproto.Chat `json:"chats"` // Current team counters - TeamUnread *TeamUnread `json:"team_unread"` + TeamUnread *tdproto.TeamUnread `json:"team_unread"` // Total number of unreads Badge uint `json:"badge"` diff --git a/server_confirm.go b/tdevents/server_confirm.go similarity index 96% rename from server_confirm.go rename to tdevents/server_confirm.go index 2b2c888..7b91ea2 100644 --- a/server_confirm.go +++ b/tdevents/server_confirm.go @@ -1,4 +1,4 @@ -package tdproto +package tdevents func NewServerConfirm(v string) (r ServerConfirm) { r.Name = r.GetName() diff --git a/server_contact_updated.go b/tdevents/server_contact_updated.go similarity index 67% rename from server_contact_updated.go rename to tdevents/server_contact_updated.go index 456358b..1790483 100644 --- a/server_contact_updated.go +++ b/tdevents/server_contact_updated.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerContactUpdated(contacts ...Contact) (r ServerContactUpdated) { +import "github.com/tada-team/tdproto" + +func NewServerContactUpdated(contacts ...tdproto.Contact) (r ServerContactUpdated) { r.Name = r.GetName() r.Params.Contacts = contacts return r @@ -17,5 +19,5 @@ func (p ServerContactUpdated) GetName() string { return "server.contact.updated" // Params of the server.contact.updated event type serverContactUpdatedParams struct { // Contact info - Contacts []Contact `json:"contacts"` + Contacts []tdproto.Contact `json:"contacts"` } diff --git a/server_debug.go b/tdevents/server_debug.go similarity index 95% rename from server_debug.go rename to tdevents/server_debug.go index 2986053..1c9d35d 100644 --- a/server_debug.go +++ b/tdevents/server_debug.go @@ -1,4 +1,4 @@ -package tdproto +package tdevents func NewServerDebug(text string) (r ServerDebug) { r.Name = r.GetName() diff --git a/server_login.go b/tdevents/server_login.go similarity index 96% rename from server_login.go rename to tdevents/server_login.go index d2e85c2..01862cf 100644 --- a/server_login.go +++ b/tdevents/server_login.go @@ -1,4 +1,4 @@ -package tdproto +package tdevents func NewServerLogin(deviceName string) (r ServerLogin) { r.Name = r.GetName() diff --git a/server_message_received.go b/tdevents/server_message_received.go similarity index 91% rename from server_message_received.go rename to tdevents/server_message_received.go index febd958..8e2a60b 100644 --- a/server_message_received.go +++ b/tdevents/server_message_received.go @@ -1,9 +1,11 @@ -package tdproto +package tdevents + +import "github.com/tada-team/tdproto" // Message receiving status type ReceivedMessage struct { // Chat or contact id - Chat JID `json:"chat"` + Chat tdproto.JID `json:"chat"` // Message id MessageId string `json:"message_id"` diff --git a/server_message_updated.go b/tdevents/server_message_updated.go similarity index 67% rename from server_message_updated.go rename to tdevents/server_message_updated.go index 5a7ee42..9b2dbf8 100644 --- a/server_message_updated.go +++ b/tdevents/server_message_updated.go @@ -1,12 +1,14 @@ -package tdproto +package tdevents -func NewServerMessageUpdated(messages []Message, delayed bool, counters *ChatCounters, teamUnread *TeamUnread, badge *uint) (r ServerMessageUpdated) { +import "github.com/tada-team/tdproto" + +func NewServerMessageUpdated(messages []tdproto.Message, delayed bool, counters *tdproto.ChatCounters, teamUnread *tdproto.TeamUnread, badge *uint) (r ServerMessageUpdated) { r.Name = r.GetName() r.ConfirmId = ConfirmId() r.Params.Messages = messages r.Params.Delayed = delayed - r.Params.ChatCounters = make([]ChatCounters, 0) + r.Params.ChatCounters = make([]tdproto.ChatCounters, 0) if counters != nil { r.Params.ChatCounters = append(r.Params.ChatCounters, *counters) } @@ -33,16 +35,16 @@ func (p ServerMessageUpdated) GetName() string { return "server.message.updated" // Params of the server.message.updated event type serverMessageUpdatedParams struct { // Messages data - Messages []Message `json:"messages"` + Messages []tdproto.Message `json:"messages"` // true = silently message update, false = new message Delayed bool `json:"delayed"` // Chat counters - ChatCounters []ChatCounters `json:"chat_counters"` + ChatCounters []tdproto.ChatCounters `json:"chat_counters"` // Current team counters - TeamUnread *TeamUnread `json:"team_unread"` + TeamUnread *tdproto.TeamUnread `json:"team_unread"` // Total number of unreads, if changed Badge *uint `json:"badge"` diff --git a/server_online.go b/tdevents/server_online.go similarity index 85% rename from server_online.go rename to tdevents/server_online.go index e64e211..d18f787 100644 --- a/server_online.go +++ b/tdevents/server_online.go @@ -1,4 +1,6 @@ -package tdproto +package tdevents + +import "github.com/tada-team/tdproto" func NewServerOnline(contacts []OnlineContact, calls []OnlineCall) (r ServerOnline) { r.Name = r.GetName() @@ -27,7 +29,7 @@ type serverOnlineParams struct { // Contact online status type OnlineContact struct { // Contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Is away from keyboard Afk bool `json:"afk,omitempty"` @@ -42,13 +44,13 @@ type OnlineContact struct { // Active call status type OnlineCall struct { // Chat or contact id - Jid JID `json:"jid"` + Jid tdproto.JID `json:"jid"` // Call id Uid string `json:"uid"` // Call start - Start ISODateTimeString `json:"start,omitempty"` + Start tdproto.ISODateTimeString `json:"start,omitempty"` // Number participants in call OnlineCount int `json:"online_count,omitempty"` diff --git a/server_processing.go b/tdevents/server_processing.go similarity index 97% rename from server_processing.go rename to tdevents/server_processing.go index 955581a..959d4b6 100644 --- a/server_processing.go +++ b/tdevents/server_processing.go @@ -1,4 +1,4 @@ -package tdproto +package tdevents func NewServerProcessing(num, total int, action, message string, hasError bool) (r ServerProcessing) { r.Name = r.GetName() diff --git a/server_push.go b/tdevents/server_push.go similarity index 55% rename from server_push.go rename to tdevents/server_push.go index f070413..399e7e6 100644 --- a/server_push.go +++ b/tdevents/server_push.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerMessagePush(p MessagePush) (r ServerMessagePush) { +import "github.com/tada-team/tdproto" + +func NewServerMessagePush(p tdproto.MessagePush) (r ServerMessagePush) { r.Name = r.GetName() r.Params = p return r @@ -9,7 +11,7 @@ func NewServerMessagePush(p MessagePush) (r ServerMessagePush) { // Push replacement for desktop application type ServerMessagePush struct { BaseEvent - Params MessagePush `json:"params"` + Params tdproto.MessagePush `json:"params"` } func (p ServerMessagePush) GetName() string { return "server.message.push" } diff --git a/server_remind_deleted.go b/tdevents/server_remind_deleted.go similarity index 74% rename from server_remind_deleted.go rename to tdevents/server_remind_deleted.go index 73b07d9..e346999 100644 --- a/server_remind_deleted.go +++ b/tdevents/server_remind_deleted.go @@ -1,8 +1,10 @@ -package tdproto +package tdevents + +import "github.com/tada-team/tdproto" func NewServerRemindDeleted(uid string) (r ServerRemindDeleted) { r.Name = r.GetName() - r.Params.Remind = []DeletedRemind{ + r.Params.Remind = []tdproto.DeletedRemind{ {Uid: uid}, } return r @@ -19,5 +21,5 @@ func (p ServerRemindDeleted) GetName() string { return "server.remind.deleted" } // Params of the server.remind.deleted event type serverRemindDeletedParams struct { // Remind information - Remind []DeletedRemind `json:"reminds"` + Remind []tdproto.DeletedRemind `json:"reminds"` } diff --git a/server_remind_fired.go b/tdevents/server_remind_fired.go similarity index 61% rename from server_remind_fired.go rename to tdevents/server_remind_fired.go index 65f14fc..3db0306 100644 --- a/server_remind_fired.go +++ b/tdevents/server_remind_fired.go @@ -1,8 +1,10 @@ -package tdproto +package tdevents -func NewServerRemindFired(remind Remind) (r ServerRemindFired) { +import "github.com/tada-team/tdproto" + +func NewServerRemindFired(remind tdproto.Remind) (r ServerRemindFired) { r.Name = r.GetName() - r.Params.Reminds = []Remind{remind} + r.Params.Reminds = []tdproto.Remind{remind} return r } @@ -17,5 +19,5 @@ func (p ServerRemindFired) GetName() string { return "server.remind.fired" } // Params of the server.remind.fired event type serverRemindFiredParams struct { // Remind information - Reminds []Remind `json:"reminds"` + Reminds []tdproto.Remind `json:"reminds"` } diff --git a/server_remind_updated.go b/tdevents/server_remind_updated.go similarity index 68% rename from server_remind_updated.go rename to tdevents/server_remind_updated.go index caf2ff3..b6b70f1 100644 --- a/server_remind_updated.go +++ b/tdevents/server_remind_updated.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerRemindUpdated(reminds ...Remind) (r ServerRemindUpdated) { +import "github.com/tada-team/tdproto" + +func NewServerRemindUpdated(reminds ...tdproto.Remind) (r ServerRemindUpdated) { r.Name = r.GetName() r.Params.Reminds = reminds return r @@ -17,5 +19,5 @@ func (p ServerRemindUpdated) GetName() string { return "server.remind.updated" } // Params of the server.remind.updated event type serverRemindUpdatedParams struct { // Remind information - Reminds []Remind `json:"reminds"` + Reminds []tdproto.Remind `json:"reminds"` } diff --git a/server_section_deleted.go b/tdevents/server_section_deleted.go similarity index 57% rename from server_section_deleted.go rename to tdevents/server_section_deleted.go index 99613ea..12769e7 100644 --- a/server_section_deleted.go +++ b/tdevents/server_section_deleted.go @@ -1,12 +1,14 @@ -package tdproto +package tdevents -func NewServerSectionDeleted(ct ChatType, section DeletedSection) (r ServerSectionDeleted) { - section.Gentime = Gentime() // XXX +import "github.com/tada-team/tdproto" + +func NewServerSectionDeleted(ct tdproto.ChatType, section tdproto.DeletedSection) (r ServerSectionDeleted) { + section.Gentime = tdproto.Gentime() // XXX r.Name = r.GetName() r.Params.ChatType = ct r.Params.Gentime = section.Gentime - r.Params.Sections = []DeletedSection{section} + r.Params.Sections = []tdproto.DeletedSection{section} return r } @@ -21,10 +23,10 @@ func (p ServerSectionDeleted) GetName() string { return "server.section.deleted" // Params of the server.section.deleted event type serverSectionDeletedParams struct { // Chat type - ChatType ChatType `json:"chat_type"` + ChatType tdproto.ChatType `json:"chat_type"` // Section/project info - Sections []DeletedSection `json:"sections"` + Sections []tdproto.DeletedSection `json:"sections"` // Deprecated Gentime int64 `json:"gentime"` diff --git a/server_section_updated.go b/tdevents/server_section_updated.go similarity index 62% rename from server_section_updated.go rename to tdevents/server_section_updated.go index d9839ab..911627f 100644 --- a/server_section_updated.go +++ b/tdevents/server_section_updated.go @@ -1,9 +1,11 @@ -package tdproto +package tdevents -func NewServerSectionUpdated(ct ChatType, sections ...Section) (r ServerSectionUpdated) { +import "github.com/tada-team/tdproto" + +func NewServerSectionUpdated(ct tdproto.ChatType, sections ...tdproto.Section) (r ServerSectionUpdated) { r.Name = r.GetName() r.Params.ChatType = ct - r.Params.Gentime = Gentime() // XXX + r.Params.Gentime = tdproto.Gentime() // XXX r.Params.Sections = sections return r } @@ -19,10 +21,10 @@ func (p ServerSectionUpdated) GetName() string { return "server.section.updated" // Params of the server.section.updated event type serverSectionUpdatedParams struct { // Chat type - ChatType ChatType `json:"chat_type"` + ChatType tdproto.ChatType `json:"chat_type"` // Section/project info - Sections []Section `json:"sections"` + Sections []tdproto.Section `json:"sections"` // deprecated Gentime int64 `json:"gentime"` diff --git a/server_tag_deleted.go b/tdevents/server_tag_deleted.go similarity index 66% rename from server_tag_deleted.go rename to tdevents/server_tag_deleted.go index 06bbc79..9456a32 100644 --- a/server_tag_deleted.go +++ b/tdevents/server_tag_deleted.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerTagDeleted(tags ...DeletedTag) (r ServerTagDeleted) { +import "github.com/tada-team/tdproto" + +func NewServerTagDeleted(tags ...tdproto.DeletedTag) (r ServerTagDeleted) { r.Name = r.GetName() r.Params.Tags = tags return r @@ -17,5 +19,5 @@ func (p ServerTagDeleted) GetName() string { return "server.tag.deleted" } // Params of the server.tag.deleted event type serverTagDeletedParams struct { // Tags info - Tags []DeletedTag `json:"tags"` + Tags []tdproto.DeletedTag `json:"tags"` } diff --git a/server_tag_updated.go b/tdevents/server_tag_updated.go similarity index 68% rename from server_tag_updated.go rename to tdevents/server_tag_updated.go index bc1e5a2..25c6675 100644 --- a/server_tag_updated.go +++ b/tdevents/server_tag_updated.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerTagUpdated(tags ...Tag) (r ServerTagUpdated) { +import "github.com/tada-team/tdproto" + +func NewServerTagUpdated(tags ...tdproto.Tag) (r ServerTagUpdated) { r.Name = r.GetName() r.Params.Tags = tags return r @@ -17,5 +19,5 @@ func (p ServerTagUpdated) GetName() string { return "server.tag.updated" } // Params of the server.tag.updated event type serverTagUpdatedParams struct { // Tags info - Tags []Tag `json:"tags"` + Tags []tdproto.Tag `json:"tags"` } diff --git a/server_team_counters.go b/tdevents/server_team_counters.go similarity index 72% rename from server_team_counters.go rename to tdevents/server_team_counters.go index 39ff1d0..08d10cc 100644 --- a/server_team_counters.go +++ b/tdevents/server_team_counters.go @@ -1,7 +1,9 @@ -package tdproto +package tdevents + +import "github.com/tada-team/tdproto" // TODO: remove empty -func NewServerTeamCounters(counters []TeamCounter, badge uint) ServerTeamCounters { +func NewServerTeamCounters(counters []tdproto.TeamCounter, badge uint) ServerTeamCounters { r := ServerTeamCounters{} r.Name = r.GetName() r.Params.Teams = counters @@ -20,7 +22,7 @@ func (p ServerTeamCounters) GetName() string { return "server.team.counters" } // Params of the server.team.counters event type serverTeamCountersParams struct { // Counters - Teams []TeamCounter `json:"teams"` + Teams []tdproto.TeamCounter `json:"teams"` // Total number of unreads Badge uint `json:"badge"` diff --git a/server_team_deleted.go b/tdevents/server_team_deleted.go similarity index 76% rename from server_team_deleted.go rename to tdevents/server_team_deleted.go index 6ccddb2..f236d3a 100644 --- a/server_team_deleted.go +++ b/tdevents/server_team_deleted.go @@ -1,8 +1,10 @@ -package tdproto +package tdevents + +import "github.com/tada-team/tdproto" func NewServerTeamDeleted(uid string, gentime int64) (r ServerTeamDeleted) { r.Name = r.GetName() - r.Params.Teams = []DeletedTeam{{ + r.Params.Teams = []tdproto.DeletedTeam{{ Uid: uid, IsArchive: true, Gentime: gentime, @@ -21,5 +23,5 @@ func (p ServerTeamDeleted) GetName() string { return "server.team.deleted" } // Params of the server.team.deleted event type serverTeamDeletedParams struct { // Teams info - Teams []DeletedTeam `json:"teams"` + Teams []tdproto.DeletedTeam `json:"teams"` } diff --git a/server_team_updated.go b/tdevents/server_team_updated.go similarity index 61% rename from server_team_updated.go rename to tdevents/server_team_updated.go index f57634a..f1d0f56 100644 --- a/server_team_updated.go +++ b/tdevents/server_team_updated.go @@ -1,8 +1,10 @@ -package tdproto +package tdevents -func NewServerTeamUpdated(team Team) (r ServerTeamUpdated) { +import "github.com/tada-team/tdproto" + +func NewServerTeamUpdated(team tdproto.Team) (r ServerTeamUpdated) { r.Name = r.GetName() - r.Params.Teams = []Team{team} + r.Params.Teams = []tdproto.Team{team} return r } @@ -16,5 +18,5 @@ func (p ServerTeamUpdated) GetName() string { return "server.team.updated" } // Params of the server.team.updated event type serverTeamUpdatedParams struct { - Teams []Team `json:"teams"` + Teams []tdproto.Team `json:"teams"` } diff --git a/server_time.go b/tdevents/server_time.go similarity index 66% rename from server_time.go rename to tdevents/server_time.go index 6bc91c7..62c6f81 100644 --- a/server_time.go +++ b/tdevents/server_time.go @@ -1,10 +1,14 @@ -package tdproto +package tdevents -import "time" +import ( + "time" + + "github.com/tada-team/tdproto" +) func NewServerTime() (r ServerTime) { r.Name = r.GetName() - r.Params.Time = IsoDatetime(time.Now()) + r.Params.Time = tdproto.IsoDatetime(time.Now()) return r } @@ -19,5 +23,5 @@ func (p ServerTime) GetName() string { return "server.time" } // Params of the server.time event type serverTimeParams struct { // Current time - Time ISODateTimeString `json:"time"` + Time tdproto.ISODateTimeString `json:"time"` } diff --git a/server_uisettings.go b/tdevents/server_uisettings.go similarity index 69% rename from server_uisettings.go rename to tdevents/server_uisettings.go index 3b6e72b..d0c0dfb 100644 --- a/server_uisettings.go +++ b/tdevents/server_uisettings.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerUiSettings(namespace string, data UiSettingsData) (r ServerUiSettings) { +import "github.com/tada-team/tdproto" + +func NewServerUiSettings(namespace string, data tdproto.UiSettingsData) (r ServerUiSettings) { r.Name = r.GetName() r.Params = ServerUiSettingsParams{ Namespace: namespace, @@ -20,7 +22,7 @@ type ServerUiSettingsParams struct { Namespace string `json:"namespace"` // UiSettingsData - Data UiSettingsData `json:"data"` + Data tdproto.UiSettingsData `json:"data"` } func (p ServerUiSettings) GetName() string { return "server.uisettings" } diff --git a/server_upload_updated.go b/tdevents/server_upload_updated.go similarity index 68% rename from server_upload_updated.go rename to tdevents/server_upload_updated.go index acf17d2..be97f10 100644 --- a/server_upload_updated.go +++ b/tdevents/server_upload_updated.go @@ -1,6 +1,8 @@ -package tdproto +package tdevents -func NewServerUploadUpdated(uploads ...Upload) (r ServerUploadUpdated) { +import "github.com/tada-team/tdproto" + +func NewServerUploadUpdated(uploads ...tdproto.Upload) (r ServerUploadUpdated) { r.Name = r.GetName() r.Params.Uploads = uploads return r @@ -17,5 +19,5 @@ func (p ServerUploadUpdated) GetName() string { return "server.upload.updated" } // Params of the server.upload.updated event type serverUploadUpdatedParams struct { // Uploads data - Uploads []Upload `json:"uploads"` + Uploads []tdproto.Upload `json:"uploads"` } diff --git a/server_warning.go b/tdevents/server_warning.go similarity index 96% rename from server_warning.go rename to tdevents/server_warning.go index 08fd949..b2d0357 100644 --- a/server_warning.go +++ b/tdevents/server_warning.go @@ -1,4 +1,4 @@ -package tdproto +package tdevents func NewServerWarning(message, orig string) (r ServerWarning) { r.Name = r.GetName() diff --git a/x.go b/tdevents/x.go similarity index 97% rename from x.go rename to tdevents/x.go index 2d68016..cd86c64 100644 --- a/x.go +++ b/tdevents/x.go @@ -1,5 +1,5 @@ // eXtra fast shortcuts -package tdproto +package tdevents import "bytes" diff --git a/tdforms/2fa.go b/tdforms/2fa.go new file mode 100644 index 0000000..dc8e42a --- /dev/null +++ b/tdforms/2fa.go @@ -0,0 +1,68 @@ +package tdforms + + +type basicPasswordUpdate struct { + NewPassword string `json:"new_password"` + NewPasswordRepeat string `json:"new_password_repeat"` + Hint string `json:"hint"` +} + +type basicToken struct { + Token string `json:"token"` +} + +type basicPassword struct { + Password string `json:"password"` +} + +type basicEmail struct { + Email string `json:"email"` +} + +type basicCode struct { + Code string `json:"code"` +} + +type Auth2faForm struct { + basicToken + basicPassword +} + +type Create2faPasswordForm struct { + basicPasswordUpdate +} + +type Update2faPasswordForm struct { + basicPasswordUpdate + basicPassword +} + +type Internal2faPasswordForm struct { + basicPassword +} + +type SendMail2faConfirmForm struct { + basicPassword + basicEmail +} + +type ConfirmMail2faForm struct { + basicPassword + basicCode + basicEmail +} + +type AuthToken2faForm struct { + basicToken +} + +type AuthCheckCode2faForm struct { + basicToken + basicCode +} + +type AuthPasswordRecovery2faForm struct { + basicPasswordUpdate + basicToken + basicCode +} diff --git a/tdforms/Readme.md b/tdforms/Readme.md new file mode 100644 index 0000000..081887b --- /dev/null +++ b/tdforms/Readme.md @@ -0,0 +1 @@ +HTTP API forms. diff --git a/tdapi/calls.go b/tdforms/calls.go similarity index 98% rename from tdapi/calls.go rename to tdforms/calls.go index f1bb812..6e265bc 100644 --- a/tdapi/calls.go +++ b/tdforms/calls.go @@ -1,4 +1,4 @@ -package tdapi +package tdforms import "github.com/tada-team/tdproto" diff --git a/tdapi/color_rule.go b/tdforms/color_rule.go similarity index 98% rename from tdapi/color_rule.go rename to tdforms/color_rule.go index 39b2406..ba68729 100644 --- a/tdapi/color_rule.go +++ b/tdforms/color_rule.go @@ -1,4 +1,4 @@ -package tdapi +package tdforms // Task color rule form type ColorRule struct { diff --git a/tdapi/contact.go b/tdforms/contact.go similarity index 99% rename from tdapi/contact.go rename to tdforms/contact.go index d13d22a..f521fc6 100644 --- a/tdapi/contact.go +++ b/tdforms/contact.go @@ -1,4 +1,4 @@ -package tdapi +package tdforms import "github.com/tada-team/tdproto" diff --git a/tdapi/device.go b/tdforms/device_ping.go similarity index 87% rename from tdapi/device.go rename to tdforms/device_ping.go index 5769dd3..dfdc659 100644 --- a/tdapi/device.go +++ b/tdforms/device_ping.go @@ -1,4 +1,4 @@ -package tdapi +package tdforms // Device ping response type DevicePing struct { diff --git a/tdforms/draft.go b/tdforms/draft.go new file mode 100644 index 0000000..a3a0f14 --- /dev/null +++ b/tdforms/draft.go @@ -0,0 +1,7 @@ +package tdforms + +// Draft form +type Draft struct { + // Draft content + DraftContent string `json:"draft"` +} diff --git a/tdapi/group.go b/tdforms/group.go similarity index 86% rename from tdapi/group.go rename to tdforms/group.go index 1a12404..b56e575 100644 --- a/tdapi/group.go +++ b/tdforms/group.go @@ -1,13 +1,7 @@ -package tdapi +package tdforms import "github.com/tada-team/tdproto" -// Group members -type GroupMembers struct { - // Group members lust - Members []tdproto.GroupMembership `json:"members"` -} - // Group form type Group struct { // Group title diff --git a/tdapi/integration.go b/tdforms/integration.go similarity index 92% rename from tdapi/integration.go rename to tdforms/integration.go index a7ff85d..9446010 100644 --- a/tdapi/integration.go +++ b/tdforms/integration.go @@ -1,7 +1,8 @@ -package tdapi +package tdforms import "github.com/tada-team/tdproto" +// Integration type Integration struct { // Enabled Enabled bool `json:"enabled"` diff --git a/tdforms/message_creation.go b/tdforms/message_creation.go new file mode 100644 index 0000000..6f73b45 --- /dev/null +++ b/tdforms/message_creation.go @@ -0,0 +1,23 @@ +package tdforms + +import "github.com/tada-team/tdproto" + +// Message creation form +type MessageCreation struct { + // Message type + Type tdproto.Mediatype `json:"type"` + + // Message text + Text string `json:"text"` + + // Message id + MessageUid string `json:"message_id,omitempty"` + + // Message attachments + Uploads []string `json:"uploads,omitempty"` + + // Backward compatibility mode + OldStyleAttachment bool `json:"old_style_attachment,omitempty"` + + MessageUpdate +} diff --git a/tdforms/message_update.go b/tdforms/message_update.go new file mode 100644 index 0000000..a01d551 --- /dev/null +++ b/tdforms/message_update.go @@ -0,0 +1,13 @@ +package tdforms + +// Update message form +type MessageUpdate struct { + // Important flag. Not required. Default: false + Important bool `json:"important,omitempty"` + + // Disable links preview generation. Not required. Default: false + Nopreview bool `json:"nopreview,omitempty"` + + // Draft message, send later + SendAt string `json:"send_at,omitempty"` +} diff --git a/tdforms/task.go b/tdforms/task.go new file mode 100644 index 0000000..e98130b --- /dev/null +++ b/tdforms/task.go @@ -0,0 +1,57 @@ +package tdforms + +import "github.com/tada-team/tdproto" + +// Task +type Task struct { + // Custom task color + CustomColorIndex *uint16 `json:"custom_color_index,omitempty"` + + // Task description + Description string `json:"description,omitempty"` + + // Task tags + Tags []string `json:"tags,omitempty"` + + // Task section UID + SectionUid string `json:"section,omitempty"` + + // User who follow the task + Observers []tdproto.JID `json:"observers,omitempty"` // TODO: rename to "followers" + + // Items of the task + Items []string `json:"items,omitempty"` + + // User who was assigned the task + Assignee tdproto.JID `json:"assignee,omitempty"` + + // Deadline time, if any + Deadline tdproto.ISODateTimeString `json:"deadline,omitempty"` + + // Is task or group public for non-guests + Public bool `json:"public,omitempty"` + + // Fire a reminder at this time + RemindAt tdproto.ISODateTimeString `json:"remind_at,omitempty"` + + // Task status + TaskStatus string `json:"task_status,omitempty"` + + // Task importance + Importance *int `json:"importance,omitempty"` + + // Task urgency + Urgency *int `json:"urgency,omitempty"` + + // Task complexity + Complexity *int `json:"complexity,omitempty"` + + // Time spent + SpentTime *int `json:"spent_time,omitempty"` + + // Linked messages + LinkedMessages []string `json:"linked_messages,omitempty"` // TODO: Message object + + // Task uploads + Uploads []string `json:"uploads,omitempty"` +} diff --git a/tdapi/team.go b/tdforms/team.go similarity index 85% rename from tdapi/team.go rename to tdforms/team.go index 39f4149..f8b423c 100644 --- a/tdapi/team.go +++ b/tdforms/team.go @@ -1,7 +1,6 @@ -package tdapi - -import "github.com/tada-team/tdproto" +package tdforms +// Team form type Team struct { // Team name Name string `json:"name"` @@ -39,9 +38,3 @@ type Team struct { // Contacts (for creation only) Contacts []Contact `json:"contacts"` } - -// Invitation information -type TeamPrejoinInfo struct { - // Short team information - Team tdproto.TeamShort `json:"team"` -} diff --git a/tdmarkup/Readme.md b/tdmarkup/Readme.md new file mode 100644 index 0000000..fad0058 --- /dev/null +++ b/tdmarkup/Readme.md @@ -0,0 +1 @@ +Messages markup. diff --git a/tdmocks/Readme.md b/tdmocks/Readme.md new file mode 100644 index 0000000..4e850eb --- /dev/null +++ b/tdmocks/Readme.md @@ -0,0 +1 @@ +Mock objects collection. diff --git a/tdquery/Readme.md b/tdquery/Readme.md new file mode 100644 index 0000000..cba4e24 --- /dev/null +++ b/tdquery/Readme.md @@ -0,0 +1 @@ +HTTP API filters. diff --git a/tdquery/atlinks.go b/tdquery/atlinks.go new file mode 100644 index 0000000..a60d617 --- /dev/null +++ b/tdquery/atlinks.go @@ -0,0 +1,8 @@ +package tdquery + +// @-links filter +type AtLinksFilter struct { + // Enable markdown + Markdown bool `schema:"markdown"` +} + diff --git a/tdapi/chats.go b/tdquery/chats.go similarity index 95% rename from tdapi/chats.go rename to tdquery/chats.go index afb6c92..586f7bf 100644 --- a/tdapi/chats.go +++ b/tdquery/chats.go @@ -1,6 +1,7 @@ -package tdapi +package tdquery -type ChatFilter struct { +// Chat filter +type Chats struct { UserParams Paginator diff --git a/tdapi/message.go b/tdquery/messages.go similarity index 54% rename from tdapi/message.go rename to tdquery/messages.go index b1a1edf..a01aa75 100644 --- a/tdapi/message.go +++ b/tdquery/messages.go @@ -1,8 +1,9 @@ -package tdapi +package tdquery import "github.com/tada-team/tdproto" -type MessageFilter struct { +// Message filter +type Messages struct { UserParams Paginator @@ -60,47 +61,3 @@ type MessageFilter struct { // ?around=msgId (include msgId) Around string `schema:"around"` } - -type MessageUpdate struct { - // Important flag. Not required. Default: false - Important bool `json:"important,omitempty"` - - // Disable links preview generation. Not required. Default: false - Nopreview bool `json:"nopreview,omitempty"` - - // Draft message, send later - SendAt string `json:"send_at,omitempty"` -} - -type Message struct { - // Message type - Type tdproto.Mediatype `json:"type"` - - // Message text - Text string `json:"text"` - - // Message id - MessageUid string `json:"message_id,omitempty"` - - // Message attachments - Uploads []string `json:"uploads,omitempty"` - - // Backward compatibility mode - OldStyleAttachment bool `json:"old_style_attachment,omitempty"` - - MessageUpdate -} - -// Message markup with checked links -type MessageMarkup struct { - // Message markup - Markup []tdproto.MarkupEntity `json:"markup"` - - // Deprecated: use markup instead - Links tdproto.MessageLinks `json:"links"` -} - -// file upload: -//
-// -//
diff --git a/tdquery/mixins.go b/tdquery/mixins.go new file mode 100644 index 0000000..1dbafa9 --- /dev/null +++ b/tdquery/mixins.go @@ -0,0 +1,17 @@ +package tdquery + +type Paginator struct { + // Limit + Limit int `json:"limit,omitempty"` + + // Offset + Offset int `json:"offset,omitempty"` +} + +type UserParams struct { + // Language code + Lang string `schema:"lang,omitempty"` + + // Timezone + Timezone string `schema:"timezone,omitempty"` +} diff --git a/tdquery/sharplinks.go b/tdquery/sharplinks.go new file mode 100644 index 0000000..ab3b9fc --- /dev/null +++ b/tdquery/sharplinks.go @@ -0,0 +1,8 @@ +package tdquery + +// #-links filter +type SharpLinksFilter struct { + // Enable markdown + Markdown bool `schema:"markdown"` +} + diff --git a/tdquery/tasks.go b/tdquery/tasks.go new file mode 100644 index 0000000..c2a4664 --- /dev/null +++ b/tdquery/tasks.go @@ -0,0 +1,67 @@ +package tdquery + +// Query parameters for listing messages +type Tasks struct { + UserParams + Paginator + + //* ?sort = [ "created" | "-created" | "last_message" | "-last_message" | "deadline" | "-deadline" ] + Sort string `schema:"sort"` + + //* ?task_status = new,done | new | any + TaskStatus string `schema:"task_status"` + + //* ?exclude_task_status = new,done | new | any + ExcludeTaskStatus string `schema:"exclude_task_status"` + + //* ?num=num1,num2,num3... + Num string `schema:"num"` + + //* ?observer=jid,jid // TODO: rename to ?follower= + Observer string `schema:"observer"` + + //* ?member=jid,jid + Member string `schema:"member"` + + //* ?assignee=jid,jid + Assignee string `schema:"assignee"` + + //* ?owner=jid,jid + Owner string `schema:"owner"` + + //* ?section=[ uid,uid... | "-" ] + Section string `schema:"section"` // TODO: rename to ?project= + + //* ?tag=[ tag,tag,tag... | "-" ] + Tag string `schema:"tag"` + + //* ?q= + Q string `schema:"q"` + + //* ?public=true|false + Public string `schema:"public"` + + //* ?deadline_gte= + DeadlineGTE string `schema:"deadline_gte"` + + //* ?deadline_lte= + DeadlineLTE string `schema:"deadline_lte"` + + //* ?done_gte= + DoneGTE string `schema:"done_gte"` + + //* ?done_lte= + DoneLTE string `schema:"done_lte"` + + //* ?created_gte= + CreatedGTE string `schema:"created_gte"` + + //* ?created_lte= + CreatedLTE string `schema:"created_lte"` + + //* ?short=true|false + Short string `schema:"short"` + + // gentime great than group/chat + GentimeGT int64 `schema:"gentime_gt"` +} diff --git a/tdapi/upload.go b/tdquery/uploads.go similarity index 55% rename from tdapi/upload.go rename to tdquery/uploads.go index b9df4f1..6d39515 100644 --- a/tdapi/upload.go +++ b/tdquery/uploads.go @@ -1,22 +1,23 @@ -package tdapi +package tdquery import "github.com/tada-team/tdproto" -type UploadFilter struct { +// Uploads filter +type Uploads struct { Paginator - // ?chat=jid,jid + // Comma separated chat jids Chat string `schema:"chat"` - // ?sender=jid,jid + // Comma separated sender jids Sender string `schema:"sender"` - // ?content_type=image/jpeg + // Content type ContentType string `schema:"content_type"` - // ?type=file,image,audio,video + // Comma separated Mediatypes Type tdproto.Mediatype `schema:"type"` - // ?text=substr + // Search string Text string `schema:"text"` } diff --git a/tdresp/2fa.go b/tdresp/2fa.go new file mode 100644 index 0000000..18f8d15 --- /dev/null +++ b/tdresp/2fa.go @@ -0,0 +1,31 @@ +package tdresp + +import "github.com/tada-team/tdproto" + +type Auth struct { + Token string `json:"token,omitempty"` + Me tdproto.UserWithMe `json:"me"` + Required2fa bool `json:"required2fa"` + Recovery2fa bool `json:"recovery2fa"` + Method2fa string `json:"method2fa"` +} + +type Auth2faMailRecovery struct { + CodeValidUntil tdproto.ISODateTimeString `json:"code_valid_until"` + NextCodeAt tdproto.ISODateTimeString `json:"next_code_at"` + CodeLength int `json:"code_length"` + Email string `json:"email"` +} + +type Auth2faSettingsResponse struct { + Enabled bool `json:"enabled"` + RecoveryStatus string `json:"recovery_status"` +} + +type Auth2faSettingsMailValidation struct { + Enabled bool `json:"enabled"` + RecoveryStatus string `json:"recovery_status"` + CodeValidUntil tdproto.ISODateTimeString `json:"code_valid_until"` + NextCodeAt string `json:"next_code_at"` + CodeLength int `json:"code_length"` +} diff --git a/tdresp/Readme.md b/tdresp/Readme.md new file mode 100644 index 0000000..f2769d2 --- /dev/null +++ b/tdresp/Readme.md @@ -0,0 +1 @@ +HTTP API responses. diff --git a/tdapi/atlinks.go b/tdresp/atlinks.go similarity index 85% rename from tdapi/atlinks.go rename to tdresp/atlinks.go index 731dd70..0ffae11 100644 --- a/tdapi/atlinks.go +++ b/tdresp/atlinks.go @@ -1,13 +1,7 @@ -package tdapi +package tdresp import "github.com/tada-team/tdproto" -// @-links filter -type AtLinksFilter struct { - // Enable markdown - Markdown bool `schema:"markdown"` -} - // @-links autocomplete response type AtLinks []AtLink diff --git a/tdapi/background_action.go b/tdresp/background_action.go similarity index 90% rename from tdapi/background_action.go rename to tdresp/background_action.go index 2f8eff1..09a945d 100644 --- a/tdapi/background_action.go +++ b/tdresp/background_action.go @@ -1,4 +1,4 @@ -package tdapi +package tdresp // Background action (for example: Excel import) information type BackgroundAction struct { diff --git a/tdapi/err.go b/tdresp/base.go similarity index 56% rename from tdapi/err.go rename to tdresp/base.go index 83a569c..c097052 100644 --- a/tdapi/err.go +++ b/tdresp/base.go @@ -1,4 +1,30 @@ -package tdapi +package tdresp + +import "github.com/tada-team/tdproto" + +// Server response +type Resp struct { + // Request status + Ok bool `json:"ok"` + + // Result only if ok is true) + Result interface{} `json:"result,omitempty"` + + // Error (only if ok is false) + Error Err `json:"error,omitempty"` + + // Error (only if ok is false and Error is 'InvalidData') + Details map[string]string `json:"details,omitempty"` + + // Reason (only if ok is false and Error is `AccessDenied`) + Reason string `json:"reason,omitempty"` + + // Reason markup (only if ok is false and Error is `AccessDenied`) + Markup []tdproto.MarkupEntity `json:"markup,omitempty"` + + // Server side work time + DebugTime string `json:"_time,omitempty"` +} type Err string diff --git a/tdapi/botcommands.go b/tdresp/botcommands.go similarity index 95% rename from tdapi/botcommands.go rename to tdresp/botcommands.go index c40b44b..875d5e2 100644 --- a/tdapi/botcommands.go +++ b/tdresp/botcommands.go @@ -1,4 +1,4 @@ -package tdapi +package tdresp // Bot commands list type BotCommands []BotCommand diff --git a/tdresp/chat_messages.go b/tdresp/chat_messages.go new file mode 100644 index 0000000..5f41919 --- /dev/null +++ b/tdresp/chat_messages.go @@ -0,0 +1,9 @@ +package tdresp + +import "github.com/tada-team/tdproto" + +// Chat messages +type ChatMessages struct { + // Message list + Messages []tdproto.Message `json:"messages"` +} diff --git a/tdresp/chats.go b/tdresp/chats.go new file mode 100644 index 0000000..4e84121 --- /dev/null +++ b/tdresp/chats.go @@ -0,0 +1,21 @@ +package tdresp + +import "github.com/tada-team/tdproto" + +// Chats response +type Chats struct { + // Chat list + Objects []tdproto.Chat `json:"objects"` + + // Contacts used in chats + Contacts []tdproto.Contact `json:"contacts,omitempty"` + + // Count + Count int `json:"count"` + + // Limit + Limit int `json:"limit"` + + // Offset + Offset int `json:"offset"` +} diff --git a/tdresp/contacts.go b/tdresp/contacts.go new file mode 100644 index 0000000..d063eee --- /dev/null +++ b/tdresp/contacts.go @@ -0,0 +1,18 @@ +package tdresp + +import "github.com/tada-team/tdproto" + +// Paginated contacts +type Contacts struct { + // Contacts list + Objects []tdproto.Contact `json:"objects"` + + // Count + Count int `json:"count"` + + // Limit + Limit int `json:"limit"` + + // Offset + Offset int `json:"offset"` +} diff --git a/tdapi/draft.go b/tdresp/draft.go similarity index 91% rename from tdapi/draft.go rename to tdresp/draft.go index dbc78e0..131ec2d 100644 --- a/tdapi/draft.go +++ b/tdresp/draft.go @@ -1,8 +1,8 @@ -package tdapi +package tdresp import "github.com/tada-team/tdproto" -// Draft form and response +// Draft response type Draft struct { // Draft content Draft string `json:"draft"` diff --git a/tdapi/easy_api.go b/tdresp/easy_api.go similarity index 97% rename from tdapi/easy_api.go rename to tdresp/easy_api.go index 32673a6..deddc67 100644 --- a/tdapi/easy_api.go +++ b/tdresp/easy_api.go @@ -1,4 +1,4 @@ -package tdapi +package tdresp // Simple api for integrations /api/message or /tasks/[team]/[num]/message type EasyApiMessage struct { diff --git a/tdapi/emoji.go b/tdresp/emoji.go similarity index 52% rename from tdapi/emoji.go rename to tdresp/emoji.go index a8299ac..f8c314b 100644 --- a/tdapi/emoji.go +++ b/tdresp/emoji.go @@ -1,7 +1,9 @@ -package tdapi +package tdresp import "github.com/tada-team/tdproto" -type EmojiResp struct { +// Emoji response +type Emoji struct { + // Emoji list All []tdproto.Emoji `json:"all"` } diff --git a/tdresp/group_members.go b/tdresp/group_members.go new file mode 100644 index 0000000..dc54a8f --- /dev/null +++ b/tdresp/group_members.go @@ -0,0 +1,9 @@ +package tdresp + +import "github.com/tada-team/tdproto" + +// Group members +type GroupMembers struct { + // Group members lust + Members []tdproto.GroupMembership `json:"members"` +} diff --git a/tdapi/hotmessages.go b/tdresp/hotmessages.go similarity index 95% rename from tdapi/hotmessages.go rename to tdresp/hotmessages.go index 82eeebe..f238100 100644 --- a/tdapi/hotmessages.go +++ b/tdresp/hotmessages.go @@ -1,4 +1,4 @@ -package tdapi +package tdresp import "github.com/tada-team/tdproto" diff --git a/tdresp/message_markup.go b/tdresp/message_markup.go new file mode 100644 index 0000000..1dec3bd --- /dev/null +++ b/tdresp/message_markup.go @@ -0,0 +1,12 @@ +package tdresp + +import "github.com/tada-team/tdproto" + +// Message markup with checked links +type MessageMarkup struct { + // Message markup + Markup []tdproto.MarkupEntity `json:"markup"` + + // Deprecated: use markup instead + Links tdproto.MessageLinks `json:"links"` +} diff --git a/tdresp/messages.go b/tdresp/messages.go new file mode 100644 index 0000000..cf21431 --- /dev/null +++ b/tdresp/messages.go @@ -0,0 +1,19 @@ +package tdresp + +import "github.com/tada-team/tdproto" + +// Messages response +type Messages struct { + // Message list + Objects []tdproto.Message `json:"objects"` + + // Count + Count int `json:"count"` + + // Limit + Limit int `json:"limit"` + + // Offset + Offset int `json:"offset"` +} + diff --git a/tdapi/my_reactions.go b/tdresp/my_reactions.go similarity index 94% rename from tdapi/my_reactions.go rename to tdresp/my_reactions.go index 7cc203f..b0a3518 100644 --- a/tdapi/my_reactions.go +++ b/tdresp/my_reactions.go @@ -1,4 +1,4 @@ -package tdapi +package tdresp import "github.com/tada-team/tdproto" diff --git a/tdresp/releases.go b/tdresp/releases.go new file mode 100644 index 0000000..9131bb6 --- /dev/null +++ b/tdresp/releases.go @@ -0,0 +1,18 @@ +package tdresp + +import "github.com/tada-team/tdproto" + +// Releases response +type Releases struct { + // Android dist + Android []tdproto.Dist `json:"android,omitempty"` + + // Linux dist + Linux []tdproto.Dist `json:"linux,omitempty"` + + // macOS dist + Mac []tdproto.Dist `json:"mac,omitempty"` + + // Windows dist + Win []tdproto.Dist `json:"win,omitempty"` +} diff --git a/tdapi/sharplinks.go b/tdresp/sharplinks.go similarity index 88% rename from tdapi/sharplinks.go rename to tdresp/sharplinks.go index 18c43fc..02508e4 100644 --- a/tdapi/sharplinks.go +++ b/tdresp/sharplinks.go @@ -1,13 +1,7 @@ -package tdapi +package tdresp import "github.com/tada-team/tdproto" -// #-links filter -type SharpLinksFilter struct { - // Enable markdown - Markdown bool `schema:"markdown"` -} - // #-links autocomplete response type SharpLinks []SharpLink diff --git a/tdapi/sms_code.go b/tdresp/sms_code.go similarity index 73% rename from tdapi/sms_code.go rename to tdresp/sms_code.go index d6e6121..807483d 100644 --- a/tdapi/sms_code.go +++ b/tdresp/sms_code.go @@ -1,16 +1,16 @@ -package tdapi +package tdresp import "github.com/tada-team/tdproto" // SMS code response type SmsCode struct { - // Normalized mobile phone number + // Phone number Phone string `json:"phone"` - // Code expiration time + // Code expiration date CodeValidUntil tdproto.ISODateTimeString `json:"code_valid_until"` - // Next code sending available time + // Next code date NextCodeAt tdproto.ISODateTimeString `json:"next_code_at"` // SMS code length diff --git a/tdresp/task_colors.go b/tdresp/task_colors.go new file mode 100644 index 0000000..d7fa87b --- /dev/null +++ b/tdresp/task_colors.go @@ -0,0 +1,10 @@ +package tdresp + +import "github.com/tada-team/tdproto" + +// Task cards colors +type TaskColors struct { + // Color list + Colors []tdproto.TaskColor `json:"colors"` +} + diff --git a/tdresp/team_prejoin_info.go b/tdresp/team_prejoin_info.go new file mode 100644 index 0000000..4b098ae --- /dev/null +++ b/tdresp/team_prejoin_info.go @@ -0,0 +1,9 @@ +package tdresp + +import "github.com/tada-team/tdproto" + +// Invitation information +type TeamPrejoinInfo struct { + // Short team information + Team tdproto.TeamShort `json:"team"` +} diff --git a/tdresp/timezones.go b/tdresp/timezones.go new file mode 100644 index 0000000..c41d9df --- /dev/null +++ b/tdresp/timezones.go @@ -0,0 +1,7 @@ +package tdresp + +// Timezones response +type Timezones struct { + // Timezones list + Timezones []string `json:"timezones"` +} diff --git a/tdresp/upload_short_messages.go b/tdresp/upload_short_messages.go new file mode 100644 index 0000000..9634b19 --- /dev/null +++ b/tdresp/upload_short_messages.go @@ -0,0 +1,18 @@ +package tdresp + +import "github.com/tada-team/tdproto" + +// Upload + ShortMessage objects +type UploadShortMessages struct { + // Upload + ShortMessage objects list + Objects []tdproto.UploadShortMessage `json:"objects"` + + // Count + Count int `json:"count"` + + // Limit + Limit int `json:"limit"` + + // Offset + Offset int `json:"offset"` +} diff --git a/utils.go b/utils.go index 0f487af..0c0e032 100644 --- a/utils.go +++ b/utils.go @@ -1,8 +1,6 @@ package tdproto import ( - "crypto/rand" - "log" "path/filepath" "runtime" "strings" @@ -32,26 +30,3 @@ func IsoDatetime(dt time.Time) string { s := dt.UTC().Format("2006-01-02T15:04:05.000000-0700") return strings.Replace(s, "+0000", "Z", 1) } - -func ConfirmId() string { - return randomSymbols(12, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") -} - -func randomSymbols(n int, letters string) string { - bytes, err := randomBytes(n) - if err != nil { - log.Panicln("random bytes fail:", err) - } - for i, b := range bytes { - bytes[i] = letters[b%byte(len(letters))] - } - return string(bytes) -} - -func randomBytes(n int) ([]byte, error) { - b := make([]byte, n) - if _, err := rand.Read(b); err != nil { - return nil, err - } - return b, nil -}