Skip to content

Commit

Permalink
Merge pull request #10 from community-network/messing-around
Browse files Browse the repository at this point in the history
[PYTHON] restructure project and add tests
  • Loading branch information
zefanjajobse authored Oct 27, 2023
2 parents 0f65539 + 0379265 commit ba8013a
Show file tree
Hide file tree
Showing 25 changed files with 2,152 additions and 729 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,6 @@ dist
.yarn/install-state.gz
.pnp.*

__pycache__
__pycache__
.idea
temp/
18 changes: 13 additions & 5 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,22 +154,30 @@ if __name__ == "__main__":
### current build method from proto to javascript via python
needs proto-compile, which can be installed with:
`pip3 install proto-compile`
```shell
pip3 install proto-compile
```
and build with:
`proto-compile --clear-output-dirs --verbosity=1 ./proto ./src/proto grpc-web --grpc_web_out_options="import_style=typescript,mode=grpcweb"`
```shell
proto-compile --clear-output-dirs --verbosity=1 ./proto ./src/proto grpc-web --grpc_web_out_options="import_style=typescript,mode=grpcweb"
```
building for python requires grpcio-tools, which can be installed with:
`pip3 install grpcio-tools`
```shell
pip3 install grpcio-tools
```
and build with:
`python3 -m grpc_tools.protoc -I. --python_out=./bfportal_grpc --grpc_python_out=./bfportal_grpc ./proto/communitygames.proto ./proto/localization.proto ./proto/authentication.proto ./proto/reporting.proto`
```shell
poetry run compile_proto
```
python package used: https://github.com/romnn/proto-compile
### Pushing your changes
package versions can be made with `npm run build` and `npm version patch` `git push --tags origin main` to release.
for python patch with `npm run build:python`, `npm run python:setimports` and `poetry build`.
for python `poetry build`.
example library used: https://github.com/tomchen/example-typescript-package
26 changes: 25 additions & 1 deletion bfportal_grpc/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,25 @@
from .proto import authentication_pb2_grpc, authentication_pb2, communitygames_pb2_grpc, communitygames_pb2, localization_pb2_grpc, localization_pb2, reporting_pb2_grpc, reporting_pb2
import sys
from pathlib import Path


def _add_proto_files_to_python_path():
absolute_path = Path(__file__).parent.joinpath("proto").absolute()
if absolute_path not in sys.path:
sys.path.append(str(absolute_path))


try:
_add_proto_files_to_python_path()
from .proto import (
authentication_pb2_grpc,
authentication_pb2,
communitygames_pb2_grpc,
communitygames_pb2,
localization_pb2_grpc,
localization_pb2,
reporting_pb2_grpc,
reporting_pb2,
)
except ImportError:
print("Please run `poetry run compile-proto` to compile the proto files.")
pass
14 changes: 7 additions & 7 deletions bfportal_grpc/access_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,25 @@
import aiohttp
import urllib.parse


class Cookie:
sid: str
remid: str

def __init__(self, sid: str, remid: str):
self.sid = sid
self.remid = remid


async def getBf2042GatewaySession(cookie: Cookie) -> str:
async with aiohttp.ClientSession() as session:
url = "https://accounts.ea.com/connect/auth?client_id=KINGSTON_COMP_APP&locale=en_US&redirect_uri=https%3A%2F%2Fportal.battlefield.com%2F&response_type=code"
headers = {
"Cookie": f"sid={cookie.sid}; remid={cookie.remid};"
}
headers = {"Cookie": f"sid={cookie.sid}; remid={cookie.remid};"}
async with session.get(url=url, headers=headers, allow_redirects=False) as r:
redirect = r.headers["Location"]
access_code = urllib.parse.urlparse(
redirect).query.split("=")[1]
access_code = urllib.parse.urlparse(redirect).query.split("=")[1]
return access_code


if __name__ == "__main__":
asyncio.run(getBf2042GatewaySession())
asyncio.run(getBf2042GatewaySession())
Empty file.
42 changes: 42 additions & 0 deletions bfportal_grpc/helpers/compile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import subprocess
from pathlib import Path
import os

PROJECT_ROOT = Path(__file__).parent.parent.parent
OUT_DIR = PROJECT_ROOT / "bfportal_grpc" / "proto"
INPUT_PROTO_FILES_DIR = PROJECT_ROOT / "proto"

PROTO_FILES = [
proto_file.relative_to(PROJECT_ROOT)
for proto_file in list(INPUT_PROTO_FILES_DIR.glob("*.proto"))
]

BASE_COMMAND = [
"python",
"-m",
"grpc_tools.protoc",
]
COMMAND_ARGUMENTS = [
f"-I={INPUT_PROTO_FILES_DIR.relative_to(PROJECT_ROOT)}",
f"--python_out=./{OUT_DIR.relative_to(PROJECT_ROOT)}",
f"--grpc_python_out=./{OUT_DIR.relative_to(PROJECT_ROOT)}",
f"--pyi_out=./{OUT_DIR.relative_to(PROJECT_ROOT)}",
*PROTO_FILES,
]
COMPILE_COMMAND = BASE_COMMAND + COMMAND_ARGUMENTS


def compile_proto():
# print(subprocess.list2cmdline(COMPILE_COMMAND))
os.chdir(PROJECT_ROOT)
command_output = subprocess.run(
COMPILE_COMMAND,
capture_output=True,
)
if command_output.returncode != 0:
print(command_output.stdout.decode())
print(command_output.stderr.decode())


if __name__ == "__main__":
compile_proto()
51 changes: 25 additions & 26 deletions bfportal_grpc/proto/authentication_pb2.py

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

114 changes: 114 additions & 0 deletions bfportal_grpc/proto/authentication_pb2.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
from google.protobuf.internal import containers as _containers
from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from typing import ClassVar as _ClassVar, Iterable as _Iterable, Mapping as _Mapping, Optional as _Optional, Union as _Union

DESCRIPTOR: _descriptor.FileDescriptor

class Platform(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
__slots__ = []
UNKNOWN: _ClassVar[Platform]
PC: _ClassVar[Platform]
PS4: _ClassVar[Platform]
XBOXONE: _ClassVar[Platform]
PS5: _ClassVar[Platform]
XBSX: _ClassVar[Platform]
COMMON: _ClassVar[Platform]

class Reason(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
__slots__ = []
NONE: _ClassVar[Reason]
PLAYER: _ClassVar[Reason]
SYNC: _ClassVar[Reason]

class UserBits(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
__slots__ = []
USER_BIT_UNSPECIFIED: _ClassVar[UserBits]
USER_BIT_ACCEPTED_TOS: _ClassVar[UserBits]
USER_BIT_ENABLE_USERSHARING: _ClassVar[UserBits]
USER_BIT_ENABLE_CRASHREPORTS: _ClassVar[UserBits]
USER_BIT_COMPLETED_TUTORIAL: _ClassVar[UserBits]
USER_BIT_CLIENT_ENABLE_USAGESHARING: _ClassVar[UserBits]
UNKNOWN: Platform
PC: Platform
PS4: Platform
XBOXONE: Platform
PS5: Platform
XBSX: Platform
COMMON: Platform
NONE: Reason
PLAYER: Reason
SYNC: Reason
USER_BIT_UNSPECIFIED: UserBits
USER_BIT_ACCEPTED_TOS: UserBits
USER_BIT_ENABLE_USERSHARING: UserBits
USER_BIT_ENABLE_CRASHREPORTS: UserBits
USER_BIT_COMPLETED_TUTORIAL: UserBits
USER_BIT_CLIENT_ENABLE_USAGESHARING: UserBits

class PlayerInfo(_message.Message):
__slots__ = ["nucleusId", "personaId", "platformId"]
NUCLEUSID_FIELD_NUMBER: _ClassVar[int]
PERSONAID_FIELD_NUMBER: _ClassVar[int]
PLATFORMID_FIELD_NUMBER: _ClassVar[int]
nucleusId: int
personaId: int
platformId: int
def __init__(self, nucleusId: _Optional[int] = ..., personaId: _Optional[int] = ..., platformId: _Optional[int] = ...) -> None: ...

class AuthRequest(_message.Message):
__slots__ = ["authCode", "redirectUri", "product", "firstPartyId", "platform"]
AUTHCODE_FIELD_NUMBER: _ClassVar[int]
REDIRECTURI_FIELD_NUMBER: _ClassVar[int]
PRODUCT_FIELD_NUMBER: _ClassVar[int]
FIRSTPARTYID_FIELD_NUMBER: _ClassVar[int]
PLATFORM_FIELD_NUMBER: _ClassVar[int]
authCode: str
redirectUri: str
product: str
firstPartyId: str
platform: Platform
def __init__(self, authCode: _Optional[str] = ..., redirectUri: _Optional[str] = ..., product: _Optional[str] = ..., firstPartyId: _Optional[str] = ..., platform: _Optional[_Union[Platform, str]] = ...) -> None: ...

class Duration(_message.Message):
__slots__ = ["seconds", "nanos"]
SECONDS_FIELD_NUMBER: _ClassVar[int]
NANOS_FIELD_NUMBER: _ClassVar[int]
seconds: int
nanos: int
def __init__(self, seconds: _Optional[int] = ..., nanos: _Optional[int] = ...) -> None: ...

class TimeTravel(_message.Message):
__slots__ = ["offset"]
OFFSET_FIELD_NUMBER: _ClassVar[int]
offset: Duration
def __init__(self, offset: _Optional[_Union[Duration, _Mapping]] = ...) -> None: ...

class ProtocolVersionOverride(_message.Message):
__slots__ = ["original", "overridden", "reason"]
ORIGINAL_FIELD_NUMBER: _ClassVar[int]
OVERRIDDEN_FIELD_NUMBER: _ClassVar[int]
REASON_FIELD_NUMBER: _ClassVar[int]
original: str
overridden: str
reason: Reason
def __init__(self, original: _Optional[str] = ..., overridden: _Optional[str] = ..., reason: _Optional[_Union[Reason, str]] = ...) -> None: ...

class Empty(_message.Message):
__slots__ = []
def __init__(self) -> None: ...

class AuthResponse(_message.Message):
__slots__ = ["sessionId", "player", "userBits", "timeTravel", "protocolVersionOverride"]
SESSIONID_FIELD_NUMBER: _ClassVar[int]
PLAYER_FIELD_NUMBER: _ClassVar[int]
USERBITS_FIELD_NUMBER: _ClassVar[int]
TIMETRAVEL_FIELD_NUMBER: _ClassVar[int]
PROTOCOLVERSIONOVERRIDE_FIELD_NUMBER: _ClassVar[int]
sessionId: str
player: PlayerInfo
userBits: _containers.RepeatedScalarFieldContainer[UserBits]
timeTravel: TimeTravel
protocolVersionOverride: ProtocolVersionOverride
def __init__(self, sessionId: _Optional[str] = ..., player: _Optional[_Union[PlayerInfo, _Mapping]] = ..., userBits: _Optional[_Iterable[_Union[UserBits, str]]] = ..., timeTravel: _Optional[_Union[TimeTravel, _Mapping]] = ..., protocolVersionOverride: _Optional[_Union[ProtocolVersionOverride, _Mapping]] = ...) -> None: ...
26 changes: 13 additions & 13 deletions bfportal_grpc/proto/authentication_pb2_grpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"""Client and server classes corresponding to protobuf-defined services."""
import grpc

from . import authentication_pb2 as proto_dot_authentication__pb2
import authentication_pb2 as authentication__pb2


class AuthenticationStub(object):
Expand All @@ -16,13 +16,13 @@ def __init__(self, channel):
"""
self.viaAuthCode = channel.unary_unary(
'/web.authentication.Authentication/viaAuthCode',
request_serializer=proto_dot_authentication__pb2.AuthRequest.SerializeToString,
response_deserializer=proto_dot_authentication__pb2.AuthResponse.FromString,
request_serializer=authentication__pb2.AuthRequest.SerializeToString,
response_deserializer=authentication__pb2.AuthResponse.FromString,
)
self.logout = channel.unary_unary(
'/web.authentication.Authentication/logout',
request_serializer=proto_dot_authentication__pb2.Empty.SerializeToString,
response_deserializer=proto_dot_authentication__pb2.Empty.FromString,
request_serializer=authentication__pb2.Empty.SerializeToString,
response_deserializer=authentication__pb2.Empty.FromString,
)


Expand All @@ -46,13 +46,13 @@ def add_AuthenticationServicer_to_server(servicer, server):
rpc_method_handlers = {
'viaAuthCode': grpc.unary_unary_rpc_method_handler(
servicer.viaAuthCode,
request_deserializer=proto_dot_authentication__pb2.AuthRequest.FromString,
response_serializer=proto_dot_authentication__pb2.AuthResponse.SerializeToString,
request_deserializer=authentication__pb2.AuthRequest.FromString,
response_serializer=authentication__pb2.AuthResponse.SerializeToString,
),
'logout': grpc.unary_unary_rpc_method_handler(
servicer.logout,
request_deserializer=proto_dot_authentication__pb2.Empty.FromString,
response_serializer=proto_dot_authentication__pb2.Empty.SerializeToString,
request_deserializer=authentication__pb2.Empty.FromString,
response_serializer=authentication__pb2.Empty.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
Expand All @@ -76,8 +76,8 @@ def viaAuthCode(request,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/web.authentication.Authentication/viaAuthCode',
proto_dot_authentication__pb2.AuthRequest.SerializeToString,
proto_dot_authentication__pb2.AuthResponse.FromString,
authentication__pb2.AuthRequest.SerializeToString,
authentication__pb2.AuthResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)

Expand All @@ -93,7 +93,7 @@ def logout(request,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/web.authentication.Authentication/logout',
proto_dot_authentication__pb2.Empty.SerializeToString,
proto_dot_authentication__pb2.Empty.FromString,
authentication__pb2.Empty.SerializeToString,
authentication__pb2.Empty.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
Loading

0 comments on commit ba8013a

Please sign in to comment.