diff --git a/.github/apk-badge.png b/.github/apk-badge.png new file mode 100644 index 00000000..5d112c2f Binary files /dev/null and b/.github/apk-badge.png differ diff --git a/.github/google-play-badge.png b/.github/google-play-badge.png new file mode 100644 index 00000000..7da103b5 Binary files /dev/null and b/.github/google-play-badge.png differ diff --git a/.github/readme-banner.png b/.github/readme-banner.png new file mode 100644 index 00000000..03e78742 Binary files /dev/null and b/.github/readme-banner.png differ diff --git a/.github/utils/.gitignore b/.github/utils/.gitignore new file mode 100644 index 00000000..d50a09fc --- /dev/null +++ b/.github/utils/.gitignore @@ -0,0 +1,2 @@ +.env +__pycache__/ diff --git a/.github/utils/_get_password.py b/.github/utils/_get_password.py new file mode 100644 index 00000000..33071b6c --- /dev/null +++ b/.github/utils/_get_password.py @@ -0,0 +1,57 @@ +import base64 +import secrets +from hashlib import sha256 +from typing import Tuple + +import mysql.connector as mysql +from Crypto.Cipher import AES + + +def get_password( + version_name: str, + version_code: int, + db_host: str, + db_user: str, + db_pass: str, + db_name: str, +) -> Tuple[str, bytes]: + db = mysql.connect( + host=db_host, + user=db_user, + password=db_pass, + database=db_name, + auth_plugin="mysql_native_password", + ) + + print(f"Generating passwords for version {version_name} ({version_code})") + + password = base64.b64encode(secrets.token_bytes(16)).decode() + iv = secrets.token_bytes(16) + + key = f"{version_name}.{password}.{version_code}" + key = sha256(key.encode()).digest() + data = "ThisIsOurHardWorkPleaseDoNotCopyOrSteal(c)2019.KubaSz" + data = sha256(data.encode()).digest() + data = data + (chr(16) * 16).encode() + + aes = AES.new(key=key, mode=AES.MODE_CBC, iv=iv) + + app_password = base64.b64encode(aes.encrypt(data)).decode() + + c = db.cursor() + c.execute( + "INSERT IGNORE INTO _appPasswords (versionCode, appPassword, password, iv) VALUES (%s, %s, %s, %s);", + (version_code, app_password, password, iv), + ) + db.commit() + + c = db.cursor() + c.execute( + "SELECT password, iv FROM _appPasswords WHERE versionCode = %s;", + (version_code,), + ) + row = c.fetchone() + + db.close() + + return (row[0], row[1]) diff --git a/.github/utils/_utils.py b/.github/utils/_utils.py new file mode 100644 index 00000000..09b59f4a --- /dev/null +++ b/.github/utils/_utils.py @@ -0,0 +1,142 @@ +import re +import subprocess +import sys +from datetime import datetime +from typing import Tuple + +VERSION_NAME_REGEX = r'versionName: "(.+?)"' +VERSION_CODE_REGEX = r"versionCode: ([0-9]+)" +VERSION_NAME_FORMAT = 'versionName: "{}"' +VERSION_CODE_FORMAT = "versionCode: {}" + + +def get_project_dir() -> str: + project_dir = sys.argv[1] + if project_dir[-1:] == "/" or project_dir[-1:] == "\\": + project_dir = project_dir[:-1] + return project_dir + + +def read_gradle_version(project_dir: str) -> Tuple[int, str]: + GRADLE_PATH = f"{project_dir}/build.gradle" + + with open(GRADLE_PATH, "r") as f: + gradle = f.read() + + version_name = re.search(VERSION_NAME_REGEX, gradle).group(1) + version_code = int(re.search(VERSION_CODE_REGEX, gradle).group(1)) + + return (version_code, version_name) + + +def write_gradle_version(project_dir: str, version_code: int, version_name: str): + GRADLE_PATH = f"{project_dir}/build.gradle" + + with open(GRADLE_PATH, "r") as f: + gradle = f.read() + + gradle = re.sub( + VERSION_NAME_REGEX, VERSION_NAME_FORMAT.format(version_name), gradle + ) + gradle = re.sub( + VERSION_CODE_REGEX, VERSION_CODE_FORMAT.format(version_code), gradle + ) + + with open(GRADLE_PATH, "w") as f: + f.write(gradle) + + +def build_version_code(version_name: str) -> int: + version = version_name.split("+")[0].split("-") + version_base = version[0] + version_suffix = version[1] if len(version) == 2 else "" + + base_parts = version_base.split(".") + major = int(base_parts[0]) or 0 + minor = int(base_parts[1]) if len(base_parts) > 1 else 0 + patch = int(base_parts[2]) if len(base_parts) > 2 else 0 + + beta = 9 + rc = 9 + if "dev" in version_suffix: + beta = 0 + rc = 0 + elif "beta." in version_suffix: + beta = int(version_suffix.split(".")[1]) + rc = 0 + elif "rc." in version_suffix: + beta = 0 + rc = int(version_suffix.split(".")[1]) + + version_code = beta + rc * 10 + patch * 100 + minor * 10000 + major * 1000000 + return version_code + + +def get_changelog(project_dir: str, format: str) -> Tuple[str, str]: + with open( + f"{project_dir}/app/src/main/assets/pl-changelog.html", "r", encoding="utf-8" + ) as f: + changelog = f.read() + + title = re.search(r"

(.+?)

", changelog).group(1) + content = re.search(r"(?s)", changelog).group(1).strip() + content = "\n".join(line.strip() for line in content.split("\n")) + + if format != "html": + content = content.replace("
  • ", "- ") + content = content.replace("
    ", "\n") + if format == "markdown": + content = re.sub(r"(.+?)", "__\\1__", content) + content = re.sub(r"(.+?)", "*\\1*", content) + content = re.sub(r"(.+?)", "**\\1**", content) + content = re.sub(r"", "", content) + + return (title, content) + + +def get_commit_log(project_dir: str, format: str, max_lines: int = None) -> str: + last_tag = ( + subprocess.check_output("git describe --tags --abbrev=0".split(" ")) + .decode() + .strip() + ) + + log = subprocess.run( + args=f"git log {last_tag}..HEAD --format=%an%x00%at%x00%h%x00%s%x00%D".split(" "), + cwd=project_dir, + stdout=subprocess.PIPE, + ) + log = log.stdout.strip().decode() + + commits = [line.split("\x00") for line in log.split("\n")] + if max_lines: + commits = commits[:max_lines] + + output = [] + valid = False + + for commit in commits: + if not commit[0]: + continue + if "origin/" in commit[4]: + valid = True + if not valid: + continue + date = datetime.fromtimestamp(float(commit[1])) + date = date.strftime("%Y-%m-%d %H:%M:%S") + if format == "html": + output.append(f"
  • {commit[3]} - {commit[0]}
  • ") + elif format == "markdown": + output.append(f"[{date}] {commit[0]}\n {commit[3]}") + elif format == "markdown_full": + output.append( + f"_[{date}] {commit[0]}_\n` `__`{commit[2]}`__ **{commit[3]}**" + ) + elif format == "plain": + output.append(f"- {commit[3]}") + + if format == "markdown": + output.insert(0, "```") + output.append("```") + + return "\n".join(output) diff --git a/.github/utils/bump_nightly.py b/.github/utils/bump_nightly.py new file mode 100644 index 00000000..88b4798c --- /dev/null +++ b/.github/utils/bump_nightly.py @@ -0,0 +1,69 @@ +import json +import os +import re +import sys +from datetime import datetime, timedelta + +import requests + +from _utils import ( + get_commit_log, + get_project_dir, + read_gradle_version, + write_gradle_version, +) + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("usage: bump_nightly.py ") + exit(-1) + + repo = os.getenv("GITHUB_REPOSITORY") + sha = os.getenv("GITHUB_SHA") + + if not repo or not sha: + print("Missing GitHub environment variables.") + exit(-1) + + with requests.get( + f"https://api.github.com/repos/{repo}/actions/runs?per_page=5&status=success" + ) as r: + data = json.loads(r.text) + runs = [run for run in data["workflow_runs"] if run["head_sha"] == sha] + if runs: + print("::set-output name=hasNewChanges::false") + exit(0) + + print("::set-output name=hasNewChanges::true") + + project_dir = get_project_dir() + + (version_code, version_name) = read_gradle_version(project_dir) + version_name = version_name.split("+")[0] + + date = datetime.now() + if date.hour > 6: + version_name += "+daily." + date.strftime("%Y%m%d-%H%M") + else: + date -= timedelta(days=1) + version_name += "+nightly." + date.strftime("%Y%m%d") + + print("::set-output name=appVersionName::" + version_name) + print("::set-output name=appVersionCode::" + str(version_code)) + + write_gradle_version(project_dir, version_code, version_name) + + commit_log = get_commit_log(project_dir, format="html", max_lines=10) + + with open( + f"{project_dir}/app/src/main/assets/pl-changelog.html", "r", encoding="utf-8" + ) as f: + changelog = f.read() + + changelog = re.sub(r"

    (.+?)

    ", f"

    {version_name}

    ", changelog) + changelog = re.sub(r"(?s)", f"", changelog) + + with open( + f"{project_dir}/app/src/main/assets/pl-changelog.html", "w", encoding="utf-8" + ) as f: + f.write(changelog) diff --git a/.github/utils/bump_version.py b/.github/utils/bump_version.py new file mode 100644 index 00000000..80d36519 --- /dev/null +++ b/.github/utils/bump_version.py @@ -0,0 +1,41 @@ +import os + +from dotenv import load_dotenv + +from _get_password import get_password +from _utils import build_version_code, write_gradle_version +from sign import sign + +if __name__ == "__main__": + version_name = input("Enter version name: ") + version_code = build_version_code(version_name) + + print(f"Bumping version to {version_name} ({version_code})") + + project_dir = "../.." + + load_dotenv() + DB_HOST = os.getenv("DB_HOST") + DB_USER = os.getenv("DB_USER") + DB_PASS = os.getenv("DB_PASS") + DB_NAME = os.getenv("DB_NAME") + + write_gradle_version(project_dir, version_code, version_name) + (password, iv) = get_password( + version_name, version_code, DB_HOST, DB_USER, DB_PASS, DB_NAME + ) + + sign(project_dir, version_name, version_code, password, iv, commit=False) + + print("Writing mock passwords") + os.chdir(project_dir) + os.system( + "sed -i -E 's/\/\*([0-9a-f]{2} ?){16}\*\//\/*secret password - removed for source code publication*\//g' app/src/main/cpp/szkolny-signing.cpp" + ) + os.system( + "sed -i -E 's/\\t0x.., 0x(.)., 0x.(.), 0x.(.), 0x.., 0x.., 0x.., 0x.(.), 0x.., 0x.(.), 0x(.)., 0x(.)., 0x.., 0x.., 0x.., 0x.(.)/\\t0x\\3\\6, 0x\\7\\4, 0x\\1\\8, 0x\\2\\5, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff /g' app/src/main/cpp/szkolny-signing.cpp" + ) + os.system( + "sed -i -E 's/param1\..(.).(.).(.).(.)..(.)..(.)..(.)..(.).../param1.MTIzNDU2Nzg5MD\\5\\2\\7\\6\\1\\3\\4\8==/g' app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/interceptor/Signing.kt" + ) + input("Press any key to finish") diff --git a/.github/utils/extract_changelogs.py b/.github/utils/extract_changelogs.py new file mode 100644 index 00000000..25d346c1 --- /dev/null +++ b/.github/utils/extract_changelogs.py @@ -0,0 +1,72 @@ +import os +import sys + +from _utils import get_changelog, get_commit_log, get_project_dir, read_gradle_version + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("usage: extract_changelogs.py ") + exit(-1) + + project_dir = get_project_dir() + + (version_code, version_name) = read_gradle_version(project_dir) + + print("::set-output name=appVersionName::" + version_name) + print("::set-output name=appVersionCode::" + str(version_code)) + + dir = f"{project_dir}/app/release/whatsnew-{version_name}/" + os.makedirs(dir, exist_ok=True) + + print("::set-output name=changelogDir::" + dir) + + (title, changelog) = get_changelog(project_dir, format="plain") + + # plain text changelog - Firebase App Distribution + with open(dir + "whatsnew-titled.txt", "w", encoding="utf-8") as f: + f.write(title) + f.write("\n") + f.write(changelog) + print("::set-output name=changelogPlainTitledFile::" + dir + "whatsnew-titled.txt") + + print("::set-output name=changelogTitle::" + title) + + # plain text changelog, max 500 chars - Google Play + with open(dir + "whatsnew-pl-PL", "w", encoding="utf-8") as f: + changelog_lines = changelog.split("\n") + changelog = "" + for line in changelog_lines: + if len(changelog) + len(line) < 500: + changelog += "\n" + line + changelog = changelog.strip() + f.write(changelog) + + print("::set-output name=changelogPlainFile::" + dir + "whatsnew-pl-PL") + + # markdown changelog - Discord webhook + (_, changelog) = get_changelog(project_dir, format="markdown") + with open(dir + "whatsnew.md", "w", encoding="utf-8") as f: + f.write(changelog) + print("::set-output name=changelogMarkdownFile::" + dir + "whatsnew.md") + + # html changelog - version info in DB + (_, changelog) = get_changelog(project_dir, format="html") + with open(dir + "whatsnew.html", "w", encoding="utf-8") as f: + f.write(changelog) + print("::set-output name=changelogHtmlFile::" + dir + "whatsnew.html") + + + changelog = get_commit_log(project_dir, format="plain", max_lines=10) + with open(dir + "commit_log.txt", "w", encoding="utf-8") as f: + f.write(changelog) + print("::set-output name=commitLogPlainFile::" + dir + "commit_log.txt") + + changelog = get_commit_log(project_dir, format="markdown", max_lines=10) + with open(dir + "commit_log.md", "w", encoding="utf-8") as f: + f.write(changelog) + print("::set-output name=commitLogMarkdownFile::" + dir + "commit_log.md") + + changelog = get_commit_log(project_dir, format="html", max_lines=10) + with open(dir + "commit_log.html", "w", encoding="utf-8") as f: + f.write(changelog) + print("::set-output name=commitLogHtmlFile::" + dir + "commit_log.html") diff --git a/.github/utils/rename_artifacts.py b/.github/utils/rename_artifacts.py new file mode 100644 index 00000000..4eeabfaf --- /dev/null +++ b/.github/utils/rename_artifacts.py @@ -0,0 +1,26 @@ +import glob +import os +import sys + +from _utils import get_project_dir + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("usage: rename_artifacts.py ") + exit(-1) + + project_dir = get_project_dir() + + files = glob.glob(f"{project_dir}/app/release/*.*") + for file in files: + file_relative = file.replace(os.getenv("GITHUB_WORKSPACE") + "/", "") + if "-aligned.apk" in file: + os.unlink(file) + elif "-signed.apk" in file: + new_file = file.replace("-signed.apk", ".apk") + if os.path.isfile(new_file): + os.unlink(new_file) + os.rename(file, new_file) + elif ".apk" in file or ".aab" in file: + print("::set-output name=signedReleaseFile::" + file) + print("::set-output name=signedReleaseFileRelative::" + file_relative) diff --git a/.github/utils/save_version.py b/.github/utils/save_version.py new file mode 100644 index 00000000..01de17a7 --- /dev/null +++ b/.github/utils/save_version.py @@ -0,0 +1,122 @@ +import glob +import os +import sys +from datetime import datetime +from time import time + +import mysql.connector as mysql +from dotenv import load_dotenv + +from _utils import get_changelog, get_commit_log, get_project_dir, read_gradle_version + + +def save_version( + project_dir: str, + db_host: str, + db_user: str, + db_pass: str, + db_name: str, + apk_server_release: str, + apk_server_nightly: str, +): + db = mysql.connect( + host=db_host, + user=db_user, + password=db_pass, + database=db_name, + auth_plugin="mysql_native_password", + ) + + (version_code, version_name) = read_gradle_version(project_dir) + (_, changelog) = get_changelog(project_dir, format="html") + + types = ["dev", "beta", "nightly", "daily", "rc", "release"] + build_type = [x for x in types if x in version_name] + build_type = build_type[0] if build_type else "release" + + if "+nightly." in version_name or "+daily." in version_name: + changelog = get_commit_log(project_dir, format="html") + build_type = "nightly" + elif "-dev" in version_name: + build_type = "dev" + elif "-beta." in version_name: + build_type = "beta" + elif "-rc." in version_name: + build_type = "rc" + + build_date = int(time()) + apk_name = None + bundle_name_play = None + + files = glob.glob(f"{project_dir}/app/release/*.*") + output_apk = f"Edziennik_{version_name}_official.apk" + output_aab_play = f"Edziennik_{version_name}_play.aab" + for file in files: + if output_apk in file: + build_date = int(os.stat(file).st_mtime) + apk_name = output_apk + if output_aab_play in file: + build_date = int(os.stat(file).st_mtime) + bundle_name_play = output_aab_play + + build_date = datetime.fromtimestamp(build_date).strftime("%Y-%m-%d %H:%M:%S") + + if build_type in ["nightly", "daily"]: + download_url = apk_server_nightly + apk_name if apk_name else None + else: + download_url = apk_server_release + apk_name if apk_name else None + + cols = [ + "versionCode", + "versionName", + "releaseDate", + "releaseNotes", + "releaseType", + "downloadUrl", + "apkName", + "bundleNamePlay", + ] + updated = { + "versionCode": version_code, + "downloadUrl": download_url, + "apkName": apk_name, + "bundleNamePlay": bundle_name_play, + } + + values = [ + version_code, + version_name, + build_date, + changelog, + build_type, + download_url, + apk_name, + bundle_name_play, + ] + values.extend(val for val in updated.values() if val) + + updated = ", ".join(f"{col} = %s" for (col, val) in updated.items() if val) + + sql = f"INSERT INTO updates ({', '.join(cols)}) VALUES ({'%s, ' * (len(cols) - 1)}%s) ON DUPLICATE KEY UPDATE {updated};" + + c = db.cursor() + c.execute(sql, tuple(values)) + db.commit() + + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("usage: save_version.py ") + exit(-1) + + project_dir = get_project_dir() + + load_dotenv() + DB_HOST = os.getenv("DB_HOST") + DB_USER = os.getenv("DB_USER") + DB_PASS = os.getenv("DB_PASS") + DB_NAME = os.getenv("DB_NAME") + APK_SERVER_RELEASE = os.getenv("APK_SERVER_RELEASE") + APK_SERVER_NIGHTLY = os.getenv("APK_SERVER_NIGHTLY") + + save_version(project_dir, DB_HOST, DB_USER, DB_PASS, DB_NAME, APK_SERVER_RELEASE, APK_SERVER_NIGHTLY) diff --git a/.github/utils/sign.py b/.github/utils/sign.py new file mode 100644 index 00000000..026d819b --- /dev/null +++ b/.github/utils/sign.py @@ -0,0 +1,84 @@ +import os +import re +import sys + +from dotenv import load_dotenv + +from _get_password import get_password +from _utils import get_project_dir, read_gradle_version + + +def sign( + project_dir: str, + version_name: str, + version_code: int, + password: str, + iv: bytes, + commit: bool = False, +): + SIGNING_PATH = f"{project_dir}/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/interceptor/Signing.kt" + CPP_PATH = f"{project_dir}/app/src/main/cpp/szkolny-signing.cpp" + + with open(SIGNING_PATH, "r") as f: + signing = f.read() + + with open(CPP_PATH, "r") as f: + cpp = f.read() + + SIGNING_REGEX = r"\$param1\..*\.\$param2" + CPP_REGEX = r"(?s)/\*.+?toys AES_IV\[16\] = {.+?};" + + SIGNING_FORMAT = "$param1.{}.$param2" + CPP_FORMAT = "/*{}*/\nstatic toys AES_IV[16] = {{\n\t{} }};" + + print(f"Writing passwords for version {version_name} ({version_code})") + + iv_hex = " ".join(["{:02x}".format(x) for x in iv]) + iv_cpp = ", ".join(["0x{:02x}".format(x) for x in iv]) + + signing = re.sub(SIGNING_REGEX, SIGNING_FORMAT.format(password), signing) + cpp = re.sub(CPP_REGEX, CPP_FORMAT.format(iv_hex, iv_cpp), cpp) + + with open(SIGNING_PATH, "w") as f: + f.write(signing) + + with open(CPP_PATH, "w") as f: + f.write(cpp) + + if commit: + os.chdir(project_dir) + os.system("git add .") + os.system( + f'git commit -m "[{version_name}] Update build.gradle, signing and changelog."' + ) + + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("usage: sign.py [commit]") + exit(-1) + + project_dir = get_project_dir() + + load_dotenv() + DB_HOST = os.getenv("DB_HOST") + DB_USER = os.getenv("DB_USER") + DB_PASS = os.getenv("DB_PASS") + DB_NAME = os.getenv("DB_NAME") + + (version_code, version_name) = read_gradle_version(project_dir) + (password, iv) = get_password( + version_name, version_code, DB_HOST, DB_USER, DB_PASS, DB_NAME + ) + + print("::set-output name=appVersionName::" + version_name) + print("::set-output name=appVersionCode::" + str(version_code)) + + sign( + project_dir, + version_name, + version_code, + password, + iv, + commit="commit" in sys.argv, + ) diff --git a/.github/utils/webhook_discord.py b/.github/utils/webhook_discord.py new file mode 100644 index 00000000..3c1404ae --- /dev/null +++ b/.github/utils/webhook_discord.py @@ -0,0 +1,118 @@ +import os +import sys +from datetime import datetime + +import requests +from dotenv import load_dotenv + +from _utils import get_changelog, get_commit_log, get_project_dir, read_gradle_version + + +def post_webhook( + project_dir: str, + apk_file: str, + apk_server_release: str, + apk_server_nightly: str, + webhook_release: str, + webhook_testing: str, +): + (_, version_name) = read_gradle_version(project_dir) + + types = ["dev", "beta", "nightly", "daily", "rc", "release"] + build_type = [x for x in types if x in version_name] + build_type = build_type[0] if build_type else None + + testing = ["dev", "beta", "nightly", "daily"] + testing = build_type in testing + + apk_name = os.path.basename(apk_file) + if build_type in ["nightly", "daily"]: + download_url = apk_server_nightly + apk_name + else: + download_url = apk_server_release + apk_name + + if testing: + build_date = int(os.stat(apk_file).st_mtime) + if build_date: + build_date = datetime.fromtimestamp(build_date).strftime("%Y-%m-%d %H:%M") + + # untagged release, get commit log + if build_type in ["nightly", "daily"]: + changelog = get_commit_log(project_dir, format="markdown", max_lines=5) + else: + changelog = get_changelog(project_dir, format="markdown") + + webhook = get_webhook_testing( + version_name, build_type, changelog, download_url, build_date + ) + requests.post(url=webhook_testing, json=webhook) + else: + changelog = get_changelog(project_dir, format="markdown") + webhook = get_webhook_release(changelog, download_url) + requests.post(url=webhook_release, json=webhook) + + +def get_webhook_release(changelog: str, download_url: str): + (title, content) = changelog + return {"content": f"__**{title}**__\n{content}\n{download_url}"} + + +def get_webhook_testing( + version_name: str, + build_type: str, + changelog: str, + download_url: str, + build_date: str, +): + return { + "embeds": [ + { + "title": f"Nowa wersja {build_type} aplikacji Szkolny.eu", + "description": f"Dostępna jest nowa wersja testowa **{build_type}**.", + "color": 2201331, + "fields": [ + { + "name": f"Wersja `{version_name}`", + "value": f"[Pobierz .APK]({download_url})" + if download_url + else "*Pobieranie niedostępne*", + "inline": False, + }, + { + "name": "Data kompilacji", + "value": build_date or "-", + "inline": False, + }, + { + "name": "Ostatnie zmiany", + "value": changelog or "-", + "inline": False, + }, + ], + } + ] + } + + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("usage: webhook_discord.py ") + exit(-1) + + project_dir = get_project_dir() + + load_dotenv() + APK_FILE = os.getenv("APK_FILE") + APK_SERVER_RELEASE = os.getenv("APK_SERVER_RELEASE") + APK_SERVER_NIGHTLY = os.getenv("APK_SERVER_NIGHTLY") + WEBHOOK_RELEASE = os.getenv("WEBHOOK_RELEASE") + WEBHOOK_TESTING = os.getenv("WEBHOOK_TESTING") + + post_webhook( + project_dir, + APK_FILE, + APK_SERVER_RELEASE, + APK_SERVER_NIGHTLY, + WEBHOOK_RELEASE, + WEBHOOK_TESTING, + ) diff --git a/.github/workflows/build-nightly-apk.yml b/.github/workflows/build-nightly-apk.yml new file mode 100644 index 00000000..0951149e --- /dev/null +++ b/.github/workflows/build-nightly-apk.yml @@ -0,0 +1,154 @@ +name: Nightly build + +on: + schedule: + # 23:30 UTC, 0:30 or 1:30 CET/CEST + - cron: "30 23 * * *" + workflow_dispatch: + +jobs: + prepare: + name: Prepare build environment + runs-on: self-hosted + outputs: + hasNewChanges: ${{ steps.nightly.outputs.hasNewChanges }} + steps: + - name: Checkout repository + uses: actions/checkout@v2 + with: + fetch-depth: 0 + clean: false + - name: Set executable permissions to gradlew + run: chmod +x ./gradlew + - name: Setup Python + uses: actions/setup-python@v2 + - name: Install packages + uses: BSFishy/pip-action@v1 + with: + packages: | + python-dotenv + pycryptodome + mysql-connector-python + requests + - name: Bump nightly version + id: nightly + run: python $GITHUB_WORKSPACE/.github/utils/bump_nightly.py $GITHUB_WORKSPACE + - name: Write signing passwords + if: steps.nightly.outputs.hasNewChanges + env: + DB_HOST: ${{ secrets.DB_HOST }} + DB_USER: ${{ secrets.DB_USER }} + DB_PASS: ${{ secrets.DB_PASS }} + DB_NAME: ${{ secrets.DB_NAME }} + run: python $GITHUB_WORKSPACE/.github/utils/sign.py $GITHUB_WORKSPACE commit + build: + name: Build APK + runs-on: self-hosted + needs: + - prepare + if: ${{ needs.prepare.outputs.hasNewChanges == 'true' }} + outputs: + androidHome: ${{ env.ANDROID_HOME }} + androidSdkRoot: ${{ env.ANDROID_SDK_ROOT }} + steps: + - name: Setup JDK 11 + uses: actions/setup-java@v2 + with: + distribution: 'temurin' + java-version: '11' + - name: Setup Android SDK + uses: android-actions/setup-android@v2 + - name: Clean build artifacts + run: | + rm -rf app/release/* + rm -rf app/build/outputs/apk/* + rm -rf app/build/outputs/bundle/* + - name: Assemble official release with Gradle + uses: gradle/gradle-build-action@v2 + with: + arguments: assembleOfficialRelease + sign: + name: Sign APK + runs-on: self-hosted + needs: + - build + outputs: + signedReleaseFile: ${{ steps.artifacts.outputs.signedReleaseFile }} + signedReleaseFileRelative: ${{ steps.artifacts.outputs.signedReleaseFileRelative }} + steps: + - name: Sign build artifacts + id: sign_app + uses: r0adkll/sign-android-release@v1 + with: + releaseDirectory: app/release + signingKeyBase64: ${{ secrets.KEY_STORE }} + alias: ${{ secrets.KEY_ALIAS }} + keyStorePassword: ${{ secrets.KEY_STORE_PASSWORD }} + keyPassword: ${{ secrets.KEY_ALIAS_PASSWORD }} + env: + ANDROID_HOME: ${{ needs.build.outputs.androidHome }} + ANDROID_SDK_ROOT: ${{ needs.build.outputs.androidSdkRoot }} + BUILD_TOOLS_VERSION: "30.0.2" + - name: Rename signed artifacts + id: artifacts + run: python $GITHUB_WORKSPACE/.github/utils/rename_artifacts.py $GITHUB_WORKSPACE + publish: + name: Publish APK + runs-on: self-hosted + needs: + - sign + steps: + - name: Setup Python + uses: actions/setup-python@v2 + + - name: Extract changelogs + id: changelog + run: python $GITHUB_WORKSPACE/.github/utils/extract_changelogs.py $GITHUB_WORKSPACE + + - name: Upload APK to SFTP + uses: easingthemes/ssh-deploy@v2.1.6 + env: + REMOTE_HOST: ${{ secrets.SSH_IP }} + REMOTE_USER: ${{ secrets.SSH_USERNAME }} + SSH_PRIVATE_KEY: ${{ secrets.SSH_KEY }} + SOURCE: ${{ needs.sign.outputs.signedReleaseFileRelative }} + TARGET: ${{ secrets.SSH_PATH_NIGHTLY }} + - name: Save version metadata + env: + DB_HOST: ${{ secrets.DB_HOST }} + DB_USER: ${{ secrets.DB_USER }} + DB_PASS: ${{ secrets.DB_PASS }} + DB_NAME: ${{ secrets.DB_NAME }} + APK_SERVER_RELEASE: ${{ secrets.APK_SERVER_RELEASE }} + APK_SERVER_NIGHTLY: ${{ secrets.APK_SERVER_NIGHTLY }} + run: python $GITHUB_WORKSPACE/.github/utils/save_version.py $GITHUB_WORKSPACE + + - name: Distribute to App Distribution + uses: wzieba/Firebase-Distribution-Github-Action@v1 + with: + appId: ${{ secrets.FIREBASE_APP_ID }} + token: ${{ secrets.FIREBASE_TOKEN }} + groups: ${{ secrets.FIREBASE_GROUPS_NIGHTLY }} + file: ${{ needs.sign.outputs.signedReleaseFile }} + releaseNotesFile: ${{ steps.changelog.outputs.commitLogPlainFile }} + + - name: Post Discord webhook + env: + APK_FILE: ${{ needs.sign.outputs.signedReleaseFile }} + APK_SERVER_RELEASE: ${{ secrets.APK_SERVER_RELEASE }} + APK_SERVER_NIGHTLY: ${{ secrets.APK_SERVER_NIGHTLY }} + WEBHOOK_RELEASE: ${{ secrets.WEBHOOK_RELEASE }} + WEBHOOK_TESTING: ${{ secrets.WEBHOOK_TESTING }} + run: python $GITHUB_WORKSPACE/.github/utils/webhook_discord.py $GITHUB_WORKSPACE + + - name: Upload workflow artifact + uses: actions/upload-artifact@v2 + if: true + with: + name: ${{ steps.changelog.outputs.appVersionName }} + path: | + app/release/whatsnew*/ + app/release/*.apk + app/release/*.aab + app/release/*.json + app/release/*.txt diff --git a/.github/workflows/build-release-aab-play.yml b/.github/workflows/build-release-aab-play.yml new file mode 100644 index 00000000..95fec5cb --- /dev/null +++ b/.github/workflows/build-release-aab-play.yml @@ -0,0 +1,131 @@ +name: Release build - Google Play [AAB] + +on: + push: + branches: + - "master" + +jobs: + prepare: + name: Prepare build environment + runs-on: self-hosted + steps: + - name: Checkout repository + uses: actions/checkout@v2 + with: + fetch-depth: 0 + clean: false + - name: Set executable permissions to gradlew + run: chmod +x ./gradlew + - name: Setup Python + uses: actions/setup-python@v2 + - name: Install packages + uses: BSFishy/pip-action@v1 + with: + packages: | + python-dotenv + pycryptodome + mysql-connector-python + requests + - name: Write signing passwords + env: + DB_HOST: ${{ secrets.DB_HOST }} + DB_USER: ${{ secrets.DB_USER }} + DB_PASS: ${{ secrets.DB_PASS }} + DB_NAME: ${{ secrets.DB_NAME }} + run: python $GITHUB_WORKSPACE/.github/utils/sign.py $GITHUB_WORKSPACE commit + build: + name: Build App Bundle + runs-on: self-hosted + needs: + - prepare + outputs: + androidHome: ${{ env.ANDROID_HOME }} + androidSdkRoot: ${{ env.ANDROID_SDK_ROOT }} + steps: + - name: Setup JDK 11 + uses: actions/setup-java@v2 + with: + distribution: 'temurin' + java-version: '11' + - name: Setup Android SDK + uses: android-actions/setup-android@v2 + - name: Clean build artifacts + run: | + rm -rf app/release/* + rm -rf app/build/outputs/apk/* + rm -rf app/build/outputs/bundle/* + - name: Bundle play release with Gradle + uses: gradle/gradle-build-action@v2 + with: + arguments: bundlePlayRelease + sign: + name: Sign App Bundle + runs-on: self-hosted + needs: + - build + outputs: + signedReleaseFile: ${{ steps.artifacts.outputs.signedReleaseFile }} + signedReleaseFileRelative: ${{ steps.artifacts.outputs.signedReleaseFileRelative }} + steps: + - name: Sign build artifacts + id: sign_app + uses: r0adkll/sign-android-release@v1 + with: + releaseDirectory: app/release + signingKeyBase64: ${{ secrets.KEY_STORE }} + alias: ${{ secrets.KEY_ALIAS }} + keyStorePassword: ${{ secrets.KEY_STORE_PASSWORD }} + keyPassword: ${{ secrets.KEY_ALIAS_PASSWORD }} + env: + ANDROID_HOME: ${{ needs.build.outputs.androidHome }} + ANDROID_SDK_ROOT: ${{ needs.build.outputs.androidSdkRoot }} + BUILD_TOOLS_VERSION: "30.0.2" + - name: Rename signed artifacts + id: artifacts + run: python $GITHUB_WORKSPACE/.github/utils/rename_artifacts.py $GITHUB_WORKSPACE + publish: + name: Publish App Bundle + runs-on: self-hosted + needs: + - sign + steps: + - name: Setup Python + uses: actions/setup-python@v2 + + - name: Extract changelogs + id: changelog + run: python $GITHUB_WORKSPACE/.github/utils/extract_changelogs.py $GITHUB_WORKSPACE + + - name: Save version metadata + env: + DB_HOST: ${{ secrets.DB_HOST }} + DB_USER: ${{ secrets.DB_USER }} + DB_PASS: ${{ secrets.DB_PASS }} + DB_NAME: ${{ secrets.DB_NAME }} + APK_SERVER_RELEASE: ${{ secrets.APK_SERVER_RELEASE }} + APK_SERVER_NIGHTLY: ${{ secrets.APK_SERVER_NIGHTLY }} + run: python $GITHUB_WORKSPACE/.github/utils/save_version.py $GITHUB_WORKSPACE + + - name: Publish AAB to Google Play + uses: r0adkll/upload-google-play@v1 + if: ${{ endsWith(needs.sign.outputs.signedReleaseFile, '.aab') }} + with: + serviceAccountJsonPlainText: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }} + packageName: pl.szczodrzynski.edziennik + releaseFile: ${{ needs.sign.outputs.signedReleaseFile }} + releaseName: ${{ steps.changelog.outputs.appVersionName }} + track: ${{ secrets.PLAY_RELEASE_TRACK }} + whatsNewDirectory: ${{ steps.changelog.outputs.changelogDir }} + + - name: Upload workflow artifact + uses: actions/upload-artifact@v2 + if: always() + with: + name: ${{ steps.changelog.outputs.appVersionName }} + path: | + app/release/whatsnew*/ + app/release/*.apk + app/release/*.aab + app/release/*.json + app/release/*.txt diff --git a/.github/workflows/build-release-apk.yml b/.github/workflows/build-release-apk.yml new file mode 100644 index 00000000..5ca055b9 --- /dev/null +++ b/.github/workflows/build-release-apk.yml @@ -0,0 +1,154 @@ +name: Release build - official + +on: + push: + tags: + - "*" + +jobs: + prepare: + name: Prepare build environment + runs-on: self-hosted + steps: + - name: Checkout repository + uses: actions/checkout@v2 + with: + fetch-depth: 0 + clean: false + - name: Set executable permissions to gradlew + run: chmod +x ./gradlew + - name: Setup Python + uses: actions/setup-python@v2 + - name: Install packages + uses: BSFishy/pip-action@v1 + with: + packages: | + python-dotenv + pycryptodome + mysql-connector-python + requests + - name: Write signing passwords + env: + DB_HOST: ${{ secrets.DB_HOST }} + DB_USER: ${{ secrets.DB_USER }} + DB_PASS: ${{ secrets.DB_PASS }} + DB_NAME: ${{ secrets.DB_NAME }} + run: python $GITHUB_WORKSPACE/.github/utils/sign.py $GITHUB_WORKSPACE commit + build: + name: Build APK + runs-on: self-hosted + needs: + - prepare + outputs: + androidHome: ${{ env.ANDROID_HOME }} + androidSdkRoot: ${{ env.ANDROID_SDK_ROOT }} + steps: + - name: Setup JDK 11 + uses: actions/setup-java@v2 + with: + distribution: 'temurin' + java-version: '11' + - name: Setup Android SDK + uses: android-actions/setup-android@v2 + - name: Clean build artifacts + run: | + rm -rf app/release/* + rm -rf app/build/outputs/apk/* + rm -rf app/build/outputs/bundle/* + - name: Assemble official release with Gradle + uses: gradle/gradle-build-action@v2 + with: + arguments: assembleOfficialRelease + sign: + name: Sign APK + runs-on: self-hosted + needs: + - build + outputs: + signedReleaseFile: ${{ steps.artifacts.outputs.signedReleaseFile }} + signedReleaseFileRelative: ${{ steps.artifacts.outputs.signedReleaseFileRelative }} + steps: + - name: Sign build artifacts + id: sign_app + uses: r0adkll/sign-android-release@v1 + with: + releaseDirectory: app/release + signingKeyBase64: ${{ secrets.KEY_STORE }} + alias: ${{ secrets.KEY_ALIAS }} + keyStorePassword: ${{ secrets.KEY_STORE_PASSWORD }} + keyPassword: ${{ secrets.KEY_ALIAS_PASSWORD }} + env: + ANDROID_HOME: ${{ needs.build.outputs.androidHome }} + ANDROID_SDK_ROOT: ${{ needs.build.outputs.androidSdkRoot }} + BUILD_TOOLS_VERSION: "30.0.2" + - name: Rename signed artifacts + id: artifacts + run: python $GITHUB_WORKSPACE/.github/utils/rename_artifacts.py $GITHUB_WORKSPACE + publish: + name: Publish APK + runs-on: self-hosted + needs: + - sign + steps: + - name: Setup Python + uses: actions/setup-python@v2 + + - name: Extract changelogs + id: changelog + run: python $GITHUB_WORKSPACE/.github/utils/extract_changelogs.py $GITHUB_WORKSPACE + + - name: Upload APK to SFTP + uses: easingthemes/ssh-deploy@v2.1.6 + env: + REMOTE_HOST: ${{ secrets.SSH_IP }} + REMOTE_USER: ${{ secrets.SSH_USERNAME }} + SSH_PRIVATE_KEY: ${{ secrets.SSH_KEY }} + SOURCE: ${{ needs.sign.outputs.signedReleaseFileRelative }} + TARGET: ${{ secrets.SSH_PATH_RELEASE }} + - name: Save version metadata + env: + DB_HOST: ${{ secrets.DB_HOST }} + DB_USER: ${{ secrets.DB_USER }} + DB_PASS: ${{ secrets.DB_PASS }} + DB_NAME: ${{ secrets.DB_NAME }} + APK_SERVER_RELEASE: ${{ secrets.APK_SERVER_RELEASE }} + APK_SERVER_NIGHTLY: ${{ secrets.APK_SERVER_NIGHTLY }} + run: python $GITHUB_WORKSPACE/.github/utils/save_version.py $GITHUB_WORKSPACE + + - name: Distribute to App Distribution + uses: wzieba/Firebase-Distribution-Github-Action@v1 + with: + appId: ${{ secrets.FIREBASE_APP_ID }} + token: ${{ secrets.FIREBASE_TOKEN }} + groups: ${{ secrets.FIREBASE_GROUPS_RELEASE }} + file: ${{ needs.sign.outputs.signedReleaseFile }} + releaseNotesFile: ${{ steps.changelog.outputs.changelogPlainTitledFile }} + - name: Release on GitHub + uses: softprops/action-gh-release@v1 + with: + name: ${{ steps.changelog.outputs.changelogTitle }} + body_path: ${{ steps.changelog.outputs.changelogMarkdownFile }} + files: ${{ needs.sign.outputs.signedReleaseFile }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Post Discord webhook + env: + APK_FILE: ${{ needs.sign.outputs.signedReleaseFile }} + APK_SERVER_RELEASE: ${{ secrets.APK_SERVER_RELEASE }} + APK_SERVER_NIGHTLY: ${{ secrets.APK_SERVER_NIGHTLY }} + WEBHOOK_RELEASE: ${{ secrets.WEBHOOK_RELEASE }} + WEBHOOK_TESTING: ${{ secrets.WEBHOOK_TESTING }} + run: python $GITHUB_WORKSPACE/.github/utils/webhook_discord.py $GITHUB_WORKSPACE + + - name: Upload workflow artifact + uses: actions/upload-artifact@v2 + if: true + with: + name: ${{ steps.changelog.outputs.appVersionName }} + path: | + app/release/whatsnew*/ + app/release/*.apk + app/release/*.aab + app/release/*.json + app/release/*.txt diff --git a/.gitignore b/.gitignore index 047ad745..375b15e2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,11 @@ + +# Created by https://www.toptal.com/developers/gitignore/api/android,androidstudio,gradle,java,kotlin +# Edit at https://www.toptal.com/developers/gitignore?templates=android,androidstudio,gradle,java,kotlin + +### Android ### # Built application files *.apk +*.aar *.ap_ *.aab @@ -23,7 +29,7 @@ build/ local.properties # Proguard folder generated by Eclipse -#proguard/ +# proguard/ # Log Files *.log @@ -40,7 +46,7 @@ captures/ .idea/tasks.xml .idea/gradle.xml .idea/assetWizardSettings.xml -.idea/dictionaries +#.idea/dictionaries .idea/libraries # Android Studio 3 in .gitignore file. .idea/caches @@ -50,11 +56,12 @@ captures/ # Keystore files # Uncomment the following lines if you do not want to check your keystore files in. -*.jks -*.keystore +#*.jks +#*.keystore # External native build folder generated in Android Studio 2.2 and later .externalNativeBuild +.cxx/ # Google Services (e.g. APIs or Firebase) # google-services.json @@ -80,3 +87,182 @@ lint/generated/ lint/outputs/ lint/tmp/ # lint/reports/ + +### Android Patch ### +gen-external-apklibs +output-metadata.json + +# Replacement of .externalNativeBuild directories introduced +# with Android Studio 3.5. + +### Java ### +# Compiled class file + +# Log file + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +!/*/libs/*.jar + +### Kotlin ### +# Compiled class file + +# Log file + +# BlueJ files + +# Mobile Tools for Java (J2ME) + +# Package Files # + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml + +### Gradle ### +.gradle + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Cache of project +.gradletasknamecache + +# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 +# gradle/wrapper/gradle-wrapper.properties + +### Gradle Patch ### +**/build/ + +### AndroidStudio ### +# Covers files to be ignored for android development using Android Studio. + +# Built application files + +# Files for the ART/Dalvik VM + +# Java class files + +# Generated files + +# Gradle files + +# Signing files +.signing/ + +# Local configuration file (sdk path, etc) + +# Proguard folder generated by Eclipse + +# Log Files + +# Android Studio +/*/build/ +/*/local.properties +/*/out +/*/*/build +/*/*/production +*.ipr +*~ +*.swp + +# Keystore files +*.jks +*.keystore + +# Google Services (e.g. APIs or Firebase) +# google-services.json + +# Android Patch + +# External native build folder generated in Android Studio 2.2 and later + +# NDK +obj/ + +# IntelliJ IDEA +*.iws +/out/ + +# User-specific configurations +.idea/caches/ +.idea/libraries/ +.idea/shelf/ +.idea/.name +.idea/compiler.xml +.idea/copyright/profiles_settings.xml +.idea/encodings.xml +.idea/misc.xml +.idea/scopes/scope_settings.xml +.idea/vcs.xml +.idea/jsLibraryMappings.xml +.idea/datasources.xml +.idea/dataSources.ids +.idea/sqlDataSources.xml +.idea/dynamic.xml +.idea/uiDesigner.xml +.idea/jarRepositories.xml + +# OS-specific files +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db + +# Legacy Eclipse project files +.classpath +.project +.cproject +.settings/ + +# Mobile Tools for Java (J2ME) + +# Package Files # + +# virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml) + +## Plugin-specific files: + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Mongo Explorer plugin +.idea/mongoSettings.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +### AndroidStudio Patch ### + +!/gradle/wrapper/gradle-wrapper.jar + +# End of https://www.toptal.com/developers/gitignore/api/android,androidstudio,gradle,java,kotlin + +signatures/ +.idea/*.xml diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml index 681f41ae..ab75be24 100644 --- a/.idea/codeStyles/Project.xml +++ b/.idea/codeStyles/Project.xml @@ -1,6 +1,11 @@ + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 00000000..79ee123c --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/copyright/Antoni.xml b/.idea/copyright/Antoni.xml new file mode 100644 index 00000000..438a39d6 --- /dev/null +++ b/.idea/copyright/Antoni.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml deleted file mode 100644 index 61f16974..00000000 --- a/.idea/copyright/profiles_settings.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/.idea/dictionaries/Kuba.xml b/.idea/dictionaries/Kuba.xml new file mode 100644 index 00000000..592a5d5e --- /dev/null +++ b/.idea/dictionaries/Kuba.xml @@ -0,0 +1,18 @@ + + + + autoryzacji + ciasteczko + csrf + edziennik + elearning + gson + hebe + idziennik + kuba + synergia + szczodrzyński + szkolny + + + \ No newline at end of file diff --git a/.idea/discord.xml b/.idea/discord.xml deleted file mode 100644 index 59b11d1d..00000000 --- a/.idea/discord.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml deleted file mode 100644 index 15a15b21..00000000 --- a/.idea/encodings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml deleted file mode 100644 index 0dd4b354..00000000 --- a/.idea/kotlinc.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index f834a4ed..00000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml deleted file mode 100644 index 7f68460d..00000000 --- a/.idea/runConfigurations.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..810fce6e --- /dev/null +++ b/LICENSE @@ -0,0 +1,621 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS diff --git a/README.md b/README.md index 3cf34f9b..1646ab6b 100644 --- a/README.md +++ b/README.md @@ -1 +1,85 @@ -Szkolny.eu +
    + +![Readme Banner](.github/readme-banner.png) + +[![Discord](https://img.shields.io/discord/619178050562686988?color=%237289DA&logo=discord&logoColor=white&style=for-the-badge)](https://szkolny.eu/discord) +[![Oficjalna strona](https://img.shields.io/badge/-website-orange?style=for-the-badge&logo=internet-explorer&logoColor=white)](https://szkolny.eu/) +[![Facebook Fanpage](https://img.shields.io/badge/-facebook-blue?style=for-the-badge&logo=facebook&logoColor=white)](https://szkolny.eu/facebook) + +![Wersja Androida](https://img.shields.io/badge/android-4.1%2B-orange?style=for-the-badge&logo=android) +[![Najnowsza wersja](https://img.shields.io/github/v/release/szkolny-eu/szkolny-android?color=%2344CC11&include_prereleases&logo=github&logoColor=white&style=for-the-badge)](https://github.com/szkolny-eu/szkolny-android/releases/latest) +![Licencja](https://img.shields.io/github/license/szkolny-eu/szkolny-android?color=blue&logo=github&logoColor=white&style=for-the-badge) + +[![Release build](https://img.shields.io/github/workflow/status/szkolny-eu/szkolny-android/Release%20build%20-%20official?label=Release&logo=github-actions&logoColor=white&style=for-the-badge)](https://github.com/szkolny-eu/szkolny-android/actions/workflows/build-release-apk.yml) +[![Play build](https://img.shields.io/github/workflow/status/szkolny-eu/szkolny-android/Release%20build%20-%20Google%20Play%20%5BAAB%5D?label=Play&logo=google-play&logoColor=white&style=for-the-badge)](https://github.com/szkolny-eu/szkolny-android/actions/workflows/build-release-aab-play.yml) +[![Nightly build](https://img.shields.io/github/workflow/status/szkolny-eu/szkolny-android/Nightly%20build?label=Nightly&logo=github-actions&logoColor=white&style=for-the-badge)](https://github.com/szkolny-eu/szkolny-android/actions/workflows/build-nightly-apk.yml) + +
    + +## Ważna informacja + +Jak zapewne już wiecie, we wrześniu 2020 r. **firma Librus zabroniła nam** publikowania w sklepie Google Play naszej aplikacji z obsługą dziennika Librus® Synergia. Prowadziliśmy rozmowy, aby **umożliwić Wam wygodny, bezpłatny dostęp do Waszych ocen, wiadomości, zadań domowych**, jednak oczekiwania firmy Librus zdecydowanie przekroczyły wszelkie nasze możliwości finansowe. Mając na uwadze powyższe względy, zdecydowaliśmy się opublikować kod źródłowy aplikacji Szkolny.eu. Liczymy, że dzięki temu aplikacja będzie mogła dalej funkcjonować, być rozwijana, pomagając Wam w czasie zdalnego nauczania i przez kolejne lata nauki. + +__Zachęcamy do [przeczytania całej informacji](https://szkolny.eu/informacja) na naszej stronie.__ + +*- Autorzy Szkolny.eu* + +## O aplikacji + +Szkolny.eu jest nieoficjalną aplikacją, umożliwiającą rodzicom i uczniom dostęp do danych z e-dziennika w każdym smartfonie. Jest to jedyna aplikacja, która posiada wsparcie dla wszystkich najpopularniejszych e-dzienników. Oznacza to, że mając kilka kont w różnych szkołach, wystarczy mieć tylko jedną aplikację. + +### Funkcje aplikacji + +- plan lekcji, terminarz, oceny, wiadomości, zadania domowe, uwagi, frekwencja +- wygodne **widgety** na ekran główny +- łatwa komunikacja z nauczycielami — **odbieranie, wyszukiwanie i wysyłanie wiadomości** +- pobieranie **załączników wiadomości i zadań domowych** +- **powiadomienia** o nowych informacjach na telefonie lub na komputerze +- organizacja zadań domowych i sprawdzianów — łatwe oznaczanie jako wykonane +- obliczanie **średniej ocen** ze wszystkich przedmiotów, oceny proponowane i końcowe +- Symulator edycji ocen — obliczanie średniej z przedmiotu po zmianie dowolnych jego ocen +- **dodawanie własnych wydarzeń** i zadań do terminarza +- nowoczesny i intuicyjny interfejs użytkownika +- **obsługa wielu profili** uczniów — jeżeli jesteś Rodzicem, możesz skonfigurować wszystkie swoje konta uczniowskie i łatwo między nimi przełączać +- opcja **automatycznej synchronizacji** z E-dziennikiem +- opcja Ciszy nocnej — nigdy więcej budzących Cię dźwięków z telefonu + +[Zobacz porównanie funkcji z innymi aplikacjami](https://szkolny.eu/funkcje) + +### Pobieranie + +Najnowsze wersje możesz pobrać z Google Play lub bezpośrednio z naszej strony, w formacie .APK. + +[](https://szkolny.eu/pobierz/android) +[](https://szkolny.eu/pobierz) + +### Kompilacja + +Aby uruchomić aplikację „ze źródeł” należy użyć Android Studio w wersji co najmniej 4.2 Beta 6. Wersja `debug` może wtedy zostać zainstalowana np. na emulatorze Androida. + +Aby zbudować wersję produkcyjną, tzn. `release` należy użyć wariantu `mainRelease` oraz podpisać wyjściowy plik .APK sygnaturą w wersji V1 i V2. + +Warianty `play` oraz `official` są zastrzeżone dla wydań oficjalnych. + +## Współpraca + +PRy wprowadzające nowe funkcje lub naprawiające błędy są mile widziane! + +__Jeśli masz jakieś pytania, zapraszamy na [nasz serwer Discord](https://szkolny.eu/discord).__ + +## Licencja + +Szkolny.eu publikowany jest na licencji [GNU GPLv3](LICENSE). W szczególności, deweloper: +- Może modyfikować oraz usprawniać kod aplikacji +- Może dystrybuować wersje produkcyjne +- Musi opublikować wszelkie wprowadzone zmiany, tzn. publiczny fork tego repozytorium +- Nie może zmieniać licencji ani copyrightu aplikacji + +Dodatkowo: +- Zabronione jest modyfikowanie lub usuwanie kodu odpowiedzialnego za zgodność wersji produkcyjnych z licencją. + +- **Wersje skompilowane nie mogą być dystrybuowane za pomocą Google Play oraz żadnej platformy, na której istnieje oficjalna wersja aplikacji**. + +**Autorzy aplikacji nie biorą odpowiedzialności za używanie aplikacji, modyfikowanie oraz dystrybuowanie.** + +Znaki towarowe zamieszczone w aplikacji oraz tym dokumencie należą do ich prawowitych właścicieli i są używane wyłącznie w celach informacyjnych. diff --git a/agendacalendarview/.gitignore b/agendacalendarview/.gitignore deleted file mode 100644 index 796b96d1..00000000 --- a/agendacalendarview/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/agendacalendarview/build.gradle b/agendacalendarview/build.gradle deleted file mode 100644 index 824ce517..00000000 --- a/agendacalendarview/build.gradle +++ /dev/null @@ -1,54 +0,0 @@ -apply plugin: 'com.android.library' -//apply plugin: 'me.tatarka.retrolambda' - -android { - compileSdkVersion rootProject.ext.compileSdkVersion - - android { - lintOptions { - abortOnError false - } - } - - defaultConfig { - minSdkVersion 14 - targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 1 - versionName "1.0" - } - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - } - debugMinify { - debuggable = true - minifyEnabled = true - proguardFiles 'proguard-android.txt' - } - } - sourceSets { - main { - assets.srcDirs = ['assets'] - } - } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 - } -} - -//apply from: 'https://raw.github.com/chrisbanes/gradle-mvn-push/master/gradle-mvn-push.gradle' - -dependencies { - implementation fileTree(dir: 'libs', include: ['*.jar']) - // Google libraries - implementation "androidx.appcompat:appcompat:${androidXAppCompat}" - implementation "androidx.recyclerview:recyclerview:${androidXRecyclerView}" - implementation "com.google.android.material:material:${googleMaterial}" - - // other libraries - //implementation 'se.emilsjolander:stickylistheaders:2.7.0' - implementation 'com.github.edisonw:StickyListHeaders:master-SNAPSHOT@aar' - implementation 'io.reactivex:rxjava:1.1.1' -} diff --git a/agendacalendarview/src/main/AndroidManifest.xml b/agendacalendarview/src/main/AndroidManifest.xml deleted file mode 100644 index 38e54711..00000000 --- a/agendacalendarview/src/main/AndroidManifest.xml +++ /dev/null @@ -1,3 +0,0 @@ - - diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/AgendaCalendarView.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/AgendaCalendarView.java deleted file mode 100644 index 0d0c0cf4..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/AgendaCalendarView.java +++ /dev/null @@ -1,264 +0,0 @@ -package com.github.tibolte.agendacalendarview; - -import android.animation.Animator; -import android.animation.ObjectAnimator; -import android.content.Context; -import android.content.res.ColorStateList; -import android.content.res.TypedArray; -import android.os.Handler; -import androidx.annotation.NonNull; -import android.util.AttributeSet; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.widget.AbsListView; -import android.widget.AdapterView; -import android.widget.FrameLayout; -import android.widget.LinearLayout; -import android.widget.TextView; - -import com.github.tibolte.agendacalendarview.agenda.AgendaAdapter; -import com.github.tibolte.agendacalendarview.agenda.AgendaView; -import com.github.tibolte.agendacalendarview.calendar.CalendarView; -import com.github.tibolte.agendacalendarview.models.BaseCalendarEvent; -import com.github.tibolte.agendacalendarview.models.CalendarEvent; -import com.github.tibolte.agendacalendarview.models.DayItem; -import com.github.tibolte.agendacalendarview.models.IDayItem; -import com.github.tibolte.agendacalendarview.models.IWeekItem; -import com.github.tibolte.agendacalendarview.models.WeekItem; -import com.github.tibolte.agendacalendarview.render.DefaultEventRenderer; -import com.github.tibolte.agendacalendarview.render.EventRenderer; -import com.github.tibolte.agendacalendarview.utils.BusProvider; -import com.github.tibolte.agendacalendarview.utils.Events; -import com.github.tibolte.agendacalendarview.utils.ListViewScrollTracker; -import com.github.tibolte.agendacalendarview.widgets.FloatingActionButton; - -import java.util.Calendar; -import java.util.List; -import java.util.Locale; - -import se.emilsjolander.stickylistheaders.StickyListHeadersListView; - -/** - * View holding the agenda and calendar view together. - */ -public class AgendaCalendarView extends FrameLayout implements StickyListHeadersListView.OnStickyHeaderChangedListener { - - private static final String LOG_TAG = AgendaCalendarView.class.getSimpleName(); - - private CalendarView mCalendarView; - private AgendaView mAgendaView; - private FloatingActionButton mFloatingActionButton; - - private int mAgendaCurrentDayTextColor, mCalendarHeaderColor, mCalendarHeaderTextColor, mCalendarBackgroundColor, mCalendarDayTextColor, mCalendarPastDayTextColor, mCalendarCurrentDayColor, mFabColor; - private CalendarPickerController mCalendarPickerController; - - public AgendaView getAgendaView() { - return mAgendaView; - } - - private ListViewScrollTracker mAgendaListViewScrollTracker; - private AbsListView.OnScrollListener mAgendaScrollListener = new AbsListView.OnScrollListener() { - int mCurrentAngle; - int mMaxAngle = 85; - - @Override - public void onScrollStateChanged(AbsListView view, int scrollState) { - - } - - @Override - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - int scrollY = mAgendaListViewScrollTracker.calculateScrollY(firstVisibleItem, visibleItemCount); - if (scrollY != 0) { - mFloatingActionButton.show(); - } - //Log.d(LOG_TAG, String.format("Agenda listView scrollY: %d", scrollY)); - /*int toAngle = scrollY / 100; - if (toAngle > mMaxAngle) { - toAngle = mMaxAngle; - } else if (toAngle < -mMaxAngle) { - toAngle = -mMaxAngle; - } - RotateAnimation rotate = new RotateAnimation(mCurrentAngle, toAngle, mFloatingActionButton.getWidth() / 2, mFloatingActionButton.getHeight() / 2); - rotate.setFillAfter(true); - mCurrentAngle = toAngle; - mFloatingActionButton.startAnimation(rotate);*/ - } - }; - - // region Constructors - - public AgendaCalendarView(Context context) { - super(context); - } - - public AgendaCalendarView(Context context, AttributeSet attrs) { - super(context, attrs); - - TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ColorOptionsView, 0, 0); - mAgendaCurrentDayTextColor = a.getColor(R.styleable.ColorOptionsView_agendaCurrentDayTextColor, getResources().getColor(R.color.theme_primary)); - mCalendarHeaderColor = a.getColor(R.styleable.ColorOptionsView_calendarHeaderColor, getResources().getColor(R.color.theme_primary_dark)); - mCalendarHeaderTextColor = a.getColor(R.styleable.ColorOptionsView_calendarHeaderTextColor, getResources().getColor(R.color.theme_text_icons)); - mCalendarBackgroundColor = a.getColor(R.styleable.ColorOptionsView_calendarColor, getResources().getColor(R.color.theme_primary)); - mCalendarDayTextColor = a.getColor(R.styleable.ColorOptionsView_calendarDayTextColor, getResources().getColor(R.color.theme_text_icons)); - mCalendarCurrentDayColor = a.getColor(R.styleable.ColorOptionsView_calendarCurrentDayTextColor, getResources().getColor(R.color.calendar_text_current_day)); - mCalendarPastDayTextColor = a.getColor(R.styleable.ColorOptionsView_calendarPastDayTextColor, getResources().getColor(R.color.theme_light_primary)); - mFabColor = a.getColor(R.styleable.ColorOptionsView_fabColor, getResources().getColor(R.color.theme_accent)); - - LayoutInflater inflater = (LayoutInflater) context - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); - inflater.inflate(R.layout.view_agendacalendar, this, true); - - setAlpha(0f); - } - - // endregion - - // region Class - View - - @Override - protected void onFinishInflate() { - super.onFinishInflate(); - mCalendarView = (CalendarView) findViewById(R.id.calendar_view); - mAgendaView = (AgendaView) findViewById(R.id.agenda_view); - mFloatingActionButton = (FloatingActionButton) findViewById(R.id.floating_action_button); - ColorStateList csl = new ColorStateList(new int[][]{new int[0]}, new int[]{mFabColor}); - mFloatingActionButton.setBackgroundTintList(csl); - - LinearLayout mDayNamesHeader = mCalendarView.findViewById(R.id.cal_day_names); - mDayNamesHeader.setBackgroundColor(mCalendarHeaderColor); - for (int i = 0; i < mDayNamesHeader.getChildCount(); i++) { - TextView txtDay = (TextView) mDayNamesHeader.getChildAt(i); - txtDay.setTextColor(mCalendarHeaderTextColor); - } - mCalendarView.findViewById(R.id.list_week).setBackgroundColor(mCalendarBackgroundColor); - - mAgendaView.getAgendaListView().setOnItemClickListener((AdapterView parent, View view, int position, long id) -> { - mCalendarPickerController.onEventSelected(CalendarManager.getInstance().getEvents().get(position)); - }); - - BusProvider.getInstance().toObserverable() - .subscribe(event -> { - if (event instanceof Events.DayClickedEvent) { - if (mCalendarPickerController != null) - mCalendarPickerController.onDaySelected(((Events.DayClickedEvent) event).getDay()); - } else if (event instanceof Events.EventsFetched) { - ObjectAnimator alphaAnimation = ObjectAnimator.ofFloat(this, "alpha", getAlpha(), 1f).setDuration(500); - alphaAnimation.addListener(new Animator.AnimatorListener() { - @Override - public void onAnimationStart(Animator animation) { - - } - - @Override - public void onAnimationEnd(Animator animation) { - long fabAnimationDelay = 500; - // Just after setting the alpha from this view to 1, we hide the fab. - // It will reappear as soon as the user is scrolling the Agenda view. - new Handler().postDelayed(() -> { - mFloatingActionButton.hide(); - mAgendaListViewScrollTracker = new ListViewScrollTracker(mAgendaView.getAgendaListView()); - mAgendaView.getAgendaListView().setOnScrollListener(mAgendaScrollListener); - mFloatingActionButton.setOnClickListener((v) -> { - mAgendaView.translateList(0); - mAgendaView.getAgendaListView().smoothScrollBy(0, 0); - //mAgendaView.getAgendaListView().getWrappedList().smoothScrollBy(0, 0); - mAgendaView.getAgendaListView().scrollToCurrentDate(CalendarManager.getInstance().getToday()); - new Handler().postDelayed(() -> mFloatingActionButton.hide(), fabAnimationDelay); - }); - }, fabAnimationDelay); - } - - @Override - public void onAnimationCancel(Animator animation) { - - } - - @Override - public void onAnimationRepeat(Animator animation) { - - } - }); - alphaAnimation.start(); - } - }); - } - - // endregion - - // region Interface - StickyListHeadersListView.OnStickyHeaderChangedListener - - @Override - public void onStickyHeaderChanged(StickyListHeadersListView stickyListHeadersListView, View header, int position, long headerId) { - //Log.d(LOG_TAG, String.format("onStickyHeaderChanged, position = %d, headerId = %d", position, headerId)); - - if (CalendarManager.getInstance().getEvents().size() > 0) { - CalendarEvent event = CalendarManager.getInstance().getEvents().get(position); - if (event != null) { - mCalendarView.scrollToDate(event); - mCalendarPickerController.onScrollToDate(event.getInstanceDay()); - } - } - } - - // endregion - - // region Public methods - - public void init(List eventList, Calendar minDate, Calendar maxDate, Locale locale, CalendarPickerController calendarPickerController, EventRenderer ... renderers) { - mCalendarPickerController = calendarPickerController; - - CalendarManager.getInstance(getContext()).buildCal(minDate, maxDate, locale, new DayItem(), new WeekItem()); - - // Feed our views with weeks list and events - mCalendarView.init(CalendarManager.getInstance(getContext()), mCalendarDayTextColor, mCalendarCurrentDayColor, mCalendarPastDayTextColor, eventList); - - // Load agenda events and scroll to current day - AgendaAdapter agendaAdapter = new AgendaAdapter(mAgendaCurrentDayTextColor); - mAgendaView.getAgendaListView().setAdapter(agendaAdapter); - mAgendaView.getAgendaListView().setOnStickyHeaderChangedListener(this); - - CalendarManager.getInstance().loadEvents(eventList, new BaseCalendarEvent()); - BusProvider.getInstance().send(new Events.EventsFetched()); - Log.d(LOG_TAG, "CalendarEventTask finished, event count "+eventList.size()); - - // add default event renderer - addEventRenderer(new DefaultEventRenderer()); - for (EventRenderer renderer: renderers) { - addEventRenderer(renderer); - } - } - - public void init(Locale locale, List lWeeks, List lDays, List lEvents, CalendarPickerController calendarPickerController) { - mCalendarPickerController = calendarPickerController; - - CalendarManager.getInstance(getContext()).loadCal(locale, lWeeks, lDays, lEvents); - - // Feed our views with weeks list and events - mCalendarView.init(CalendarManager.getInstance(getContext()), mCalendarDayTextColor, mCalendarCurrentDayColor, mCalendarPastDayTextColor, lEvents); - - // Load agenda events and scroll to current day - AgendaAdapter agendaAdapter = new AgendaAdapter(mAgendaCurrentDayTextColor); - mAgendaView.getAgendaListView().setAdapter(agendaAdapter); - mAgendaView.getAgendaListView().setOnStickyHeaderChangedListener(this); - - // notify that actually everything is loaded - BusProvider.getInstance().send(new Events.EventsFetched()); - Log.d(LOG_TAG, "CalendarEventTask finished"); - - // add default event renderer - addEventRenderer(new DefaultEventRenderer()); - } - - public void addEventRenderer(@NonNull final EventRenderer renderer) { - AgendaAdapter adapter = (AgendaAdapter) mAgendaView.getAgendaListView().getAdapter(); - adapter.addEventRenderer(renderer); - } - - public void enableFloatingIndicator(boolean enable) { - mFloatingActionButton.setVisibility(enable ? VISIBLE : GONE); - } - - // endregion -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/CalendarManager.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/CalendarManager.java deleted file mode 100644 index c661d32b..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/CalendarManager.java +++ /dev/null @@ -1,267 +0,0 @@ -package com.github.tibolte.agendacalendarview; - -import com.github.tibolte.agendacalendarview.models.CalendarEvent; -import com.github.tibolte.agendacalendarview.models.IDayItem; -import com.github.tibolte.agendacalendarview.models.IWeekItem; -import com.github.tibolte.agendacalendarview.utils.DateHelper; - -import android.content.Context; -import android.util.Log; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import java.util.Locale; - -/** - * This class manages information about the calendar. (Events, weather info...) - * Holds reference to the days list of the calendar. - * As the app is using several views, we want to keep everything in one place. - */ -public class CalendarManager { - - private static final String LOG_TAG = CalendarManager.class.getSimpleName(); - - private static CalendarManager mInstance; - - private Context mContext; - private Locale mLocale; - private Calendar mToday = Calendar.getInstance(); - private SimpleDateFormat mWeekdayFormatter; - private SimpleDateFormat mMonthHalfNameFormat; - - /// instances of classes provided from outside - private IDayItem mCleanDay; - private IWeekItem mCleanWeek; - - /** - * List of days used by the calendar - */ - private List mDays = new ArrayList<>(); - /** - * List of weeks used by the calendar - */ - private List mWeeks = new ArrayList<>(); - /** - * List of events instances - */ - private List mEvents = new ArrayList<>(); - - // region Constructors - - public CalendarManager(Context context) { - this.mContext = context; - } - - public static CalendarManager getInstance(Context context) { - if (mInstance == null) { - mInstance = new CalendarManager(context); - } - return mInstance; - } - - public static CalendarManager getInstance() { - return mInstance; - } - - // endregion - - // region Getters/Setters - - public Locale getLocale() { - return mLocale; - } - - public Context getContext() { - return mContext; - } - - public Calendar getToday() { - return mToday; - } - - public void setToday(Calendar today) { - this.mToday = today; - } - - public List getWeeks() { - return mWeeks; - } - - public List getEvents() { - return mEvents; - } - - public List getDays() { - return mDays; - } - - public SimpleDateFormat getWeekdayFormatter() { - return mWeekdayFormatter; - } - - public SimpleDateFormat getMonthHalfNameFormat() { - return mMonthHalfNameFormat; - } - - // endregion - - // region Public methods - - public void buildCal(Calendar minDate, Calendar maxDate, Locale locale, IDayItem cleanDay, IWeekItem cleanWeek) { - if (minDate == null || maxDate == null) { - throw new IllegalArgumentException( - "minDate and maxDate must be non-null."); - } - if (minDate.after(maxDate)) { - throw new IllegalArgumentException( - "minDate must be before maxDate."); - } - if (locale == null) { - throw new IllegalArgumentException("Locale is null."); - } - - setLocale(locale); - - mDays.clear(); - mWeeks.clear(); - mEvents.clear(); - - mCleanDay = cleanDay; - mCleanWeek = cleanWeek; - - Calendar mMinCal = Calendar.getInstance(mLocale); - Calendar mMaxCal = Calendar.getInstance(mLocale); - Calendar mWeekCounter = Calendar.getInstance(mLocale); - - mMinCal.setTime(minDate.getTime()); - mMaxCal.setTime(maxDate.getTime()); - - // maxDate is exclusive, here we bump back to the previous day, as maxDate if December 1st, 2020, - // we don't include that month in our list - mMaxCal.add(Calendar.MINUTE, -1); - - // Now iterate we iterate between mMinCal and mMaxCal so we build our list of weeks - mWeekCounter.setTime(mMinCal.getTime()); - int maxMonth = mMaxCal.get(Calendar.MONTH); - int maxYear = mMaxCal.get(Calendar.YEAR); - - int currentMonth = mWeekCounter.get(Calendar.MONTH); - int currentYear = mWeekCounter.get(Calendar.YEAR); - - // Loop through the weeks - while ((currentMonth <= maxMonth // Up to, including the month. - || currentYear < maxYear) // Up to the year. - && currentYear < maxYear + 1) { // But not > next yr. - - Date date = mWeekCounter.getTime(); - // Build our week list - int currentWeekOfYear = mWeekCounter.get(Calendar.WEEK_OF_YEAR); - - IWeekItem weekItem = cleanWeek.copy(); - weekItem.setWeekInYear(currentWeekOfYear); - weekItem.setYear(currentYear); - weekItem.setDate(date); - weekItem.setMonth(currentMonth); - weekItem.setLabel(mMonthHalfNameFormat.format(date)); - List dayItems = getDayCells(mWeekCounter); // gather days for the built week - weekItem.setDayItems(dayItems); - mWeeks.add(weekItem); - - //Log.d(LOG_TAG, String.format("Adding week: %s", weekItem)); - - mWeekCounter.add(Calendar.WEEK_OF_YEAR, 1); - - currentMonth = mWeekCounter.get(Calendar.MONTH); - currentYear = mWeekCounter.get(Calendar.YEAR); - } - } - - public void loadEvents(List eventList, CalendarEvent noEvent) { - - for (IWeekItem weekItem : getWeeks()) { - for (IDayItem dayItem : weekItem.getDayItems()) { - boolean isEventForDay = false; - boolean isShowBadgeForDay = false; - for (CalendarEvent event : eventList) { - if (DateHelper.isBetweenInclusive(dayItem.getDate(), event.getStartTime(), event.getEndTime())) { - CalendarEvent copy = event.copy(); - - if (copy.getShowBadge()) { - isShowBadgeForDay = true; - } - - Calendar dayInstance = Calendar.getInstance(); - dayInstance.setTime(dayItem.getDate()); - copy.setInstanceDay(dayInstance); - copy.setDayReference(dayItem); - copy.setWeekReference(weekItem); - // add instances in chronological order - getEvents().add(copy); - isEventForDay = true; - } - } - if (!isEventForDay) { - Calendar dayInstance = Calendar.getInstance(); - dayInstance.setTime(dayItem.getDate()); - CalendarEvent copy = noEvent.copy(); - - copy.setInstanceDay(dayInstance); - copy.setDayReference(dayItem); - copy.setWeekReference(weekItem); - copy.setLocation(""); - copy.setTitle(getContext().getResources().getString(R.string.agenda_event_no_events)); - copy.setPlaceholder(true); - getEvents().add(copy); - } - dayItem.setShowBadge(isShowBadgeForDay); - } - } - } - - public void loadCal (Locale locale, List lWeeks, List lDays, List lEvents) { - mWeeks = lWeeks; - mDays = lDays; - mEvents = lEvents; - setLocale(locale); - } - - // endregion - - // region Private methods - - private List getDayCells(Calendar startCal) { - Calendar cal = Calendar.getInstance(mLocale); - cal.setTime(startCal.getTime()); - List dayItems = new ArrayList<>(); - - int firstDayOfWeek = cal.get(Calendar.DAY_OF_WEEK); - int offset = cal.getFirstDayOfWeek() - firstDayOfWeek; - if (offset > 0) { - offset -= 7; - } - cal.add(Calendar.DATE, offset); - - //Log.d(LOG_TAG, String.format("Buiding row week starting at %s", cal.getTime())); - for (int c = 0; c < 7; c++) { - IDayItem dayItem = mCleanDay.copy(); - dayItem.buildDayItemFromCal(cal); - dayItems.add(dayItem); - cal.add(Calendar.DATE, 1); - } - - mDays.addAll(dayItems); - return dayItems; - } - - private void setLocale(Locale locale) { - this.mLocale = locale; - setToday(Calendar.getInstance(mLocale)); - mWeekdayFormatter = new SimpleDateFormat(getContext().getString(R.string.day_name_format), mLocale); - mMonthHalfNameFormat = new SimpleDateFormat(getContext().getString(R.string.month_half_name_format), locale); - } - - // endregion -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/CalendarPickerController.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/CalendarPickerController.java deleted file mode 100644 index a2a86dde..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/CalendarPickerController.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.github.tibolte.agendacalendarview; - -import com.github.tibolte.agendacalendarview.models.CalendarEvent; -import com.github.tibolte.agendacalendarview.models.IDayItem; - -import java.util.Calendar; - -public interface CalendarPickerController { - void onDaySelected(IDayItem dayItem); - - void onEventSelected(CalendarEvent event); - - void onScrollToDate(Calendar calendar); -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/agenda/AgendaAdapter.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/agenda/AgendaAdapter.java deleted file mode 100644 index 2e6c6d31..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/agenda/AgendaAdapter.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.github.tibolte.agendacalendarview.agenda; - -import com.github.tibolte.agendacalendarview.models.CalendarEvent; -import com.github.tibolte.agendacalendarview.render.DefaultEventRenderer; -import com.github.tibolte.agendacalendarview.render.EventRenderer; - -import androidx.annotation.NonNull; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.BaseAdapter; - -import java.util.ArrayList; -import java.util.List; - -import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter; - -/** - * Adapter for the agenda, implements StickyListHeadersAdapter. - * Days as sections and CalendarEvents as list items. - */ -public class AgendaAdapter extends BaseAdapter implements StickyListHeadersAdapter { - - private List mEvents = new ArrayList<>(); - private List> mRenderers = new ArrayList<>(); - private int mCurrentDayColor; - - // region Constructor - - public AgendaAdapter(int currentDayTextColor) { - this.mCurrentDayColor = currentDayTextColor; - } - - // endregion - - // region Public methods - - public void updateEvents(List events) { - this.mEvents.clear(); - this.mEvents.addAll(events); - notifyDataSetChanged(); - } - - // endregion - - // region Interface - StickyListHeadersAdapter - - @Override - public View getHeaderView(int position, View convertView, ViewGroup parent) { - AgendaHeaderView agendaHeaderView = (AgendaHeaderView) convertView; - if (agendaHeaderView == null) { - agendaHeaderView = AgendaHeaderView.inflate(parent); - } - agendaHeaderView.setDay(getItem(position).getInstanceDay(), mCurrentDayColor, getItem(position).getDayReference().getShowBadge()); - return agendaHeaderView; - } - - @Override - public long getHeaderId(int position) { - return mEvents.get(position).getInstanceDay().getTimeInMillis(); - } - - // endregion - - // region Class - BaseAdapter - - @Override - public int getCount() { - return mEvents.size(); - } - - @Override - public CalendarEvent getItem(int position) { - return mEvents.get(position); - } - - @Override - public long getItemId(int position) { - return position; - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - EventRenderer eventRenderer = new DefaultEventRenderer(); - final CalendarEvent event = getItem(position); - - // Search for the correct event renderer - for (EventRenderer renderer : mRenderers) { - if(event.getClass().isAssignableFrom(renderer.getRenderType())) { - eventRenderer = renderer; - break; - } - } - convertView = LayoutInflater.from(parent.getContext()) - .inflate(eventRenderer.getEventLayout(), parent, false); - eventRenderer.render(convertView, event); - return convertView; - } - - public void addEventRenderer(@NonNull final EventRenderer renderer) { - mRenderers.add(renderer); - } - - // endregion -} \ No newline at end of file diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/agenda/AgendaEventView.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/agenda/AgendaEventView.java deleted file mode 100644 index 198f65cd..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/agenda/AgendaEventView.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.github.tibolte.agendacalendarview.agenda; - -import com.github.tibolte.agendacalendarview.R; - -import android.content.Context; -import android.util.AttributeSet; -import android.view.LayoutInflater; -import android.view.ViewGroup; -import android.widget.LinearLayout; - -/** - * List item view for the StickyHeaderListView of the agenda view - */ -public class AgendaEventView extends LinearLayout { - public static AgendaEventView inflate(ViewGroup parent) { - return (AgendaEventView) LayoutInflater.from(parent.getContext()).inflate(R.layout.view_agenda_event, parent, false); - } - - // region Constructors - - public AgendaEventView(Context context) { - this(context, null); - } - - public AgendaEventView(Context context, AttributeSet attrs) { - this(context, attrs, 0); - } - - public AgendaEventView(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - setPadding(getResources().getDimensionPixelSize(R.dimen.agenda_event_view_padding_left), - getResources().getDimensionPixelSize(R.dimen.agenda_event_view_padding_top), - getResources().getDimensionPixelSize(R.dimen.agenda_event_view_padding_right), - getResources().getDimensionPixelSize(R.dimen.agenda_event_view_padding_bottom)); - } - - // endregion -} \ No newline at end of file diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/agenda/AgendaHeaderView.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/agenda/AgendaHeaderView.java deleted file mode 100644 index 36b16ddb..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/agenda/AgendaHeaderView.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.github.tibolte.agendacalendarview.agenda; - -import com.github.tibolte.agendacalendarview.CalendarManager; -import com.github.tibolte.agendacalendarview.R; -import com.github.tibolte.agendacalendarview.utils.DateHelper; - -import android.content.Context; -import android.content.res.Resources; -import android.graphics.drawable.GradientDrawable; -import android.util.AttributeSet; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.LinearLayout; -import android.widget.TextView; - -import java.text.SimpleDateFormat; -import java.util.Calendar; - -/** - * Header view for the StickyHeaderListView of the agenda view - */ -public class AgendaHeaderView extends LinearLayout { - - public static AgendaHeaderView inflate(ViewGroup parent) { - return (AgendaHeaderView) LayoutInflater.from(parent.getContext()).inflate(R.layout.view_agenda_header, parent, false); - } - - // region Constructors - - public AgendaHeaderView(Context context) { - super(context); - } - - public AgendaHeaderView(Context context, AttributeSet attrs) { - super(context, attrs); - } - - public AgendaHeaderView(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - } - - // endregion - - // region Public methods - - public void setDay(Calendar day, int currentDayTextColor, boolean showBadge) { - TextView txtDayOfMonth = (TextView) findViewById(R.id.view_agenda_day_of_month); - TextView txtDayOfWeek = (TextView) findViewById(R.id.view_agenda_day_of_week); - TextView txtDay = (TextView) findViewById(R.id.view_agenda_day_text); - View circleView = findViewById(R.id.view_day_circle_selected); - - Calendar today = CalendarManager.getInstance().getToday(); - - SimpleDateFormat dayWeekFormatter = new SimpleDateFormat(getContext().getString(R.string.day_name_format), CalendarManager.getInstance().getLocale()); - SimpleDateFormat dayWeekLongFormatter = new SimpleDateFormat("EEEE", CalendarManager.getInstance().getLocale()); - - txtDayOfMonth.setTextColor(getResources().getColor(R.color.calendar_text_default)); - txtDayOfWeek.setTextColor(getResources().getColor(R.color.calendar_text_default)); - - if (DateHelper.sameDate(day, today)) { - txtDayOfMonth.setTextColor(currentDayTextColor); - circleView.setVisibility(VISIBLE); - GradientDrawable drawable = (GradientDrawable) circleView.getBackground(); - drawable.setStroke((int) (2 * Resources.getSystem().getDisplayMetrics().density), currentDayTextColor); - } else if (showBadge) { - circleView.setVisibility(VISIBLE); - GradientDrawable drawable = (GradientDrawable) circleView.getBackground(); - drawable.setStroke((int) (2 * Resources.getSystem().getDisplayMetrics().density), 0xffff0000); - } - else { - circleView.setVisibility(INVISIBLE); - } - - txtDayOfMonth.setText(String.valueOf(day.get(Calendar.DAY_OF_MONTH))); - txtDayOfWeek.setText(dayWeekFormatter.format(day.getTime())); - //txtDay.setText(dayWeekLongFormatter.format(day.getTime())); - } - - // endregion -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/agenda/AgendaListView.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/agenda/AgendaListView.java deleted file mode 100644 index 235b04c6..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/agenda/AgendaListView.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.github.tibolte.agendacalendarview.agenda; - -import com.github.tibolte.agendacalendarview.CalendarManager; -import com.github.tibolte.agendacalendarview.models.CalendarEvent; -import com.github.tibolte.agendacalendarview.utils.DateHelper; - -import android.content.Context; -import android.util.AttributeSet; - -import java.util.Calendar; -import java.util.List; - -import se.emilsjolander.stickylistheaders.StickyListHeadersListView; - -/** - * StickyListHeadersListView to scroll chronologically through events. - */ -public class AgendaListView extends StickyListHeadersListView { - - // region Constructors - - public AgendaListView(Context context) { - super(context); - } - - public AgendaListView(Context context, AttributeSet attrs) { - super(context, attrs); - } - - public AgendaListView(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - } - - // endregion - - // region Public methods - - public void scrollToCurrentDate(Calendar today) { - List events = CalendarManager.getInstance().getEvents(); - - int toIndex = 0; - for (int i = 0; i < events.size(); i++) { - if (DateHelper.sameDate(today, events.get(i).getInstanceDay())) { - toIndex = i; - break; - } - } - - final int finalToIndex = toIndex; - post(()->setSelection(finalToIndex)); - } - - // endregion -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/agenda/AgendaView.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/agenda/AgendaView.java deleted file mode 100644 index 80b317da..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/agenda/AgendaView.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.github.tibolte.agendacalendarview.agenda; - -import android.animation.Animator; -import android.animation.ObjectAnimator; -import android.content.Context; -import android.util.AttributeSet; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.ViewGroup; -import android.view.ViewTreeObserver; -import android.widget.FrameLayout; - -import com.github.tibolte.agendacalendarview.CalendarManager; -import com.github.tibolte.agendacalendarview.R; -import com.github.tibolte.agendacalendarview.utils.BusProvider; -import com.github.tibolte.agendacalendarview.utils.Events; - -public class AgendaView extends FrameLayout { - - private AgendaListView mAgendaListView; - private View mShadowView; - - // region Constructors - - public AgendaView(Context context) { - super(context); - } - - public AgendaView(Context context, AttributeSet attrs) { - super(context, attrs); - - LayoutInflater inflater = (LayoutInflater) context - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); - inflater.inflate(R.layout.view_agenda, this, true); - } - - // endregion - - // region Class - View - - @Override - protected void onFinishInflate() { - super.onFinishInflate(); - - mAgendaListView = (AgendaListView) findViewById(R.id.agenda_listview); - mShadowView = findViewById(R.id.view_shadow); - - BusProvider.getInstance().toObserverable() - .subscribe(event -> { - if (event instanceof Events.DayClickedEvent) { - Events.DayClickedEvent clickedEvent = (Events.DayClickedEvent) event; - getAgendaListView().scrollToCurrentDate(clickedEvent.getCalendar()); - } else if (event instanceof Events.CalendarScrolledEvent) { - int offset = (int) (3 * getResources().getDimension(R.dimen.day_cell_height)); - translateList(offset); - } else if (event instanceof Events.EventsFetched) { - if (getAgendaListView().getAdapter() != null) - ((AgendaAdapter) getAgendaListView().getAdapter()).updateEvents(CalendarManager.getInstance().getEvents()); - - getViewTreeObserver().addOnGlobalLayoutListener( - new ViewTreeObserver.OnGlobalLayoutListener() { - @Override - public void onGlobalLayout() { - if (getWidth() != 0 && getHeight() != 0) { - // display only two visible rows on the calendar view - ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams(); - int height = getHeight(); - int margin = (int) (getContext().getResources().getDimension(R.dimen.calendar_header_height) + 2 * getContext().getResources().getDimension(R.dimen.day_cell_height)); - layoutParams.height = height; - layoutParams.setMargins(0, margin, 0, 0); - setLayoutParams(layoutParams); - - getAgendaListView().scrollToCurrentDate(CalendarManager.getInstance().getToday()); - - getViewTreeObserver().removeGlobalOnLayoutListener(this); - } - } - } - - ); - } else if (event instanceof Events.ForecastFetched) { - ((AgendaAdapter) getAgendaListView().getAdapter()).updateEvents(CalendarManager.getInstance().getEvents()); - } - }); - } - - @Override - public boolean dispatchTouchEvent(MotionEvent event) { - int eventaction = event.getAction(); - - switch (eventaction) { - case MotionEvent.ACTION_DOWN: - // if the user touches the listView, we put it back to the top - translateList(0); - break; - default: - break; - } - - return super.dispatchTouchEvent(event); - } - - // endregion - - // region Public methods - - public AgendaListView getAgendaListView() { - return mAgendaListView; - } - - public void translateList(int targetY) { - if (targetY != getTranslationY()) { - ObjectAnimator mover = ObjectAnimator.ofFloat(this, "translationY", targetY); - mover.setDuration(150); - mover.addListener(new Animator.AnimatorListener() { - @Override - public void onAnimationStart(Animator animation) { - //mShadowView.setVisibility(GONE); - } - - @Override - public void onAnimationEnd(Animator animation) { - if (targetY == 0) { - BusProvider.getInstance().send(new Events.AgendaListViewTouchedEvent()); - } - //mShadowView.setVisibility(VISIBLE); - } - - @Override - public void onAnimationCancel(Animator animation) { - - } - - @Override - public void onAnimationRepeat(Animator animation) { - - } - }); - mover.start(); - } - } - - // endregion -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/calendar/CalendarView.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/calendar/CalendarView.java deleted file mode 100644 index 67d7490c..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/calendar/CalendarView.java +++ /dev/null @@ -1,279 +0,0 @@ -package com.github.tibolte.agendacalendarview.calendar; - -import com.github.tibolte.agendacalendarview.CalendarManager; -import com.github.tibolte.agendacalendarview.R; -import com.github.tibolte.agendacalendarview.calendar.weekslist.WeekListView; -import com.github.tibolte.agendacalendarview.calendar.weekslist.WeeksAdapter; -import com.github.tibolte.agendacalendarview.models.CalendarEvent; -import com.github.tibolte.agendacalendarview.models.IDayItem; -import com.github.tibolte.agendacalendarview.models.IWeekItem; -import com.github.tibolte.agendacalendarview.utils.BusProvider; -import com.github.tibolte.agendacalendarview.utils.DateHelper; -import com.github.tibolte.agendacalendarview.utils.Events; - -import android.content.Context; -import androidx.recyclerview.widget.LinearLayoutManager; -import android.util.AttributeSet; -import android.view.LayoutInflater; -import android.view.ViewGroup; -import android.view.ViewTreeObserver; -import android.widget.LinearLayout; -import android.widget.TextView; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.List; -import java.util.Locale; - -/** - * The calendar view is a freely scrolling view that allows the user to browse between days of the - * year. - */ -public class CalendarView extends LinearLayout { - - private static final String LOG_TAG = CalendarView.class.getSimpleName(); - - /** - * Top of the calendar view layout, the week days list - */ - private LinearLayout mDayNamesHeader; - /** - * Part of the calendar view layout always visible, the weeks list - */ - private WeekListView mListViewWeeks; - /** - * The adapter for the weeks list - */ - private WeeksAdapter mWeeksAdapter; - /** - * The current highlighted day in blue - */ - private IDayItem mSelectedDay; - /** - * The current row displayed at top of the list - */ - private int mCurrentListPosition; - - // region Constructors - - public CalendarView(Context context) { - super(context); - } - - public CalendarView(Context context, AttributeSet attrs) { - super(context, attrs); - - LayoutInflater inflater = (LayoutInflater) context - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); - inflater.inflate(R.layout.view_calendar, this, true); - - setOrientation(VERTICAL); - } - - // endregion - - public IDayItem getSelectedDay() { - return mSelectedDay; - } - - public void setSelectedDay(IDayItem mSelectedDay) { - this.mSelectedDay = mSelectedDay; - } - - public WeekListView getListViewWeeks() { - return mListViewWeeks; - } - - // region Class - View - - @Override - protected void onFinishInflate() { - super.onFinishInflate(); - - mDayNamesHeader = (LinearLayout) findViewById(R.id.cal_day_names); - mListViewWeeks = (WeekListView) findViewById(R.id.list_week); - mListViewWeeks.setLayoutManager(new LinearLayoutManager(getContext())); - mListViewWeeks.setHasFixedSize(true); - mListViewWeeks.setItemAnimator(null); - mListViewWeeks.setSnapEnabled(true); - - // display only two visible rows on the calendar view - getViewTreeObserver().addOnGlobalLayoutListener( - new ViewTreeObserver.OnGlobalLayoutListener() { - @Override - public void onGlobalLayout() { - if (getWidth() != 0 && getHeight() != 0) { - collapseCalendarView(); - getViewTreeObserver().removeGlobalOnLayoutListener(this); - } - } - } - ); - } - - @Override - protected void onAttachedToWindow() { - super.onAttachedToWindow(); - - BusProvider.getInstance().toObserverable() - .subscribe(event -> { - if (event instanceof Events.CalendarScrolledEvent) { - expandCalendarView(); - } else if (event instanceof Events.AgendaListViewTouchedEvent) { - collapseCalendarView(); - } else if (event instanceof Events.DayClickedEvent) { - Events.DayClickedEvent clickedEvent = (Events.DayClickedEvent) event; - updateSelectedDay(clickedEvent.getCalendar(), clickedEvent.getDay()); - } - }); - } - - // endregion - - // region Public methods - - public void init(CalendarManager calendarManager, int dayTextColor, int currentDayTextColor, int pastDayTextColor, List eventList) { - Calendar today = calendarManager.getToday(); - Locale locale = calendarManager.getLocale(); - SimpleDateFormat weekDayFormatter = calendarManager.getWeekdayFormatter(); - List weeks = calendarManager.getWeeks(); - - setUpHeader(today, weekDayFormatter, locale); - setUpAdapter(today, weeks, dayTextColor, currentDayTextColor, pastDayTextColor, eventList); - scrollToDate(today, weeks); - } - - /** - * Fired when the Agenda list view changes section. - * - * @param calendarEvent The event for the selected position in the agenda listview. - */ - public void scrollToDate(final CalendarEvent calendarEvent) { - mListViewWeeks.post(()->scrollToPosition(updateSelectedDay(calendarEvent.getInstanceDay(), calendarEvent.getDayReference()))); - } - - public void scrollToDate(Calendar today, List weeks) { - Integer currentWeekIndex = null; - - for (int c = 0; c < weeks.size(); c++) { - if (DateHelper.sameWeek(today, weeks.get(c))) { - currentWeekIndex = c; - break; - } - } - - if (currentWeekIndex != null) { - final Integer finalCurrentWeekIndex = currentWeekIndex; - mListViewWeeks.post(() -> scrollToPosition(finalCurrentWeekIndex)); - } - } - - public void setBackgroundColor(int color) { - mListViewWeeks.setBackgroundColor(color); - } - - // endregion - - // region Private methods - - private void scrollToPosition(int targetPosition) { - LinearLayoutManager layoutManager = ((LinearLayoutManager) mListViewWeeks.getLayoutManager()); - layoutManager.scrollToPosition(targetPosition); - } - - private void updateItemAtPosition(int position) { - WeeksAdapter weeksAdapter = (WeeksAdapter) mListViewWeeks.getAdapter(); - weeksAdapter.notifyItemChanged(position); - } - - /** - * Creates a new adapter if necessary and sets up its parameters. - */ - private void setUpAdapter(Calendar today, List weeks, int dayTextColor, int currentDayTextColor, int pastDayTextColor, List events) { - BusProvider.getInstance().toObserverable() - .subscribe(event -> { - if (event instanceof Events.EventsFetched) { - //Log.d("CalendarView", "events size "+events.size()); - if (mWeeksAdapter == null) { - //Log.d(LOG_TAG, "Setting adapter with today's calendar: " + today.toString()); - mWeeksAdapter = new WeeksAdapter(getContext(), today, dayTextColor, currentDayTextColor, pastDayTextColor, events); - mListViewWeeks.setAdapter(mWeeksAdapter); - } - mWeeksAdapter.updateWeeksItems(weeks); - }}); - - } - - private void setUpHeader(Calendar today, SimpleDateFormat weekDayFormatter, Locale locale) { - int daysPerWeek = 7; - String[] dayLabels = new String[daysPerWeek]; - Calendar cal = Calendar.getInstance(CalendarManager.getInstance(getContext()).getLocale()); - cal.setTime(today.getTime()); - int firstDayOfWeek = cal.getFirstDayOfWeek(); - for (int count = 0; count < 7; count++) { - cal.set(Calendar.DAY_OF_WEEK, firstDayOfWeek + count); - if (locale.getLanguage().equals("en")) { - dayLabels[count] = weekDayFormatter.format(cal.getTime()).toUpperCase(locale); - } else { - dayLabels[count] = weekDayFormatter.format(cal.getTime()); - } - } - - for (int i = 0; i < mDayNamesHeader.getChildCount(); i++) { - TextView txtDay = (TextView) mDayNamesHeader.getChildAt(i); - txtDay.setText(dayLabels[i]); - } - } - - private void expandCalendarView() { - ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams(); - layoutParams.height = (int) (getResources().getDimension(R.dimen.calendar_header_height) + 5 * getResources().getDimension(R.dimen.day_cell_height)); - setLayoutParams(layoutParams); - } - - private void collapseCalendarView() { - ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams(); - layoutParams.height = (int) (getResources().getDimension(R.dimen.calendar_header_height) + 2 * getResources().getDimension(R.dimen.day_cell_height)); - setLayoutParams(layoutParams); - } - - /** - * Update a selected cell day item. - * - * @param calendar The Calendar instance of the day selected. - * @param dayItem The DayItem information held by the cell item. - * @return The selected row of the weeks list, to be updated. - */ - private int updateSelectedDay(Calendar calendar, IDayItem dayItem) { - Integer currentWeekIndex = null; - - // update highlighted/selected day - if (!dayItem.equals(getSelectedDay())) { - dayItem.setSelected(true); - if (getSelectedDay() != null) { - getSelectedDay().setSelected(false); - } - setSelectedDay(dayItem); - } - - for (int c = 0; c < CalendarManager.getInstance().getWeeks().size(); c++) { - if (DateHelper.sameWeek(calendar, CalendarManager.getInstance().getWeeks().get(c))) { - currentWeekIndex = c; - break; - } - } - - if (currentWeekIndex != null) { - // highlighted day has changed, update the rows concerned - if (currentWeekIndex != mCurrentListPosition) { - updateItemAtPosition(mCurrentListPosition); - } - mCurrentListPosition = currentWeekIndex; - updateItemAtPosition(currentWeekIndex); - } - - return mCurrentListPosition; - } - - // endregion -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/calendar/weekslist/WeekListView.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/calendar/weekslist/WeekListView.java deleted file mode 100644 index 099bc6eb..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/calendar/weekslist/WeekListView.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.github.tibolte.agendacalendarview.calendar.weekslist; - -import com.github.tibolte.agendacalendarview.utils.BusProvider; -import com.github.tibolte.agendacalendarview.utils.Events; - -import android.content.Context; -import androidx.recyclerview.widget.RecyclerView; -import android.util.AttributeSet; -import android.view.View; - -public class WeekListView extends RecyclerView { - private boolean mUserScrolling = false; - private boolean mScrolling = false; - - // region Constructors - - public WeekListView(Context context) { - super(context); - } - - public WeekListView(Context context, AttributeSet attrs) { - super(context, attrs); - } - - public WeekListView(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - } - - // endregion - - // region Public methods - - /** - * Enable snapping behaviour for this recyclerView - * - * @param enabled enable or disable the snapping behaviour - */ - public void setSnapEnabled(boolean enabled) { - if (enabled) { - addOnScrollListener(mScrollListener); - } else { - removeOnScrollListener(mScrollListener); - } - } - - // endregion - - // region Private methods - - private OnScrollListener mScrollListener = new OnScrollListener() { - @Override - public void onScrolled(RecyclerView recyclerView, int dx, int dy) { - super.onScrolled(recyclerView, dx, dy); - } - - @Override - public void onScrollStateChanged(RecyclerView recyclerView, int newState) { - super.onScrollStateChanged(recyclerView, newState); - final WeeksAdapter weeksAdapter = (WeeksAdapter) getAdapter(); - - switch (newState) { - case SCROLL_STATE_IDLE: - if (mUserScrolling) { - scrollToView(getCenterView()); - postDelayed(() -> weeksAdapter.setDragging(false), 700); // Wait for recyclerView to settle - } - - mUserScrolling = false; - mScrolling = false; - break; - // If scroll is caused by a touch (scroll touch, not any touch) - case SCROLL_STATE_DRAGGING: - BusProvider.getInstance().send(new Events.CalendarScrolledEvent()); - // If scroll was initiated already, this is not a user scrolling, but probably a tap, else set userScrolling - if (!mScrolling) { - mUserScrolling = true; - } - weeksAdapter.setDragging(true); - break; - case SCROLL_STATE_SETTLING: - // The user's finger is not touching the list anymore, no need - // for any alpha animation then - weeksAdapter.setAlphaSet(true); - mScrolling = true; - break; - } - } - }; - - private View getChildClosestToPosition(int y) { - if (getChildCount() <= 0) { - return null; - } - - int itemHeight = getChildAt(0).getMeasuredHeight(); - - int closestY = 9999; - View closestChild = null; - - for (int i = 0; i < getChildCount(); i++) { - View child = getChildAt(i); - - int childCenterY = ((int) child.getY() + (itemHeight / 2)); - int yDistance = childCenterY - y; - - // If child center is closer than previous closest, set it as closest - if (Math.abs(yDistance) < Math.abs(closestY)) { - closestY = yDistance; - closestChild = child; - } - } - - return closestChild; - } - - private View getCenterView() { - return getChildClosestToPosition(getMeasuredHeight() / 2); - } - - private void scrollToView(View child) { - if (child == null) { - return; - } - - stopScroll(); - - int scrollDistance = getScrollDistance(child); - - if (scrollDistance != 0) { - smoothScrollBy(0, scrollDistance); - } - } - - private int getScrollDistance(View child) { - int itemHeight = getChildAt(0).getMeasuredHeight(); - int centerY = getMeasuredHeight() / 2; - - int childCenterY = ((int) child.getY() + (itemHeight / 2)); - - return childCenterY - centerY; - } - - // endregion -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/calendar/weekslist/WeeksAdapter.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/calendar/weekslist/WeeksAdapter.java deleted file mode 100644 index df2177df..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/calendar/weekslist/WeeksAdapter.java +++ /dev/null @@ -1,321 +0,0 @@ -package com.github.tibolte.agendacalendarview.calendar.weekslist; - -import com.github.tibolte.agendacalendarview.CalendarManager; -import com.github.tibolte.agendacalendarview.R; -import com.github.tibolte.agendacalendarview.models.CalendarEvent; -import com.github.tibolte.agendacalendarview.models.IDayItem; -import com.github.tibolte.agendacalendarview.models.IWeekItem; -import com.github.tibolte.agendacalendarview.utils.BusProvider; -import com.github.tibolte.agendacalendarview.utils.DateHelper; -import com.github.tibolte.agendacalendarview.utils.Events; - -import android.animation.Animator; -import android.animation.AnimatorSet; -import android.animation.ObjectAnimator; -import android.content.Context; -import android.content.res.Resources; -import android.graphics.PorterDuff; -import android.graphics.PorterDuffColorFilter; -import android.graphics.Typeface; -import android.graphics.drawable.GradientDrawable; - -import androidx.recyclerview.widget.RecyclerView; - -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.FrameLayout; -import android.widget.LinearLayout; -import android.widget.TextView; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; - -public class WeeksAdapter extends RecyclerView.Adapter { - - public static final long FADE_DURATION = 250; - - private Context mContext; - private Calendar mToday; - private List mWeeksList = new ArrayList<>(); - private List mEventList = new ArrayList<>(); - private boolean mDragging; - private boolean mAlphaSet; - private int mDayTextColor, mPastDayTextColor, mCurrentDayColor; - - // region Constructor - - public WeeksAdapter(Context context, Calendar today, int dayTextColor, int currentDayTextColor, int pastDayTextColor, List events) { - this.mToday = today; - this.mContext = context; - this.mDayTextColor = dayTextColor; - this.mCurrentDayColor = currentDayTextColor; - this.mPastDayTextColor = pastDayTextColor; - this.mEventList = events; - } - - // endregion - - public void updateWeeksItems(List weekItems) { - this.mWeeksList.clear(); - this.mWeeksList.addAll(weekItems); - notifyDataSetChanged(); - } - - // region Getters/setters - - public List getWeeksList() { - return mWeeksList; - } - - public boolean isDragging() { - return mDragging; - } - - public void setDragging(boolean dragging) { - if (dragging != this.mDragging) { - this.mDragging = dragging; - notifyItemRangeChanged(0, mWeeksList.size()); - } - } - - public boolean isAlphaSet() { - return mAlphaSet; - } - - public void setAlphaSet(boolean alphaSet) { - mAlphaSet = alphaSet; - } - - // endregion - - // region RecyclerView.Adapter methods - - @Override - public WeekViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_week, parent, false); - return new WeekViewHolder(view); - } - - @Override - public void onBindViewHolder(WeekViewHolder weekViewHolder, int position) { - IWeekItem weekItem = mWeeksList.get(position); - weekViewHolder.bindWeek(weekItem, mToday); - } - - @Override - public int getItemCount() { - return mWeeksList.size(); - } - - // endregion - - // region Class - WeekViewHolder - - public class WeekViewHolder extends RecyclerView.ViewHolder { - - /** - * List of layout containers for each day - */ - private List mCells; - private TextView mTxtMonth; - private FrameLayout mMonthBackground; - - public WeekViewHolder(View itemView) { - super(itemView); - mTxtMonth = (TextView) itemView.findViewById(R.id.month_label); - mMonthBackground = (FrameLayout) itemView.findViewById(R.id.month_background); - LinearLayout daysContainer = (LinearLayout) itemView.findViewById(R.id.week_days_container); - setUpChildren(daysContainer); - } - - public void bindWeek(IWeekItem weekItem, Calendar today) { - setUpMonthOverlay(); - - List dayItems = weekItem.getDayItems(); - - for (int c = 0; c < dayItems.size(); c++) { - final IDayItem dayItem = dayItems.get(c); - LinearLayout cellItem = mCells.get(c); - TextView txtDay = (TextView) cellItem.findViewById(R.id.view_day_day_label); - TextView txtMonth = (TextView) cellItem.findViewById(R.id.view_day_month_label); - View circleView = cellItem.findViewById(R.id.view_day_circle_selected); - View eventIndicator1 = cellItem.findViewById(R.id.view_day_event_indicator1); - View eventIndicator2 = cellItem.findViewById(R.id.view_day_event_indicator2); - View eventIndicator3 = cellItem.findViewById(R.id.view_day_event_indicator3); - cellItem.setOnClickListener(v->BusProvider.getInstance().send(new Events.DayClickedEvent(dayItem))); - - eventIndicator1.setVisibility(View.INVISIBLE); - eventIndicator2.setVisibility(View.INVISIBLE); - eventIndicator3.setVisibility(View.INVISIBLE); - - Calendar dayItemCalendar = Calendar.getInstance(); - dayItemCalendar.setTime(dayItem.getDate()); - int eventCount = 0; - for (CalendarEvent event: mEventList) { - if (event.getStartTime().get(Calendar.YEAR) == dayItemCalendar.get(Calendar.YEAR) - && event.getStartTime().get(Calendar.MONTH) == dayItemCalendar.get(Calendar.MONTH) - && event.getStartTime().get(Calendar.DAY_OF_MONTH) == dayItemCalendar.get(Calendar.DAY_OF_MONTH)) { - eventCount++; - if (eventCount == 1) { - eventIndicator1.setVisibility(View.VISIBLE); - eventIndicator1.getBackground().setColorFilter(new PorterDuffColorFilter(event.getColor(),PorterDuff.Mode.MULTIPLY)); - } - if (eventCount == 2) { - eventIndicator2.setVisibility(View.VISIBLE); - eventIndicator2.getBackground().setColorFilter(new PorterDuffColorFilter(event.getColor(),PorterDuff.Mode.MULTIPLY)); - } - if (eventCount == 3) { - eventIndicator3.setVisibility(View.VISIBLE); - eventIndicator3.getBackground().setColorFilter(new PorterDuffColorFilter(event.getColor(),PorterDuff.Mode.MULTIPLY)); - } - } - } - - //Log.d("CalendarView", "Event count for day "+dayItem.getValue()+" is "+eventCount); - - txtMonth.setVisibility(View.GONE); - txtDay.setTextColor(mDayTextColor); - txtMonth.setTextColor(mDayTextColor); - circleView.setVisibility(View.GONE); - - txtDay.setTypeface(null, Typeface.NORMAL); - txtMonth.setTypeface(null, Typeface.NORMAL); - - // Display the day - txtDay.setText(Integer.toString(dayItem.getValue())); - - // Highlight first day of the month - if (dayItem.isFirstDayOfTheMonth() && !dayItem.isSelected()) { - txtMonth.setVisibility(View.VISIBLE); - txtMonth.setText(dayItem.getMonth()); - txtDay.setTypeface(null, Typeface.BOLD); - txtMonth.setTypeface(null, Typeface.BOLD); - } - - // Check if this day is in the past - if (today.getTime().after(dayItem.getDate()) && !DateHelper.sameDate(today, dayItem.getDate())) { - txtDay.setTextColor(mPastDayTextColor); - txtMonth.setTextColor(mPastDayTextColor); - } - - // Highlight the cell if this day is today - if (dayItem.isToday() && !dayItem.isSelected()) { - txtDay.setTextColor(mCurrentDayColor); - } - - if (dayItem.getShowBadge()) { - circleView.setVisibility(View.VISIBLE); - GradientDrawable drawable = (GradientDrawable) circleView.getBackground(); - drawable.setStroke((int) (2 * Resources.getSystem().getDisplayMetrics().density), 0xffff0000); - } - - // Show a circle if the day is selected - if (dayItem.isSelected()) { - txtDay.setTextColor(mDayTextColor); - circleView.setVisibility(View.VISIBLE); - GradientDrawable drawable = (GradientDrawable) circleView.getBackground(); - drawable.setStroke((int) (1 * Resources.getSystem().getDisplayMetrics().density), mDayTextColor); - } - - // Check if the month label has to be displayed - if (dayItem.getValue() == 15) { - mTxtMonth.setVisibility(View.VISIBLE); - SimpleDateFormat monthDateFormat = new SimpleDateFormat(mContext.getResources().getString(R.string.month_name_format), CalendarManager.getInstance().getLocale()); - String month = monthDateFormat.format(weekItem.getDate()).toUpperCase(); - if (today.get(Calendar.YEAR) != weekItem.getYear()) { - month = month + String.format(" %d", weekItem.getYear()); - } - mTxtMonth.setText(month); - } - } - } - - private void setUpChildren(LinearLayout daysContainer) { - mCells = new ArrayList<>(); - for (int i = 0; i < daysContainer.getChildCount(); i++) { - mCells.add((LinearLayout) daysContainer.getChildAt(i)); - } - } - - private void setUpMonthOverlay() { - mTxtMonth.setVisibility(View.GONE); - - if (isDragging()) { - AnimatorSet animatorSetFadeIn = new AnimatorSet(); - animatorSetFadeIn.setDuration(FADE_DURATION); - ObjectAnimator animatorTxtAlphaIn = ObjectAnimator.ofFloat(mTxtMonth, "alpha", mTxtMonth.getAlpha(), 1f); - ObjectAnimator animatorBackgroundAlphaIn = ObjectAnimator.ofFloat(mMonthBackground, "alpha", mMonthBackground.getAlpha(), 1f); - animatorSetFadeIn.playTogether( - animatorTxtAlphaIn - //animatorBackgroundAlphaIn - ); - animatorSetFadeIn.addListener(new Animator.AnimatorListener() { - @Override - public void onAnimationStart(Animator animation) { - - } - - @Override - public void onAnimationEnd(Animator animation) { - setAlphaSet(true); - } - - @Override - public void onAnimationCancel(Animator animation) { - - } - - @Override - public void onAnimationRepeat(Animator animation) { - - } - }); - animatorSetFadeIn.start(); - } else { - AnimatorSet animatorSetFadeOut = new AnimatorSet(); - animatorSetFadeOut.setDuration(FADE_DURATION); - ObjectAnimator animatorTxtAlphaOut = ObjectAnimator.ofFloat(mTxtMonth, "alpha", mTxtMonth.getAlpha(), 0f); - ObjectAnimator animatorBackgroundAlphaOut = ObjectAnimator.ofFloat(mMonthBackground, "alpha", mMonthBackground.getAlpha(), 0f); - animatorSetFadeOut.playTogether( - animatorTxtAlphaOut - //animatorBackgroundAlphaOut - ); - animatorSetFadeOut.addListener(new Animator.AnimatorListener() { - @Override - public void onAnimationStart(Animator animation) { - - } - - @Override - public void onAnimationEnd(Animator animation) { - setAlphaSet(false); - } - - @Override - public void onAnimationCancel(Animator animation) { - - } - - @Override - public void onAnimationRepeat(Animator animation) { - - } - }); - animatorSetFadeOut.start(); - } - - if (isAlphaSet()) { - //mMonthBackground.setAlpha(1f); - mTxtMonth.setAlpha(1f); - } else { - //mMonthBackground.setAlpha(0f); - mTxtMonth.setAlpha(0f); - } - } - } - - // endregion -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/BaseCalendarEvent.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/BaseCalendarEvent.java deleted file mode 100644 index 642eea2c..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/BaseCalendarEvent.java +++ /dev/null @@ -1,345 +0,0 @@ -package com.github.tibolte.agendacalendarview.models; - -import java.util.Calendar; - -/** - * Event model class containing the information to be displayed on the agenda view. - */ -public class BaseCalendarEvent implements CalendarEvent { - - /** - * Id of the event. - */ - private long mId; - /** - * Color to be displayed in the agenda view. - */ - private int mColor; - /** - * Text color displayed on the background color - */ - private int mTextColor; - /** - * Title of the event. - */ - private String mTitle; - /** - * Description of the event. - */ - private String mDescription; - /** - * Where the event takes place. - */ - private String mLocation; - /** - * Calendar instance helping sorting the events per section in the agenda view. - */ - private Calendar mInstanceDay; - /** - * Start time of the event. - */ - private Calendar mStartTime; - /** - * End time of the event. - */ - private Calendar mEndTime; - /** - * Indicates if the event lasts all day. - */ - private boolean mAllDay; - /** - * Tells if this BaseCalendarEvent instance is used as a placeholder in the agenda view, if there's - * no event for that day. - */ - private boolean mPlaceHolder; - /** - * Tells if this BaseCalendarEvent instance is used as a forecast information holder in the agenda - * view. - */ - private boolean mWeather; - /** - * Duration of the event. - */ - private String mDuration; - /** - * References to a DayItem instance for that event, used to link interaction between the - * calendar view and the agenda view. - */ - private IDayItem mDayReference; - /** - * References to a WeekItem instance for that event, used to link interaction between the - * calendar view and the agenda view. - */ - private IWeekItem mWeekReference; - /** - * Weather icon string returned by the Dark Sky API. - */ - private String mWeatherIcon; - /** - * Temperature value returned by the Dark Sky API. - */ - private double mTemperature; - - private boolean mShowBadge; - - // region Constructor - - /** - * Initializes the event - * - * @param id The id of the event. - * @param color The color of the event. - * @param textColor The color of the event description text. - * @param title The title of the event. - * @param description The description of the event. - * @param location The location of the event. - * @param dateStart The start date of the event. - * @param dateEnd The end date of the event. - * @param allDay Int that can be equal to 0 or 1. - * @param duration The duration of the event in RFC2445 format. - */ - public BaseCalendarEvent(long id, int color, int textColor, String title, String description, String location, long dateStart, long dateEnd, int allDay, String duration) { - this.mId = id; - this.mColor = color; - this.mTextColor = textColor; - this.mAllDay = (allDay == 1); - this.mDuration = duration; - this.mTitle = title; - this.mDescription = description; - this.mLocation = location; - - this.mStartTime = Calendar.getInstance(); - this.mStartTime.setTimeInMillis(dateStart); - this.mEndTime = Calendar.getInstance(); - this.mEndTime.setTimeInMillis(dateEnd); - } - - public BaseCalendarEvent() { - - } - - /** - * Initializes the event - * @param title The title of the event. - * @param description The description of the event. - * @param location The location of the event. - * @param color The color of the event (for display in the app). - * @param textColor The color of the event description text. - * @param startTime The start time of the event. - * @param endTime The end time of the event. - * @param allDay Indicates if the event lasts the whole day. - */ - public BaseCalendarEvent(String title, String description, String location, int color, int textColor, Calendar startTime, Calendar endTime, boolean allDay) { - this.mTitle = title; - this.mDescription = description; - this.mLocation = location; - this.mColor = color; - this.mTextColor = textColor; - this.mStartTime = startTime; - this.mEndTime = endTime; - this.mAllDay = allDay; - } - - public BaseCalendarEvent(String title, String description, String location, int color, int textColor, Calendar startTime, Calendar endTime, boolean allDay, long id, boolean showBadge) { - this.mTitle = title; - this.mDescription = description; - this.mLocation = location; - this.mColor = color; - this.mTextColor = textColor; - this.mStartTime = startTime; - this.mEndTime = endTime; - this.mAllDay = allDay; - this.mId = id; - this.mShowBadge = showBadge; - } - - public BaseCalendarEvent(BaseCalendarEvent calendarEvent) { - this.mId = calendarEvent.getId(); - this.mColor = calendarEvent.getColor(); - this.mTextColor = calendarEvent.getTextColor(); - this.mAllDay = calendarEvent.isAllDay(); - this.mDuration = calendarEvent.getDuration(); - this.mTitle = calendarEvent.getTitle(); - this.mDescription = calendarEvent.getDescription(); - this.mLocation = calendarEvent.getLocation(); - this.mStartTime = calendarEvent.getStartTime(); - this.mEndTime = calendarEvent.getEndTime(); - this.mShowBadge = calendarEvent.getShowBadge(); - } - - // endregion - - // region Getters/Setters - - public int getColor() { - return mColor; - } - - public void setColor(int mColor) { - this.mColor = mColor; - } - - public int getTextColor() { - return mTextColor; - } - - public void setTextColor(int mTextColor) { - this.mTextColor = mTextColor; - } - - public String getDescription() { - return mDescription; - } - - public boolean isAllDay() { - return mAllDay; - } - - public void setAllDay(boolean allDay) { - this.mAllDay = allDay; - } - - public void setDescription(String mDescription) { - this.mDescription = mDescription; - } - - public Calendar getInstanceDay() { - return mInstanceDay; - } - - public void setInstanceDay(Calendar mInstanceDay) { - this.mInstanceDay = mInstanceDay; - this.mInstanceDay.set(Calendar.HOUR, 0); - this.mInstanceDay.set(Calendar.MINUTE, 0); - this.mInstanceDay.set(Calendar.SECOND, 0); - this.mInstanceDay.set(Calendar.MILLISECOND, 0); - this.mInstanceDay.set(Calendar.AM_PM, 0); - } - - public Calendar getEndTime() { - return mEndTime; - } - - public void setEndTime(Calendar mEndTime) { - this.mEndTime = mEndTime; - } - public void setPlaceholder(boolean placeholder) { - mPlaceHolder = placeholder; - } - public boolean isPlaceholder() { - return mPlaceHolder; - } - - public long getId() { - return mId; - } - - public void setId(long mId) { - this.mId = mId; - } - - public boolean getShowBadge() { - return mShowBadge; - } - - public void setShowBadge(boolean mShowBadge) { - this.mShowBadge = mShowBadge; - } - - public String getLocation() { - return mLocation; - } - - public void setLocation(String mLocation) { - this.mLocation = mLocation; - } - - public Calendar getStartTime() { - return mStartTime; - } - - public void setStartTime(Calendar mStartTime) { - this.mStartTime = mStartTime; - } - - public String getTitle() { - return mTitle; - } - - public void setTitle(String mTitle) { - this.mTitle = mTitle; - } - - public String getDuration() { - return mDuration; - } - - public void setDuration(String duration) { - this.mDuration = duration; - } - - public boolean isPlaceHolder() { - return mPlaceHolder; - } - - public void setPlaceHolder(boolean mPlaceHolder) { - this.mPlaceHolder = mPlaceHolder; - } - - public boolean isWeather() { - return mWeather; - } - - public void setWeather(boolean mWeather) { - this.mWeather = mWeather; - } - - public IDayItem getDayReference() { - return mDayReference; - } - - public void setDayReference(IDayItem mDayReference) { - this.mDayReference = mDayReference; - } - - public IWeekItem getWeekReference() { - return mWeekReference; - } - - public void setWeekReference(IWeekItem mWeekReference) { - this.mWeekReference = mWeekReference; - } - - public String getWeatherIcon() { - return mWeatherIcon; - } - - public void setWeatherIcon(String mWeatherIcon) { - this.mWeatherIcon = mWeatherIcon; - } - - public double getTemperature() { - return mTemperature; - } - - public void setTemperature(double mTemperature) { - this.mTemperature = mTemperature; - } - - @Override - public CalendarEvent copy() { - return new BaseCalendarEvent(this); - } - - // endregion - - @Override - public String toString() { - return "BaseCalendarEvent{" - + "title='" - + mTitle - + ", instanceDay= " - + mInstanceDay.getTime() - + "}"; - } -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/CalendarEvent.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/CalendarEvent.java deleted file mode 100644 index 05df9a0f..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/CalendarEvent.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.github.tibolte.agendacalendarview.models; - -import java.util.Calendar; - -public interface CalendarEvent { - - - void setPlaceholder(boolean placeholder); - - boolean isPlaceholder(); - - public String getLocation(); - - public void setLocation(String mLocation); - - long getId(); - - void setId(long mId); - - boolean getShowBadge(); - - void setShowBadge(boolean mShowBadge); - - int getTextColor(); - - void setTextColor(int mTextColor); - - String getDescription(); - - void setDescription(String mDescription); - - boolean isAllDay(); - - void setAllDay(boolean allDay); - - Calendar getStartTime(); - - void setStartTime(Calendar mStartTime); - - Calendar getEndTime(); - - void setEndTime(Calendar mEndTime); - - String getTitle(); - - void setTitle(String mTitle); - - Calendar getInstanceDay(); - - void setInstanceDay(Calendar mInstanceDay); - - IDayItem getDayReference(); - - void setDayReference(IDayItem mDayReference); - - IWeekItem getWeekReference(); - - void setWeekReference(IWeekItem mWeekReference); - - CalendarEvent copy(); - - int getColor(); -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/DayItem.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/DayItem.java deleted file mode 100644 index 39be4985..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/DayItem.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.github.tibolte.agendacalendarview.models; - -import com.github.tibolte.agendacalendarview.CalendarManager; -import com.github.tibolte.agendacalendarview.utils.DateHelper; - -import java.util.Calendar; -import java.util.Date; - -/** - * Day model class. - */ -public class DayItem implements IDayItem { - private Date mDate; - private int mValue; - private int mDayOfTheWeek; - private boolean mToday; - private boolean mFirstDayOfTheMonth; - private boolean mSelected; - private String mMonth; - private boolean mShowBadge; - - // region Constructor - - public DayItem(Date date, int value, boolean today, String month) { - this.mDate = date; - this.mValue = value; - this.mToday = today; - this.mMonth = month; - } - // only for cleanDay - public DayItem() { - - } - public DayItem(DayItem original) { - - this.mDate = original.getDate(); - this.mValue = original.getValue(); - this.mToday = original.isToday(); - this.mDayOfTheWeek = original.getDayOftheWeek(); - this.mFirstDayOfTheMonth = original.isFirstDayOfTheMonth(); - this.mSelected = original.isSelected(); - this.mMonth = original.getMonth(); - this.mShowBadge = original.mShowBadge; - } - // endregion - - // region Getters/Setters - - public Date getDate() { - return mDate; - } - - public void setDate(Date date) { - this.mDate = date; - } - - public int getValue() { - return mValue; - } - - public void setValue(int value) { - this.mValue = value; - } - - public boolean isToday() { - return mToday; - } - - public void setToday(boolean today) { - this.mToday = today; - } - - public boolean isSelected() { - return mSelected; - } - - public void setSelected(boolean selected) { - this.mSelected = selected; - } - - public boolean isFirstDayOfTheMonth() { - return mFirstDayOfTheMonth; - } - - public void setFirstDayOfTheMonth(boolean firstDayOfTheMonth) { - this.mFirstDayOfTheMonth = firstDayOfTheMonth; - } - - public String getMonth() { - return mMonth; - } - - public void setMonth(String month) { - this.mMonth = month; - } - - public int getDayOftheWeek() { - return mDayOfTheWeek; - } - - public void setDayOftheWeek(int mDayOftheWeek) { - this.mDayOfTheWeek = mDayOftheWeek; - } - - public void setShowBadge(boolean showBadge) { - this.mShowBadge = showBadge; - } - - public boolean getShowBadge() { - return this.mShowBadge; - } - - // region Public methods - - public void buildDayItemFromCal(Calendar calendar) { - Date date = calendar.getTime(); - this.mDate = date; - - this.mValue = calendar.get(Calendar.DAY_OF_MONTH); - this.mToday = DateHelper.sameDate(calendar, CalendarManager.getInstance().getToday()); - this.mMonth = CalendarManager.getInstance().getMonthHalfNameFormat().format(date); - if (this.mValue == 1) { - this.mFirstDayOfTheMonth = true; - } - } - - // endregion - - @Override - public String toString() { - return "DayItem{" - + "Date='" - + mDate.toString() - + ", value=" - + mValue - + '}'; - } - - @Override - public IDayItem copy() { - return new DayItem(this); - } - - // endregion -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/IDayItem.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/IDayItem.java deleted file mode 100644 index acfe3c76..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/IDayItem.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.github.tibolte.agendacalendarview.models; - -import java.util.Calendar; -import java.util.Date; - -public interface IDayItem { - - // region Getters/Setters - - Date getDate(); - - void setDate(Date date); - - int getValue(); - - void setValue(int value); - - boolean isToday(); - - void setToday(boolean today); - - boolean isSelected(); - - void setSelected(boolean selected); - - boolean isFirstDayOfTheMonth(); - - void setFirstDayOfTheMonth(boolean firstDayOfTheMonth); - - String getMonth(); - - void setMonth(String month); - - int getDayOftheWeek(); - - void setDayOftheWeek(int mDayOftheWeek); - - // endregion - - void buildDayItemFromCal(Calendar calendar); - - String toString(); - - IDayItem copy(); - - void setShowBadge(boolean showBadge); - - boolean getShowBadge(); -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/IWeekItem.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/IWeekItem.java deleted file mode 100644 index bb08b89a..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/IWeekItem.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.github.tibolte.agendacalendarview.models; - -import java.util.Date; -import java.util.List; - -public interface IWeekItem { - - - int getWeekInYear(); - - void setWeekInYear(int weekInYear); - - int getYear(); - - void setYear(int year); - - int getMonth(); - - void setMonth(int month); - - Date getDate(); - - void setDate(Date date); - - String getLabel(); - - void setLabel(String label); - - List getDayItems(); - - void setDayItems(List dayItems); - - IWeekItem copy(); -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/WeekItem.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/WeekItem.java deleted file mode 100644 index 40b94902..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/models/WeekItem.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.github.tibolte.agendacalendarview.models; - -import java.util.Date; -import java.util.List; - -/** - * Week model class. - */ -public class WeekItem implements IWeekItem { - private int mWeekInYear; - private int mYear; - private int mMonth; - private Date mDate; - private String mLabel; - private List mDayItems; - - // region Constructor - - public WeekItem(int weekInYear, int year, Date date, String label, int month) { - this.mWeekInYear = weekInYear; - this.mYear = year; - this.mDate = date; - this.mLabel = label; - this.mMonth = month; - } - public WeekItem(WeekItem original) { - this.mWeekInYear = original.getWeekInYear(); - this.mYear = original.getYear(); - this.mMonth = original.getMonth(); - this.mDate = original.getDate(); - this.mLabel = original.getLabel(); - this.mDayItems = original.getDayItems(); - } - - public WeekItem(){ - - } - - // endregion - - // region Getters/Setters - - public int getWeekInYear() { - return mWeekInYear; - } - - public void setWeekInYear(int weekInYear) { - this.mWeekInYear = weekInYear; - } - - public int getYear() { - return mYear; - } - - public void setYear(int year) { - this.mYear = year; - } - - public int getMonth() { - return mMonth; - } - - public void setMonth(int month) { - this.mMonth = month; - } - - public Date getDate() { - return mDate; - } - - public void setDate(Date date) { - this.mDate = date; - } - - public String getLabel() { - return mLabel; - } - - public void setLabel(String label) { - this.mLabel = label; - } - - public List getDayItems() { - return mDayItems; - } - - public void setDayItems(List dayItems) { - this.mDayItems = dayItems; - } - - @Override - public IWeekItem copy() { - return new WeekItem(this); - } - - // endregion - - @Override - public String toString() { - return "WeekItem{" - + "label='" - + mLabel - + '\'' - + ", weekInYear=" - + mWeekInYear - + ", year=" - + mYear - + '}'; - } -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/render/DefaultEventRenderer.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/render/DefaultEventRenderer.java deleted file mode 100644 index 729ad706..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/render/DefaultEventRenderer.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.github.tibolte.agendacalendarview.render; - -import android.content.Context; -import android.content.res.Resources; -import androidx.annotation.NonNull; -import androidx.cardview.widget.CardView; -import androidx.core.content.ContextCompat; - -import android.graphics.Color; -import android.util.TypedValue; -import android.view.View; -import android.widget.LinearLayout; -import android.widget.TextView; - -import com.github.tibolte.agendacalendarview.R; -import com.github.tibolte.agendacalendarview.models.BaseCalendarEvent; -import com.google.android.material.internal.ViewUtils; - -/** - * Class helping to inflate our default layout in the AgendaAdapter - */ -public class DefaultEventRenderer extends EventRenderer { - - public static int themeAttributeToColor(int themeAttributeId, - Context context, - int fallbackColorId) { - TypedValue outValue = new TypedValue(); - Resources.Theme theme = context.getTheme(); - boolean wasResolved = - theme.resolveAttribute( - themeAttributeId, outValue, true); - if (wasResolved) { - return ContextCompat.getColor( - context, outValue.resourceId); - } else { - // fallback colour handling - return fallbackColorId; - } - } - - // region class - EventRenderer - - @Override - public void render(@NonNull View view, @NonNull BaseCalendarEvent event) { - CardView card = view.findViewById(R.id.view_agenda_event_card_view); - TextView txtTitle = view.findViewById(R.id.view_agenda_event_title); - TextView txtLocation = view.findViewById(R.id.view_agenda_event_location); - LinearLayout descriptionContainer = view.findViewById(R.id.view_agenda_event_description_container); - LinearLayout locationContainer = view.findViewById(R.id.view_agenda_event_location_container); - - descriptionContainer.setVisibility(View.VISIBLE); - - txtTitle.setText(event.getTitle()); - txtLocation.setText(event.getLocation()); - if (event.getLocation().length() > 0) { - locationContainer.setVisibility(View.VISIBLE); - txtLocation.setText(event.getLocation()); - } else { - locationContainer.setVisibility(View.GONE); - } - - if (!event.isPlaceholder()/*!event.getTitle().equals(view.getResources().getString(R.string.agenda_event_no_events))*/) { - txtTitle.setTextColor(event.getTextColor()); - card.setCardBackgroundColor(event.getColor()); - txtLocation.setTextColor(event.getTextColor()); - } - else { - card.setCardBackgroundColor(Color.TRANSPARENT); - card.setCardElevation(0); - card.setBackgroundColor(Color.TRANSPARENT); - card.setRadius(0); - card.setBackgroundDrawable(null); - } - } - - @Override - public int getEventLayout() { - return R.layout.view_agenda_event; - } - - // endregion -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/render/EventRenderer.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/render/EventRenderer.java deleted file mode 100644 index e62f23b5..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/render/EventRenderer.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.github.tibolte.agendacalendarview.render; - -import androidx.annotation.LayoutRes; -import android.view.View; - -import com.github.tibolte.agendacalendarview.models.CalendarEvent; - -import java.lang.reflect.ParameterizedType; - -/** - * Base class for helping layout rendering - */ -public abstract class EventRenderer { - public abstract void render(final View view, final T event); - - @LayoutRes - public abstract int getEventLayout(); - - public Class getRenderType() { - ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass(); - return (Class) type.getActualTypeArguments()[0]; - } -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/utils/BusProvider.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/utils/BusProvider.java deleted file mode 100644 index 99bdbf3d..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/utils/BusProvider.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.github.tibolte.agendacalendarview.utils; - -import rx.Observable; -import rx.subjects.PublishSubject; -import rx.subjects.SerializedSubject; -import rx.subjects.Subject; - -public class BusProvider { - - public static BusProvider mInstance; - - private final Subject mBus = new SerializedSubject<>(PublishSubject.create()); - - // region Constructors - - public static BusProvider getInstance() { - if (mInstance == null) { - mInstance = new BusProvider(); - } - return mInstance; - } - - // endregion - - // region Public methods - - public void send(Object object) { - mBus.onNext(object); - } - - public Observable toObserverable() { - return mBus; - } - - // endregion -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/utils/DateHelper.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/utils/DateHelper.java deleted file mode 100644 index f9439d04..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/utils/DateHelper.java +++ /dev/null @@ -1,135 +0,0 @@ -package com.github.tibolte.agendacalendarview.utils; - -import com.github.tibolte.agendacalendarview.CalendarManager; -import com.github.tibolte.agendacalendarview.R; -import com.github.tibolte.agendacalendarview.models.IWeekItem; - -import android.content.Context; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; -import java.util.concurrent.TimeUnit; - -/** - * Class containing helper functions for dates - */ -public class DateHelper { - - // region Public methods - - /** - * Check if two Calendar instances have the same time (by month, year and day of month) - * - * @param cal The first Calendar instance. - * @param selectedDate The second Calendar instance. - * @return True if both instances have the same time. - */ - public static boolean sameDate(Calendar cal, Calendar selectedDate) { - return cal.get(Calendar.MONTH) == selectedDate.get(Calendar.MONTH) - && cal.get(Calendar.YEAR) == selectedDate.get(Calendar.YEAR) - && cal.get(Calendar.DAY_OF_MONTH) == selectedDate.get(Calendar.DAY_OF_MONTH); - } - - /** - * Check if a Date instance and a Calendar instance have the same time (by month, year and day - * of month) - * - * @param cal The Calendar instance. - * @param selectedDate The Date instance. - * @return True if both have the same time. - */ - public static boolean sameDate(Calendar cal, Date selectedDate) { - Calendar selectedCal = Calendar.getInstance(); - selectedCal.setTime(selectedDate); - return cal.get(Calendar.MONTH) == selectedCal.get(Calendar.MONTH) - && cal.get(Calendar.YEAR) == selectedCal.get(Calendar.YEAR) - && cal.get(Calendar.DAY_OF_MONTH) == selectedCal.get(Calendar.DAY_OF_MONTH); - } - - /** - * Check if a Date instance is between two Calendar instances' dates (inclusively) in time. - * - * @param selectedDate The date to verify. - * @param startCal The start time. - * @param endCal The end time. - * @return True if the verified date is between the two specified dates. - */ - public static boolean isBetweenInclusive(Date selectedDate, Calendar startCal, Calendar endCal) { - Calendar selectedCal = Calendar.getInstance(); - selectedCal.setTime(selectedDate); - // Check if we deal with the same day regarding startCal and endCal - return sameDate(selectedCal, startCal) || selectedCal.after(startCal) && selectedCal.before(endCal); - } - - /** - * Check if Calendar instance's date is in the same week, as the WeekItem instance. - * - * @param cal The Calendar instance to verify. - * @param week The WeekItem instance to compare to. - * @return True if both instances are in the same week. - */ - public static boolean sameWeek(Calendar cal, IWeekItem week) { - return (cal.get(Calendar.WEEK_OF_YEAR) == week.getWeekInYear() && cal.get(Calendar.YEAR) == week.getYear()); - } - - /** - * Convert a millisecond duration to a string format - * - * @param millis A duration to convert to a string form - * @return A string of the form "Xd" or either "XhXm". - */ - public static String getDuration(Context context, long millis) { - if (millis < 0) { - throw new IllegalArgumentException("Duration must be greater than zero!"); - } - - long days = TimeUnit.MILLISECONDS.toDays(millis); - millis -= TimeUnit.DAYS.toMillis(days); - long hours = TimeUnit.MILLISECONDS.toHours(millis); - millis -= TimeUnit.HOURS.toMillis(hours); - long minutes = TimeUnit.MILLISECONDS.toMinutes(millis); - - StringBuilder sb = new StringBuilder(64); - if (days > 0) { - sb.append(days); - sb.append(context.getResources().getString(R.string.agenda_event_day_duration)); - return (sb.toString()); - } else { - if (hours > 0) { - sb.append(hours); - sb.append("h"); - } - if (minutes > 0) { - sb.append(minutes); - sb.append("m"); - } - } - - return (sb.toString()); - } - - /** - * Used for displaying the date in any section of the agenda view. - * - * @param calendar The date of the section. - * @param locale The locale used by the Sunrise calendar. - * @return The formatted date without the year included. - */ - public static String getYearLessLocalizedDate(Calendar calendar, Locale locale) { - SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance(DateFormat.FULL, CalendarManager.getInstance().getLocale()); - String pattern = sdf.toPattern(); - - String yearLessPattern = pattern.replaceAll("\\W?[Yy]+\\W?", ""); - SimpleDateFormat yearLessSDF = new SimpleDateFormat(yearLessPattern, locale); - String yearLessDate = yearLessSDF.format(calendar.getTime()).toUpperCase(); - if (yearLessDate.endsWith(",")) { - yearLessDate = yearLessDate.substring(0, yearLessDate.length() - 1); - } - return yearLessDate; - } - - // endregion -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/utils/Events.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/utils/Events.java deleted file mode 100644 index 98d13f20..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/utils/Events.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.github.tibolte.agendacalendarview.utils; - -import com.github.tibolte.agendacalendarview.models.IDayItem; - -import java.util.Calendar; - -/** - * Events emitted by the bus provider. - */ -public class Events { - - public static class DayClickedEvent { - - public Calendar mCalendar; - public IDayItem mDayItem; - - public DayClickedEvent(IDayItem dayItem) { - this.mCalendar = Calendar.getInstance(); - this.mCalendar.setTime(dayItem.getDate()); - this.mDayItem = dayItem; - } - - public Calendar getCalendar() { - return mCalendar; - } - - public IDayItem getDay() { - return mDayItem; - } - } - - public static class CalendarScrolledEvent { - } - - public static class AgendaListViewTouchedEvent { - } - - public static class EventsFetched { - } - - public static class ForecastFetched { - } -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/utils/ListViewScrollTracker.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/utils/ListViewScrollTracker.java deleted file mode 100644 index 47e16de3..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/utils/ListViewScrollTracker.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.github.tibolte.agendacalendarview.utils; - -import com.github.tibolte.agendacalendarview.agenda.AgendaListView; - -import android.util.SparseArray; -import android.view.View; - -/** - * Helper class calculating the scrolling distance in the AgendaListView. - */ -public class ListViewScrollTracker { - private AgendaListView mListView; - private SparseArray mPositions; - private SparseArray mListViewItemHeights = new SparseArray<>(); - private int mFirstVisiblePosition; - private int mReferencePosition = -1; // Position of the current date in the Agenda listView - - // region Constructor and Accessor(s) - - public ListViewScrollTracker(AgendaListView listView) { - mListView = listView; - } - - public int getReferencePosition() { - return mReferencePosition; - } - - // endregion - - // region Public methods - - /** - * Call from an AbsListView.OnScrollListener to calculate the incremental offset (change in - * scroll offset - * since the last calculation). - * - * @param firstVisiblePosition First visible item position in the list. - * @param visibleItemCount Number of visible items in the list. - * @return The incremental offset, or 0 if it wasn't possible to calculate the offset. - */ - public int calculateIncrementalOffset(int firstVisiblePosition, int visibleItemCount) { - // Remember previous positions, if any - SparseArray previousPositions = mPositions; - - // Store new positions - mPositions = new SparseArray<>(); - for (int i = 0; i < visibleItemCount; i++) { - mPositions.put(firstVisiblePosition + i, mListView.getListChildAt(i).getTop()); - } - - if (previousPositions != null) { - // Find position which exists in both mPositions and previousPositions, then return the difference - // of the new and old Y values. - for (int i = 0; i < previousPositions.size(); i++) { - int previousPosition = previousPositions.keyAt(i); - int previousTop = previousPositions.get(previousPosition); - Integer newTop = mPositions.get(previousPosition); - if (newTop != null) { - return newTop - previousTop; - } - } - } - - return 0; // No view's position was in both previousPositions and mPositions - } - - /** - * Call from an AbsListView.OnScrollListener to calculate the scrollY (Here - * we definite as the distance in pixels compared to the position representing the current - * date). - * - * @param firstVisiblePosition First visible item position in the list. - * @param visibleItemCount Number of visible items in the list. - * @return Distance in pixels compared to current day position (negative if firstVisiblePosition less than mReferencePosition) - */ - public int calculateScrollY(int firstVisiblePosition, int visibleItemCount) { - mFirstVisiblePosition = firstVisiblePosition; - if (mReferencePosition < 0) { - mReferencePosition = mFirstVisiblePosition; - } - - if (visibleItemCount > 0) { - View c = mListView.getListChildAt(0); // this is the first visible row - int scrollY = -c.getTop(); - mListViewItemHeights.put(firstVisiblePosition, c.getMeasuredHeight()); - - if (mFirstVisiblePosition >= mReferencePosition) { - for (int i = mReferencePosition; i < firstVisiblePosition; ++i) { - if (mListViewItemHeights.get(i) == null) { - mListViewItemHeights.put(i, c.getMeasuredHeight()); - } - scrollY += mListViewItemHeights.get(i); // add all heights of the views that are gone - } - return scrollY; - } else { - for (int i = mReferencePosition - 1; i >= firstVisiblePosition; --i) { - if (mListViewItemHeights.get(i) == null) { - mListViewItemHeights.put(i, c.getMeasuredHeight()); - } - scrollY -= mListViewItemHeights.get(i); - } - return scrollY; - } - - } - return 0; - } - - public void clear() { - mPositions = null; - } - - // endregion -} diff --git a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/widgets/FloatingActionButton.java b/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/widgets/FloatingActionButton.java deleted file mode 100644 index bd008910..00000000 --- a/agendacalendarview/src/main/java/com/github/tibolte/agendacalendarview/widgets/FloatingActionButton.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.github.tibolte.agendacalendarview.widgets; - -import android.content.Context; -import android.util.AttributeSet; -import android.view.ViewGroup; -import android.view.ViewTreeObserver; -import android.view.animation.AccelerateDecelerateInterpolator; -import android.view.animation.Interpolator; - -/** - * Floating action button helping to scroll back to the current date. - */ -public class FloatingActionButton extends com.google.android.material.floatingactionbutton.FloatingActionButton { - private static final int TRANSLATE_DURATION_MILLIS = 200; - - private boolean mVisible = true; - - private final Interpolator mInterpolator = new AccelerateDecelerateInterpolator(); - - // region Constructors - - public FloatingActionButton(Context context) { - super(context); - } - - public FloatingActionButton(Context context, AttributeSet attrs) { - super(context, attrs); - } - - public FloatingActionButton(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - } - - // endregion - - // region Overrides - - @Override - public void show() { - show(true); - } - - @Override - public void hide() { - hide(true); - } - - // endregion - - // region Public methods - - public void show(boolean animate) { - toggle(true, animate, false); - } - - public void hide(boolean animate) { - toggle(false, animate, false); - } - - public boolean isVisible() { - return mVisible; - } - - // endregion - - // region Private methods - - private void toggle(final boolean visible, final boolean animate, boolean force) { - if (mVisible != visible || force) { - mVisible = visible; - int height = getHeight(); - if (height == 0 && !force) { - ViewTreeObserver vto = getViewTreeObserver(); - if (vto.isAlive()) { - vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { - @Override - public boolean onPreDraw() { - ViewTreeObserver currentVto = getViewTreeObserver(); - if (currentVto.isAlive()) { - currentVto.removeOnPreDrawListener(this); - } - toggle(visible, animate, true); - return true; - } - }); - return; - } - } - int translationY = visible ? 0 : height + getMarginBottom(); - if (animate) { - animate().setInterpolator(mInterpolator) - .setDuration(TRANSLATE_DURATION_MILLIS) - .translationY(translationY); - } else { - setTranslationY(translationY); - } - } - } - - private int getMarginBottom() { - int marginBottom = 0; - final ViewGroup.LayoutParams layoutParams = getLayoutParams(); - if (layoutParams instanceof ViewGroup.MarginLayoutParams) { - marginBottom = ((ViewGroup.MarginLayoutParams) layoutParams).bottomMargin; - } - return marginBottom; - } - - // endregion -} diff --git a/agendacalendarview/src/main/res/drawable/agenda_day_circle.xml b/agendacalendarview/src/main/res/drawable/agenda_day_circle.xml deleted file mode 100644 index e1398e00..00000000 --- a/agendacalendarview/src/main/res/drawable/agenda_day_circle.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/agendacalendarview/src/main/res/drawable/fab_arrow.xml b/agendacalendarview/src/main/res/drawable/fab_arrow.xml deleted file mode 100644 index 3b4d3a8c..00000000 --- a/agendacalendarview/src/main/res/drawable/fab_arrow.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - \ No newline at end of file diff --git a/agendacalendarview/src/main/res/drawable/selected_day_color_circle.xml b/agendacalendarview/src/main/res/drawable/selected_day_color_circle.xml deleted file mode 100644 index 3d53cf8c..00000000 --- a/agendacalendarview/src/main/res/drawable/selected_day_color_circle.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/agendacalendarview/src/main/res/drawable/shadow.xml b/agendacalendarview/src/main/res/drawable/shadow.xml deleted file mode 100644 index 7ab76207..00000000 --- a/agendacalendarview/src/main/res/drawable/shadow.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - \ No newline at end of file diff --git a/agendacalendarview/src/main/res/layout/list_item_week.xml b/agendacalendarview/src/main/res/layout/list_item_week.xml deleted file mode 100644 index 846ba637..00000000 --- a/agendacalendarview/src/main/res/layout/list_item_week.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/agendacalendarview/src/main/res/layout/view_agenda.xml b/agendacalendarview/src/main/res/layout/view_agenda.xml deleted file mode 100644 index 5f4a704e..00000000 --- a/agendacalendarview/src/main/res/layout/view_agenda.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/agendacalendarview/src/main/res/layout/view_agenda_event.xml b/agendacalendarview/src/main/res/layout/view_agenda_event.xml deleted file mode 100644 index 92329386..00000000 --- a/agendacalendarview/src/main/res/layout/view_agenda_event.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/agendacalendarview/src/main/res/layout/view_agenda_header.xml b/agendacalendarview/src/main/res/layout/view_agenda_header.xml deleted file mode 100644 index e0391dd5..00000000 --- a/agendacalendarview/src/main/res/layout/view_agenda_header.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/agendacalendarview/src/main/res/layout/view_agendacalendar.xml b/agendacalendarview/src/main/res/layout/view_agendacalendar.xml deleted file mode 100644 index e2df4255..00000000 --- a/agendacalendarview/src/main/res/layout/view_agendacalendar.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/agendacalendarview/src/main/res/layout/view_calendar.xml b/agendacalendarview/src/main/res/layout/view_calendar.xml deleted file mode 100644 index 4b3839e0..00000000 --- a/agendacalendarview/src/main/res/layout/view_calendar.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/agendacalendarview/src/main/res/layout/view_day_calendar_header.xml b/agendacalendarview/src/main/res/layout/view_day_calendar_header.xml deleted file mode 100644 index 2326af49..00000000 --- a/agendacalendarview/src/main/res/layout/view_day_calendar_header.xml +++ /dev/null @@ -1,9 +0,0 @@ - - \ No newline at end of file diff --git a/agendacalendarview/src/main/res/layout/view_day_cell.xml b/agendacalendarview/src/main/res/layout/view_day_cell.xml deleted file mode 100644 index cebb97db..00000000 --- a/agendacalendarview/src/main/res/layout/view_day_cell.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/agendacalendarview/src/main/res/values-en/strings.xml b/agendacalendarview/src/main/res/values-en/strings.xml deleted file mode 100644 index 1d9b1040..00000000 --- a/agendacalendarview/src/main/res/values-en/strings.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - Today - Tomorrow - d - All day - No events - - - LLLL - MMM - diff --git a/agendacalendarview/src/main/res/values/attrs.xml b/agendacalendarview/src/main/res/values/attrs.xml deleted file mode 100644 index 6750df84..00000000 --- a/agendacalendarview/src/main/res/values/attrs.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/agendacalendarview/src/main/res/values/colors.xml b/agendacalendarview/src/main/res/values/colors.xml deleted file mode 100644 index 7904509d..00000000 --- a/agendacalendarview/src/main/res/values/colors.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - #000000 - #9C9CA0 - #CCFFFFFF - #F3F3F3 - - - - #00000000 - - - #2196F3 - #1976D2 - #2196F3 - #BBDEFB - #4caf50 - #FFFFFF - - \ No newline at end of file diff --git a/agendacalendarview/src/main/res/values/dimens.xml b/agendacalendarview/src/main/res/values/dimens.xml deleted file mode 100644 index 7b639f8d..00000000 --- a/agendacalendarview/src/main/res/values/dimens.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - 20dp - 52dp - 14dp - 32dp - - - 60dp - - - - - 70dp - 5dp - 15dp - 5dp - \ No newline at end of file diff --git a/agendacalendarview/src/main/res/values/strings.xml b/agendacalendarview/src/main/res/values/strings.xml deleted file mode 100644 index 7c2c5f8a..00000000 --- a/agendacalendarview/src/main/res/values/strings.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - LLLL - E - - - Dziś - Jutro - d - Cały dzień - Brak wydarzeń - - MMM - diff --git a/agendacalendarview/src/main/res/values/styles.xml b/agendacalendarview/src/main/res/values/styles.xml deleted file mode 100644 index b4bf4679..00000000 --- a/agendacalendarview/src/main/res/values/styles.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle index 012144f0..ecf9159d 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,60 +1,85 @@ apply plugin: 'com.android.application' -apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-android' +apply plugin: 'kotlin-kapt' +apply plugin: 'kotlin-parcelize' apply plugin: 'com.google.gms.google-services' -apply plugin: 'io.fabric' +apply plugin: 'com.google.firebase.crashlytics' + +apply from: 'git-info.gradle' android { - signingConfigs { - } - compileSdkVersion rootProject.ext.compileSdkVersion + compileSdkVersion setup.compileSdk + defaultConfig { applicationId 'pl.szczodrzynski.edziennik' minSdkVersion setup.minSdk targetSdkVersion setup.targetSdk + versionCode release.versionCode versionName release.versionName - multiDexEnabled true - } - buildTypes { - applicationVariants.all { variant -> - variant.outputs.all { - if (variant.buildType.name == "release") { - outputFileName = "Edziennik_" + defaultConfig.versionName + ".apk" - } else if (variant.buildType.name == "debugMinify") { - outputFileName = "Edziennik_" + defaultConfig.versionName + "_debugMinify.apk" - } else { - outputFileName = "Edziennik_" + defaultConfig.versionName + "_debug.apk" - } + + buildConfigField "java.util.Map", "GIT_INFO", gitInfoMap + buildConfigField "String", "VERSION_BASE", "\"${release.versionName}\"" + manifestPlaceholders = [ + buildTimestamp: String.valueOf(System.currentTimeMillis()) + ] + + multiDexEnabled = true + + externalNativeBuild { + cmake { + cppFlags "-std=c++11" } } + + kapt { + arguments { + arg("room.schemaLocation", "$projectDir/schemas") + } + } + } + + buildTypes { debug { - minifyEnabled false + minifyEnabled = false + manifestPlaceholders = [ + buildTimestamp: 0 + ] } release { - minifyEnabled true - shrinkResources true - proguardFiles getDefaultProguardFile('proguard-android.txt') + minifyEnabled = true + shrinkResources = true + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' proguardFiles fileTree('proguard').asList().toArray() } } - dependencies { - implementation "com.google.firebase:firebase-core:${versions.firebase}" + flavorDimensions "platform" + productFlavors { + main { + versionName "${release.versionName}-${gitInfo.versionSuffix}" + } + official {} + play {} } + variantFilter { variant -> + def flavors = variant.flavors*.name + setIgnore(variant.buildType.name == "debug" && !flavors.contains("main")) + } + defaultConfig { vectorDrawables.useSupportLibrary = true } lintOptions { - checkReleaseBuilds false + checkReleaseBuilds = false } - dataBinding { - enabled = true + buildFeatures { + dataBinding = true + viewBinding = true } compileOptions { - sourceCompatibility '1.8' - targetCompatibility '1.8' - } - productFlavors { + coreLibraryDesugaringEnabled = true + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = "1.8" @@ -62,97 +87,125 @@ android { packagingOptions { exclude 'META-INF/library-core_release.kotlin_module' } -} - -/*task finalizeBundleDebug(type: Copy) { - from("debug/debug") - include "app.aab" - destinationDir file("debug/debug") - rename "app.aab", "Edziennik_debug.aab" -} - -// it finalizes :bundleRelease -task finalizeBundleRelease(type: Copy) { - from("release/release") - include "app.aab" - destinationDir file("release/release") - rename "app.aab", "Edziennik_${android.defaultConfig.versionCode}.aab" -}*/ -/* -// this adds the above two tasks -tasks.whenTaskAdded { task -> - if (task.name == "bundleDebug") { - task.finalizedBy finalizeBundleDebug - } else if (task.name == "bundleRelease") { - task.finalizedBy finalizeBundleRelease + externalNativeBuild { + cmake { + path "src/main/cpp/CMakeLists.txt" + version "3.10.2" + } } -}*/ +} + +tasks.whenTaskAdded { task -> + if (!task.name.endsWith("Release") && !task.name.endsWith("ReleaseWithR8")) + return + def renameTaskName = "rename${task.name.capitalize()}" + + def flavor = "" + if (task.name.startsWith("bundle")) + flavor = task.name.substring("bundle".length(), task.name.indexOf("Release")).uncapitalize() + if (task.name.startsWith("assemble")) + flavor = task.name.substring("assemble".length(), task.name.indexOf("Release")).uncapitalize() + if (task.name.startsWith("minify")) + flavor = task.name.substring("minify".length(), task.name.indexOf("Release")).uncapitalize() + + if (flavor != "") { + tasks.create(renameTaskName, Copy) { + from file("${projectDir}/${flavor}/release/"), + file("${buildDir}/outputs/mapping/${flavor}Release/"), + file("${buildDir}/outputs/apk/${flavor}/release/"), + file("${buildDir}/outputs/bundle/${flavor}Release/") + include "*.aab", "*.apk", "mapping.txt", "output-metadata.json" + destinationDir file("${projectDir}/release/") + rename ".+?\\.(.+)", "Edziennik_${android.defaultConfig.versionName}_${flavor}." + '$1' + } + task.finalizedBy(renameTaskName) + } +} dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') - annotationProcessor "androidx.room:room-compiler:${versions.room}" - debugImplementation "com.amitshekhar.android:debug-db:1.0.5" + // Language cores + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + coreLibraryDesugaring "com.android.tools:desugar_jdk_libs:1.1.5" - implementation "android.arch.navigation:navigation-fragment-ktx:${versions.navigationFragment}" - implementation "androidx.appcompat:appcompat:${versions.appcompat}" - implementation "androidx.cardview:cardview:${versions.cardView}" - implementation "androidx.constraintlayout:constraintlayout:${versions.constraintLayout}" - implementation "androidx.core:core-ktx:${versions.ktx}" - implementation "androidx.gridlayout:gridlayout:${versions.gridLayout}" - implementation "androidx.legacy:legacy-support-v4:${versions.legacy}" - implementation "androidx.lifecycle:lifecycle-livedata:${versions.lifecycle}" - implementation "androidx.recyclerview:recyclerview:${versions.recyclerView}" - implementation "androidx.room:room-runtime:${versions.room}" - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${versions.kotlin}" + // Android Jetpack + implementation "androidx.appcompat:appcompat:1.3.1" + implementation "androidx.cardview:cardview:1.0.0" + implementation "androidx.constraintlayout:constraintlayout:2.1.1" + implementation "androidx.core:core-ktx:1.6.0" + implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.1" + implementation "androidx.navigation:navigation-fragment-ktx:2.3.5" + implementation "androidx.recyclerview:recyclerview:1.2.1" + implementation "androidx.room:room-runtime:2.3.0" + implementation "androidx.work:work-runtime-ktx:2.6.0" + kapt "androidx.room:room-compiler:2.3.0" - implementation "com.google.android.gms:play-services-wearable:${versions.play_services}" - implementation "com.google.android.material:material:${versions.material}" - implementation "com.google.firebase:firebase-messaging:${versions.firebasemessaging}" + // Google design libs + implementation "com.google.android.material:material:1.4.0" + implementation "com.google.android.flexbox:flexbox:3.0.0" - //implementation "com.github.kuba2k2.MaterialDrawer:library:e603091449" - implementation "com.mikepenz:crossfader:1.6.0" // do not update - implementation "com.mikepenz:iconics-core:${versions.iconics}" - implementation "com.mikepenz:iconics-views:${versions.iconics}" - implementation "com.mikepenz:community-material-typeface:${versions.font_cmd}@aar" + // Play Services/Firebase + implementation "com.google.android.gms:play-services-wearable:17.1.0" + implementation "com.google.firebase:firebase-core:19.0.2" + implementation "com.google.firebase:firebase-crashlytics:18.2.3" + implementation("com.google.firebase:firebase-messaging") { version { strictly "20.1.3" } } - implementation "com.github.kuba2k2:NavLib:${versions.navlib}" + // OkHttp, Retrofit, Gson, Jsoup + implementation("com.squareup.okhttp3:okhttp") { version { strictly "3.12.13" } } + implementation "com.squareup.retrofit2:retrofit:2.9.0" + implementation "com.squareup.retrofit2:converter-gson:2.9.0" + implementation "com.squareup.retrofit2:converter-scalars:2.9.0" + implementation 'com.google.code.gson:gson:2.8.8' + implementation 'org.jsoup:jsoup:1.14.3' + implementation "pl.droidsonroids:jspoon:1.3.2" + implementation "pl.droidsonroids.retrofit2:converter-jspoon:1.3.2" - implementation "com.afollestad.material-dialogs:commons:${versions.materialdialogs}" - implementation "com.afollestad.material-dialogs:core:${versions.materialdialogs}" + // Szkolny.eu libraries/forks + implementation "eu.szkolny:android-snowfall:1ca9ea2da3" + implementation "eu.szkolny:agendacalendarview:1.0.4" + implementation "eu.szkolny:cafebar:5bf0c618de" + implementation "eu.szkolny.fslogin:lib:2.0.0" + implementation "eu.szkolny:material-about-library:1d5ebaf47c" + implementation "eu.szkolny:mhttp:af4b62e6e9" + implementation "eu.szkolny:nachos:0e5dfcaceb" + implementation "eu.szkolny.selective-dao:annotation:27f8f3f194" + implementation "eu.szkolny:ssl-provider:1.0.0" + implementation "pl.szczodrzynski:navlib:0.8.0" + implementation "pl.szczodrzynski:numberslidingpicker:2921225f76" + implementation "pl.szczodrzynski:recyclertablayout:700f980584" + implementation "pl.szczodrzynski:tachyon:551943a6b5" + kapt "eu.szkolny.selective-dao:codegen:27f8f3f194" - implementation "cat.ereza:customactivityoncrash:2.2.0" - implementation "com.applandeo:material-calendar-view:1.5.0" - implementation "com.crashlytics.sdk.android:crashlytics:2.10.1" + // Iconics & related + implementation "com.mikepenz:iconics-core:5.3.2" + implementation "com.mikepenz:iconics-views:5.3.2" + implementation "com.mikepenz:community-material-typeface:5.8.55.0-kotlin@aar" + implementation "eu.szkolny:szkolny-font:77e33acc2a" + + // Other dependencies + implementation "cat.ereza:customactivityoncrash:2.3.0" + implementation "com.android.volley:volley:1.2.1" implementation "com.daimajia.swipelayout:library:1.2.0@aar" - implementation "com.evernote:android-job:1.2.6" - implementation "com.github.antonKozyriatskyi:CircularProgressIndicator:1.2.2" - implementation "com.github.bassaer:chatmessageview:2.0.1" - implementation("com.github.ozodrukh:CircularReveal:2.0.1@aar") {transitive = true} - implementation "com.heinrichreimersoftware:material-intro:1.5.8" // do not update - implementation "com.jaredrummler:colorpicker:1.0.2" - implementation "com.squareup.okhttp3:okhttp:3.12.0" - implementation "com.theartofdev.edmodo:android-image-cropper:2.8.0" // do not update - implementation "com.wdullaer:materialdatetimepicker:4.1.2" - implementation "com.yuyh.json:jsonviewer:1.0.6" + implementation "com.github.Applandeo:Material-Calendar-View:15de569cbc" // https://github.com/Applandeo/Material-Calendar-View + implementation "com.github.CanHub:Android-Image-Cropper:2.2.2" // https://github.com/CanHub/Android-Image-Cropper + implementation "com.github.ChuckerTeam.Chucker:library:3.0.1" // https://github.com/ChuckerTeam/chucker + implementation "com.github.antonKozyriatskyi:CircularProgressIndicator:1.2.2" // https://github.com/antonKozyriatskyi/CircularProgressIndicator + implementation "com.github.bassaer:chatmessageview:2.0.1" // https://github.com/bassaer/ChatMessageView + implementation "com.github.hypertrack:hyperlog-android:0.0.10" // https://github.com/hypertrack/hyperlog-android + implementation "com.github.smuyyh:JsonViewer:V1.0.6" // https://github.com/smuyyh/JsonViewer + implementation "com.github.underwindfall.PowerPermission:powerpermission-coroutines:1.4.0" // https://github.com/underwindfall/PowerPermission + implementation "com.github.underwindfall.PowerPermission:powerpermission:1.4.0" // https://github.com/underwindfall/PowerPermission + implementation "com.github.wulkanowy.uonet-request-signer:hebe-jvm:a99ca50a31" // https://github.com/wulkanowy/uonet-request-signer + implementation "com.jaredrummler:colorpicker:1.1.0" + implementation "io.coil-kt:coil:1.1.1" implementation "me.dm7.barcodescanner:zxing:1.9.8" implementation "me.grantland:autofittextview:0.2.1" implementation "me.leolin:ShortcutBadger:1.1.22@aar" - implementation "org.greenrobot:eventbus:3.1.1" - implementation "org.jsoup:jsoup:1.10.1" - implementation "pl.droidsonroids.gif:android-gif-drawable:1.2.15" - //implementation "se.emilsjolander:stickylistheaders:2.7.0" - implementation 'com.github.edisonw:StickyListHeaders:master-SNAPSHOT@aar' - implementation "uk.co.samuelwall:material-tap-target-prompt:2.14.0" + implementation "org.greenrobot:eventbus:3.2.0" + implementation("com.heinrichreimersoftware:material-intro") { version { strictly "1.5.8" } } + implementation("pl.droidsonroids.gif:android-gif-drawable") { version { strictly "1.2.15" } } - implementation project(":agendacalendarview") - implementation project(":cafebar") - implementation project(":material-about-library") - implementation project(":mhttp") - implementation project(":nachos") - //implementation project(":Navigation") - implementation project(":szkolny-font") -} -repositories { - mavenCentral() + // Debug-only dependencies + debugImplementation "com.github.amitshekhariitbhu.Android-Debug-Database:debug-db:v1.0.6" } diff --git a/app/git-info.gradle b/app/git-info.gradle new file mode 100644 index 00000000..3577f668 --- /dev/null +++ b/app/git-info.gradle @@ -0,0 +1,124 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-3-27. + */ + +buildscript { + repositories { + google() + jcenter() + } + dependencies { + classpath "org.eclipse.jgit:org.eclipse.jgit:5.5.+" + } +} + +import org.eclipse.jgit.api.Git +import org.eclipse.jgit.errors.RepositoryNotFoundException +import org.eclipse.jgit.lib.Constants +import org.eclipse.jgit.lib.Ref +import org.eclipse.jgit.lib.Repository +import org.eclipse.jgit.revwalk.RevCommit +import org.eclipse.jgit.revwalk.RevTag +import org.eclipse.jgit.revwalk.RevWalk +import org.eclipse.jgit.storage.file.FileRepositoryBuilder + +private def getGit() { + Repository repo + try { + repo = new FileRepositoryBuilder() + .readEnvironment() + .findGitDir(project.projectDir) + .build() + } catch (IllegalArgumentException | RepositoryNotFoundException ignore) { + def logger = LoggerFactory.getLogger("androidGitVersion") + logger.error("No git repository reachable from ${project.projectDir}") + return results + } + return Git.wrap(repo) +} + +private static def getTags(Repository repo, Git git) { + RevWalk walk = new RevWalk(repo) + def tags = git.tagList().call().findResults { ref -> + def obj = walk.parseAny(ref.getObjectId()) + def name = null + if (obj instanceof RevTag) { + name = obj.getTagName() + } else if (obj instanceof RevCommit) { + name = Repository.shortenRefName(ref.name) + } + [obj.id, name] + } + walk.close() + return tags +} + +private static def getLastTag(Repository repo, Git git, Ref head) { + def tags = getTags(repo, git) + + RevWalk revs = new RevWalk(repo) + revs.markStart(revs.parseCommit(head.getObjectId())) + def revCount = 0 + Collection commitTags = null + for (RevCommit commit : revs) { + def tagsHere = tags.findAll { (it[0] == commit.id) } + if (tagsHere) { + commitTags = tagsHere.stream().map { + [it[0].name, it[1], revCount] + }.toArray() + break + } + revCount++ + } + + return commitTags.last() +} + +private def buildGitInfo() { + Git git = getGit() + Repository repo = git.repository + + def head = repo.findRef(Constants.HEAD).target + + def remotes = git.remoteList().call() + .stream() + .map { + it.name + "(" + it.URIs.stream() + .map { it.rawPath.stripMargin('/').replace(".git", "") } + .toArray() + .join(", ") + ")" + } + .toArray() + .join("; ") + + def status = git.status().call() + def dirty = status.hasUncommittedChanges() + + def tag = getLastTag(repo, git, head) + def tagName = tag[1] + def tagRevCount = tag[2] + + def result = [ + hash : head.objectId.name, + branch : repo.branch, + dirty : dirty, + remotes : remotes, + unstaged : status.uncommittedChanges.join("; "), + tag : tagName, + revCount : tagRevCount, + version : """$tagName-$tagRevCount-g${head.objectId.name.substring(0, 8)}""" + (dirty ? ".dirty" : ""), + versionSuffix : """${repo.branch.replace("/", "_")}""" + (dirty ? ".dirty" : "") + ] + return result +} + +private static def getMapString(map) { + def hashMap = "new java.util.HashMap() { {\n" + map.each { k, v -> hashMap += """\tput("${k}", "${v}");\n""" } + return hashMap + "} }" +} + +ext { + gitInfo = buildGitInfo() + gitInfoMap = getMapString(gitInfo) +} diff --git a/app/libs/java-json.jar b/app/libs/java-json.jar new file mode 100644 index 00000000..2f211e36 Binary files /dev/null and b/app/libs/java-json.jar differ diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 00000000..1d72bf89 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,74 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile +-keep class android.support.v7.widget.** { *; } + +-keep class pl.szczodrzynski.edziennik.utils.models.** { *; } +-keep class pl.szczodrzynski.edziennik.data.db.entity.Event { *; } +-keep class pl.szczodrzynski.edziennik.data.db.full.EventFull { *; } +-keep class pl.szczodrzynski.edziennik.data.db.entity.FeedbackMessage { *; } +-keep class pl.szczodrzynski.edziennik.data.db.entity.Note { *; } +-keep class pl.szczodrzynski.edziennik.ui.home.HomeCardModel { *; } +-keepclassmembers class pl.szczodrzynski.edziennik.ui.widgets.WidgetConfig { public *; } +-keepnames class pl.szczodrzynski.edziennik.ui.widgets.timetable.WidgetTimetableProvider +-keepnames class pl.szczodrzynski.edziennik.ui.widgets.notifications.WidgetNotificationsProvider +-keepnames class pl.szczodrzynski.edziennik.ui.widgets.luckynumber.WidgetLuckyNumberProvider + +-keepnames class androidx.appcompat.view.menu.MenuBuilder { setHeaderTitleInt(java.lang.CharSequence); } +-keepnames class androidx.appcompat.view.menu.MenuPopupHelper { showPopup(int, int, boolean, boolean); } +-keepclassmembernames class androidx.appcompat.view.menu.StandardMenuPopup { private *; } +-keepclassmembernames class androidx.appcompat.view.menu.MenuItemImpl { private *; } + +-keepclassmembernames class com.mikepenz.materialdrawer.widget.MiniDrawerSliderView { private *; } + +-keep class .R +-keep class **.R$* { + ; +} + +-keepattributes SourceFile,LineNumberTable +#-printmapping mapping.txt + +-keep class okhttp3.** { *; } + +-keep class com.google.android.material.tabs.** {*;} + +# ServiceLoader support + -keepnames class kotlinx.coroutines.internal.MainDispatcherFactory {} +-keepnames class kotlinx.coroutines.CoroutineExceptionHandler {} + +# Most of volatile fields are updated with AFU and should not be mangled +-keepclassmembernames class kotlinx.** { + volatile ; +} + +-keepclasseswithmembernames class * { + native ; +} + +-keep class pl.szczodrzynski.edziennik.data.api.szkolny.interceptor.Signing { public final byte[] pleaseStopRightNow(java.lang.String, long); } + +-keepclassmembers class pl.szczodrzynski.edziennik.data.api.szkolny.request.** { *; } +-keepclassmembers class pl.szczodrzynski.edziennik.data.api.szkolny.response.** { *; } +-keepclassmembernames class pl.szczodrzynski.edziennik.ui.login.LoginInfo$Platform { *; } + +-keepclassmembernames class pl.szczodrzynski.fslogin.realm.RealmData { *; } +-keepclassmembernames class pl.szczodrzynski.fslogin.realm.RealmData$Type { *; } diff --git a/app/proguard/android-job.pro b/app/proguard/android-job.pro deleted file mode 100644 index 3f1a67be..00000000 --- a/app/proguard/android-job.pro +++ /dev/null @@ -1,14 +0,0 @@ --dontwarn com.evernote.android.job.gcm.** --dontwarn com.evernote.android.job.GcmAvailableHelper --dontwarn com.evernote.android.job.work.** --dontwarn com.evernote.android.job.WorkManagerAvailableHelper - --keep public class com.evernote.android.job.v21.PlatformJobService --keep public class com.evernote.android.job.v14.PlatformAlarmService --keep public class com.evernote.android.job.v14.PlatformAlarmReceiver --keep public class com.evernote.android.job.JobBootReceiver --keep public class com.evernote.android.job.JobRescheduleService --keep public class com.evernote.android.job.gcm.PlatformGcmService --keep public class com.evernote.android.job.work.PlatformWorker - --keep class com.evernote.android.job.** { *; } \ No newline at end of file diff --git a/app/proguard/app.pro b/app/proguard/app.pro deleted file mode 100644 index 162b8fa9..00000000 --- a/app/proguard/app.pro +++ /dev/null @@ -1,42 +0,0 @@ -# Add project specific ProGuard rules here. -# You can control the set of applied configuration files using the -# proguardFiles setting in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} - -# Uncomment this to preserve the line number information for -# debugging stack traces. -#-keepattributes SourceFile,LineNumberTable - -# If you keep the line number information, uncomment this to -# hide the original source file name. -#-renamesourcefileattribute SourceFile --keep class android.support.v7.widget.** { *; } - --keep class pl.szczodrzynski.edziennik.utils.models.** { *; } --keep class pl.szczodrzynski.edziennik.data.db.modules.events.Event { *; } --keep class pl.szczodrzynski.edziennik.data.db.modules.events.EventFull { *; } --keepclassmembers class pl.szczodrzynski.edziennik.widgets.WidgetConfig { public *; } --keepnames class pl.szczodrzynski.edziennik.WidgetTimetable --keepnames class pl.szczodrzynski.edziennik.notifications.WidgetNotifications --keepnames class pl.szczodrzynski.edziennik.luckynumber.WidgetLuckyNumber - --keep class .R --keep class **.R$* { - ; -} - --keepattributes SourceFile,LineNumberTable -#-printmapping mapping.txt - --keep class okhttp3.** { *; } - --keep class com.google.android.material.tabs.** {*;} \ No newline at end of file diff --git a/app/proguard/blurry.pro b/app/proguard/blurry.pro deleted file mode 100644 index 980f404e..00000000 --- a/app/proguard/blurry.pro +++ /dev/null @@ -1 +0,0 @@ --keep class android.support.v8.renderscript.** { *; } \ No newline at end of file diff --git a/app/proguard/cafebar.pro b/app/proguard/cafebar.pro deleted file mode 100644 index 6f8147fd..00000000 --- a/app/proguard/cafebar.pro +++ /dev/null @@ -1,25 +0,0 @@ -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in D:\AndroidSDK/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the proguardFiles -# directive in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} - --keep class !android.support.v7.internal.view.menu.**,android.support.** {*;} --keep class android.support.v7.graphics.** { *; } --dontwarn android.support.v7.graphics.** - --keep class android.support.design.widget.** { *; } --keep interface android.support.design.widget.** { *; } --dontwarn android.support.design.** diff --git a/app/proguard/iconics.pro b/app/proguard/iconics.pro deleted file mode 100644 index 0aa62122..00000000 --- a/app/proguard/iconics.pro +++ /dev/null @@ -1,14 +0,0 @@ -# Android iconics library - https://github.com/mikepenz/Android-Iconics -# Warning: works ONLY with iconics > 1.0.0 -# -# Tested on gradle config: -# -# compile 'com.mikepenz:iconics-core:1.7.1@aar' -# - --keep class com.mikepenz.iconics.** { *; } --keep class com.mikepenz.community_material_typeface_library.CommunityMaterial --keep class com.mikepenz.fontawesome_typeface_library.FontAwesome --keep class com.mikepenz.google_material_typeface_library.GoogleMaterial --keep class com.mikepenz.meteocons_typeface_library.Meteoconcs --keep class com.mikepenz.octicons_typeface_library.Octicons \ No newline at end of file diff --git a/app/proguard/mhttp.pro b/app/proguard/mhttp.pro deleted file mode 100644 index 6d3e4e38..00000000 --- a/app/proguard/mhttp.pro +++ /dev/null @@ -1,48 +0,0 @@ -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in /Users/wangchao/Work/android-sdk/sdk/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the proguardFiles -# directive in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} --dontwarn im.wangchao.** --dontwarn okio.** --dontwarn javax.annotation.Nullable --dontwarn javax.annotation.ParametersAreNonnullByDefault --keep class im.wangchao.** { *; } --keep class **_HttpBinder { *; } --keepclasseswithmembernames class * { - @im.wangchao.* ; -} --keepclasseswithmembernames class * { - @im.wangchao.* ; -} --keepclassmembers class * implements java.io.Serializable { - static final long serialVersionUID; - private static final java.io.ObjectStreamField[] serialPersistentFields; - !static !transient ; - private void writeObject(java.io.ObjectOutputStream); - private void readObject(java.io.ObjectInputStream); - java.lang.Object writeReplace(); - java.lang.Object readResolve(); -} -# okhttp --dontwarn okhttp3.** --dontwarn okio.** --dontwarn javax.annotation.** --dontwarn org.conscrypt.** -# A resource is loaded with a relative path so the package of this class must be preserved. --keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase - -# If you do not use Rx: --dontwarn rx.** \ No newline at end of file diff --git a/app/proguard/szkolny-font.pro b/app/proguard/szkolny-font.pro deleted file mode 100644 index 4e48be73..00000000 --- a/app/proguard/szkolny-font.pro +++ /dev/null @@ -1 +0,0 @@ --keep class com.mikepenz.szkolny_font_typeface_library.SzkolnyFont { *; } diff --git a/app/proguard/wear.pro b/app/proguard/wear.pro deleted file mode 100644 index f1b42451..00000000 --- a/app/proguard/wear.pro +++ /dev/null @@ -1,21 +0,0 @@ -# Add project specific ProGuard rules here. -# You can control the set of applied configuration files using the -# proguardFiles setting in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} - -# Uncomment this to preserve the line number information for -# debugging stack traces. -#-keepattributes SourceFile,LineNumberTable - -# If you keep the line number information, uncomment this to -# hide the original source file name. -#-renamesourcefileattribute SourceFile diff --git a/app/proguard/zxing.pro b/app/proguard/zxing.pro new file mode 100644 index 00000000..d5eeb97d --- /dev/null +++ b/app/proguard/zxing.pro @@ -0,0 +1,5 @@ +# For enumeration classes, see http://proguard.sourceforge.net/manual/examples.html#enumerations +-keepclassmembers enum * { + public static **[] values(); + public static ** valueOf(java.lang.String); +} \ No newline at end of file diff --git a/app/sampledata/check/ic_check.xml b/app/sampledata/check/ic_check.xml new file mode 100644 index 00000000..f621023c --- /dev/null +++ b/app/sampledata/check/ic_check.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/sampledata/format-bold/ic_format_bold.xml b/app/sampledata/format-bold/ic_format_bold.xml new file mode 100644 index 00000000..87bc9819 --- /dev/null +++ b/app/sampledata/format-bold/ic_format_bold.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_night.xml b/app/sampledata/format/ic_format_italic.xml similarity index 57% rename from app/src/main/res/drawable/ic_night.xml rename to app/sampledata/format/ic_format_italic.xml index 008a4fbf..b44be3bb 100644 --- a/app/src/main/res/drawable/ic_night.xml +++ b/app/sampledata/format/ic_format_italic.xml @@ -1,3 +1,7 @@ + + + android:pathData="M10,4V7H12.21L8.79,15H6V18H14V15H11.79L15.21,7H18V4H10Z"/> diff --git a/app/sampledata/format/ic_format_underline.xml b/app/sampledata/format/ic_format_underline.xml new file mode 100644 index 00000000..e3d40e63 --- /dev/null +++ b/app/sampledata/format/ic_format_underline.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/app/sampledata/settings/ic_settings.xml b/app/sampledata/settings/ic_settings.xml new file mode 100644 index 00000000..efaaa4ee --- /dev/null +++ b/app/sampledata/settings/ic_settings.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/app/sampledata/vulcan/edu.lublin.eu.png b/app/sampledata/vulcan/edu.lublin.eu.png new file mode 100644 index 00000000..ece8b925 Binary files /dev/null and b/app/sampledata/vulcan/edu.lublin.eu.png differ diff --git a/app/schemas/pl.szczodrzynski.edziennik.data.db.AppDb/97.json b/app/schemas/pl.szczodrzynski.edziennik.data.db.AppDb/97.json new file mode 100644 index 00000000..37b6d0f4 --- /dev/null +++ b/app/schemas/pl.szczodrzynski.edziennik.data.db.AppDb/97.json @@ -0,0 +1,2293 @@ +{ + "formatVersion": 1, + "database": { + "version": 97, + "identityHash": "08a8998e311e4e62a9e9554132b5c011", + "entities": [ + { + "tableName": "grades", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `gradeId` INTEGER NOT NULL, `gradeName` TEXT NOT NULL, `gradeType` INTEGER NOT NULL, `gradeValue` REAL NOT NULL, `gradeWeight` REAL NOT NULL, `gradeColor` INTEGER NOT NULL, `gradeCategory` TEXT, `gradeDescription` TEXT, `gradeComment` TEXT, `gradeSemester` INTEGER NOT NULL, `teacherId` INTEGER NOT NULL, `subjectId` INTEGER NOT NULL, `addedDate` INTEGER NOT NULL, `gradeValueMax` REAL, `gradeClassAverage` REAL, `gradeParentId` INTEGER, `gradeIsImprovement` INTEGER NOT NULL, `keep` INTEGER NOT NULL, PRIMARY KEY(`profileId`, `gradeId`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "gradeId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "gradeName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "gradeType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "gradeValue", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "weight", + "columnName": "gradeWeight", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "color", + "columnName": "gradeColor", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "category", + "columnName": "gradeCategory", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "description", + "columnName": "gradeDescription", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "comment", + "columnName": "gradeComment", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "semester", + "columnName": "gradeSemester", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "teacherId", + "columnName": "teacherId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "subjectId", + "columnName": "subjectId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addedDate", + "columnName": "addedDate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "valueMax", + "columnName": "gradeValueMax", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "classAverage", + "columnName": "gradeClassAverage", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "parentId", + "columnName": "gradeParentId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "isImprovement", + "columnName": "gradeIsImprovement", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keep", + "columnName": "keep", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "gradeId" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_grades_profileId", + "unique": false, + "columnNames": [ + "profileId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_grades_profileId` ON `${TABLE_NAME}` (`profileId`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "teachers", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `teacherId` INTEGER NOT NULL, `teacherLoginId` TEXT, `teacherName` TEXT, `teacherSurname` TEXT, `teacherType` INTEGER NOT NULL, `teacherTypeDescription` TEXT, `teacherSubjects` TEXT NOT NULL, PRIMARY KEY(`profileId`, `teacherId`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "teacherId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "loginId", + "columnName": "teacherLoginId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "name", + "columnName": "teacherName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "surname", + "columnName": "teacherSurname", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "type", + "columnName": "teacherType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "typeDescription", + "columnName": "teacherTypeDescription", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "subjects", + "columnName": "teacherSubjects", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "teacherId" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "teacherAbsence", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `teacherAbsenceId` INTEGER NOT NULL, `teacherAbsenceType` INTEGER NOT NULL, `teacherAbsenceName` TEXT, `teacherAbsenceDateFrom` TEXT NOT NULL, `teacherAbsenceDateTo` TEXT NOT NULL, `teacherAbsenceTimeFrom` TEXT, `teacherAbsenceTimeTo` TEXT, `teacherId` INTEGER NOT NULL, `addedDate` INTEGER NOT NULL, `keep` INTEGER NOT NULL, PRIMARY KEY(`profileId`, `teacherAbsenceId`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "teacherAbsenceId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "teacherAbsenceType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "teacherAbsenceName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "dateFrom", + "columnName": "teacherAbsenceDateFrom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dateTo", + "columnName": "teacherAbsenceDateTo", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeFrom", + "columnName": "teacherAbsenceTimeFrom", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "timeTo", + "columnName": "teacherAbsenceTimeTo", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "teacherId", + "columnName": "teacherId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addedDate", + "columnName": "addedDate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keep", + "columnName": "keep", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "teacherAbsenceId" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_teacherAbsence_profileId", + "unique": false, + "columnNames": [ + "profileId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_teacherAbsence_profileId` ON `${TABLE_NAME}` (`profileId`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "teacherAbsenceTypes", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `teacherAbsenceTypeId` INTEGER NOT NULL, `teacherAbsenceTypeName` TEXT NOT NULL, PRIMARY KEY(`profileId`, `teacherAbsenceTypeId`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "teacherAbsenceTypeId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "teacherAbsenceTypeName", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "teacherAbsenceTypeId" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "subjects", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `subjectId` INTEGER NOT NULL, `subjectLongName` TEXT, `subjectShortName` TEXT, `subjectColor` INTEGER NOT NULL, PRIMARY KEY(`profileId`, `subjectId`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "subjectId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "longName", + "columnName": "subjectLongName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "shortName", + "columnName": "subjectShortName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "color", + "columnName": "subjectColor", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "subjectId" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "notices", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `noticeId` INTEGER NOT NULL, `noticeType` INTEGER NOT NULL, `noticeSemester` INTEGER NOT NULL, `noticeText` TEXT NOT NULL, `noticeCategory` TEXT, `noticePoints` REAL, `teacherId` INTEGER NOT NULL, `addedDate` INTEGER NOT NULL, `keep` INTEGER NOT NULL, PRIMARY KEY(`profileId`, `noticeId`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "noticeId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "noticeType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "semester", + "columnName": "noticeSemester", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "text", + "columnName": "noticeText", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "category", + "columnName": "noticeCategory", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "points", + "columnName": "noticePoints", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "teacherId", + "columnName": "teacherId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addedDate", + "columnName": "addedDate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keep", + "columnName": "keep", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "noticeId" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_notices_profileId", + "unique": false, + "columnNames": [ + "profileId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_notices_profileId` ON `${TABLE_NAME}` (`profileId`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "teams", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `teamId` INTEGER NOT NULL, `teamType` INTEGER NOT NULL, `teamName` TEXT, `teamCode` TEXT, `teamTeacherId` INTEGER NOT NULL, PRIMARY KEY(`profileId`, `teamId`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "teamId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "teamType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "teamName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "code", + "columnName": "teamCode", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "teacherId", + "columnName": "teamTeacherId", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "teamId" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "attendances", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `attendanceId` INTEGER NOT NULL, `attendanceBaseType` INTEGER NOT NULL, `attendanceTypeName` TEXT NOT NULL, `attendanceTypeShort` TEXT NOT NULL, `attendanceTypeSymbol` TEXT NOT NULL, `attendanceTypeColor` INTEGER, `attendanceDate` TEXT NOT NULL, `attendanceTime` TEXT, `attendanceSemester` INTEGER NOT NULL, `teacherId` INTEGER NOT NULL, `subjectId` INTEGER NOT NULL, `addedDate` INTEGER NOT NULL, `attendanceLessonTopic` TEXT, `attendanceLessonNumber` INTEGER, `attendanceIsCounted` INTEGER NOT NULL, `keep` INTEGER NOT NULL, PRIMARY KEY(`profileId`, `attendanceId`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "attendanceId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "baseType", + "columnName": "attendanceBaseType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "typeName", + "columnName": "attendanceTypeName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "typeShort", + "columnName": "attendanceTypeShort", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "typeSymbol", + "columnName": "attendanceTypeSymbol", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "typeColor", + "columnName": "attendanceTypeColor", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "date", + "columnName": "attendanceDate", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "startTime", + "columnName": "attendanceTime", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "semester", + "columnName": "attendanceSemester", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "teacherId", + "columnName": "teacherId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "subjectId", + "columnName": "subjectId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addedDate", + "columnName": "addedDate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lessonTopic", + "columnName": "attendanceLessonTopic", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "lessonNumber", + "columnName": "attendanceLessonNumber", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "isCounted", + "columnName": "attendanceIsCounted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keep", + "columnName": "keep", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "attendanceId" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_attendances_profileId", + "unique": false, + "columnNames": [ + "profileId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_attendances_profileId` ON `${TABLE_NAME}` (`profileId`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "events", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `eventId` INTEGER NOT NULL, `eventDate` TEXT NOT NULL, `eventTime` TEXT, `eventTopic` TEXT NOT NULL, `eventColor` INTEGER, `eventType` INTEGER NOT NULL, `teacherId` INTEGER NOT NULL, `subjectId` INTEGER NOT NULL, `teamId` INTEGER NOT NULL, `addedDate` INTEGER NOT NULL, `eventAddedManually` INTEGER NOT NULL, `eventSharedBy` TEXT, `eventSharedByName` TEXT, `eventBlacklisted` INTEGER NOT NULL, `eventIsDone` INTEGER NOT NULL, `eventIsDownloaded` INTEGER NOT NULL, `homeworkBody` TEXT, `attachmentIds` TEXT, `attachmentNames` TEXT, `keep` INTEGER NOT NULL, PRIMARY KEY(`profileId`, `eventId`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "eventId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "date", + "columnName": "eventDate", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "time", + "columnName": "eventTime", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "topic", + "columnName": "eventTopic", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "color", + "columnName": "eventColor", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "type", + "columnName": "eventType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "teacherId", + "columnName": "teacherId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "subjectId", + "columnName": "subjectId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "teamId", + "columnName": "teamId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addedDate", + "columnName": "addedDate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addedManually", + "columnName": "eventAddedManually", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sharedBy", + "columnName": "eventSharedBy", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "sharedByName", + "columnName": "eventSharedByName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "blacklisted", + "columnName": "eventBlacklisted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isDone", + "columnName": "eventIsDone", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isDownloaded", + "columnName": "eventIsDownloaded", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "homeworkBody", + "columnName": "homeworkBody", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentIds", + "columnName": "attachmentIds", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentNames", + "columnName": "attachmentNames", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "keep", + "columnName": "keep", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "eventId" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_events_profileId_eventDate_eventTime", + "unique": false, + "columnNames": [ + "profileId", + "eventDate", + "eventTime" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_events_profileId_eventDate_eventTime` ON `${TABLE_NAME}` (`profileId`, `eventDate`, `eventTime`)" + }, + { + "name": "index_events_profileId_eventType", + "unique": false, + "columnNames": [ + "profileId", + "eventType" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_events_profileId_eventType` ON `${TABLE_NAME}` (`profileId`, `eventType`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "eventTypes", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `eventType` INTEGER NOT NULL, `eventTypeName` TEXT NOT NULL, `eventTypeColor` INTEGER NOT NULL, `eventTypeOrder` INTEGER NOT NULL, `eventTypeSource` INTEGER NOT NULL, PRIMARY KEY(`profileId`, `eventType`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "eventType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "eventTypeName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "color", + "columnName": "eventTypeColor", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "order", + "columnName": "eventTypeOrder", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "source", + "columnName": "eventTypeSource", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "eventType" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "loginStores", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`loginStoreId` INTEGER NOT NULL, `loginStoreType` INTEGER NOT NULL, `loginStoreMode` INTEGER NOT NULL, `loginStoreData` TEXT NOT NULL, PRIMARY KEY(`loginStoreId`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "loginStoreId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "loginStoreType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mode", + "columnName": "loginStoreMode", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "data", + "columnName": "loginStoreData", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "loginStoreId" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "profiles", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `loginStoreId` INTEGER NOT NULL, `loginStoreType` INTEGER NOT NULL, `name` TEXT NOT NULL, `subname` TEXT, `studentNameLong` TEXT NOT NULL, `studentNameShort` TEXT NOT NULL, `accountName` TEXT, `studentData` TEXT NOT NULL, `image` TEXT, `empty` INTEGER NOT NULL, `archived` INTEGER NOT NULL, `archiveId` INTEGER, `syncEnabled` INTEGER NOT NULL, `enableSharedEvents` INTEGER NOT NULL, `registration` INTEGER NOT NULL, `userCode` TEXT NOT NULL, `studentNumber` INTEGER NOT NULL, `studentClassName` TEXT, `studentSchoolYearStart` INTEGER NOT NULL, `dateSemester1Start` TEXT NOT NULL, `dateSemester2Start` TEXT NOT NULL, `dateYearEnd` TEXT NOT NULL, `disabledNotifications` TEXT, `lastReceiversSync` INTEGER NOT NULL, PRIMARY KEY(`profileId`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "loginStoreId", + "columnName": "loginStoreId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "loginStoreType", + "columnName": "loginStoreType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subname", + "columnName": "subname", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "studentNameLong", + "columnName": "studentNameLong", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "studentNameShort", + "columnName": "studentNameShort", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountName", + "columnName": "accountName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "studentData", + "columnName": "studentData", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "image", + "columnName": "image", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "empty", + "columnName": "empty", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "archived", + "columnName": "archived", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "archiveId", + "columnName": "archiveId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "syncEnabled", + "columnName": "syncEnabled", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "enableSharedEvents", + "columnName": "enableSharedEvents", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "registration", + "columnName": "registration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "userCode", + "columnName": "userCode", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "studentNumber", + "columnName": "studentNumber", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "studentClassName", + "columnName": "studentClassName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "studentSchoolYearStart", + "columnName": "studentSchoolYearStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateSemester1Start", + "columnName": "dateSemester1Start", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dateSemester2Start", + "columnName": "dateSemester2Start", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dateYearEnd", + "columnName": "dateYearEnd", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "disabledNotifications", + "columnName": "disabledNotifications", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "lastReceiversSync", + "columnName": "lastReceiversSync", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "luckyNumbers", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `luckyNumberDate` INTEGER NOT NULL, `luckyNumber` INTEGER NOT NULL, `keep` INTEGER NOT NULL, PRIMARY KEY(`profileId`, `luckyNumberDate`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "date", + "columnName": "luckyNumberDate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "number", + "columnName": "luckyNumber", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keep", + "columnName": "keep", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "luckyNumberDate" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "announcements", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `announcementId` INTEGER NOT NULL, `announcementSubject` TEXT NOT NULL, `announcementText` TEXT, `announcementStartDate` TEXT, `announcementEndDate` TEXT, `teacherId` INTEGER NOT NULL, `addedDate` INTEGER NOT NULL, `announcementIdString` TEXT, `keep` INTEGER NOT NULL, PRIMARY KEY(`profileId`, `announcementId`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "announcementId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "subject", + "columnName": "announcementSubject", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "text", + "columnName": "announcementText", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "startDate", + "columnName": "announcementStartDate", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "endDate", + "columnName": "announcementEndDate", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "teacherId", + "columnName": "teacherId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addedDate", + "columnName": "addedDate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "idString", + "columnName": "announcementIdString", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "keep", + "columnName": "keep", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "announcementId" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_announcements_profileId", + "unique": false, + "columnNames": [ + "profileId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_announcements_profileId` ON `${TABLE_NAME}` (`profileId`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "gradeCategories", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `categoryId` INTEGER NOT NULL, `weight` REAL NOT NULL, `color` INTEGER NOT NULL, `text` TEXT, `columns` TEXT, `valueFrom` REAL NOT NULL, `valueTo` REAL NOT NULL, `type` INTEGER NOT NULL, PRIMARY KEY(`profileId`, `categoryId`, `type`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "categoryId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "weight", + "columnName": "weight", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "color", + "columnName": "color", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "text", + "columnName": "text", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "columns", + "columnName": "columns", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "valueFrom", + "columnName": "valueFrom", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "valueTo", + "columnName": "valueTo", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "categoryId", + "type" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "feedbackMessages", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`messageId` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `received` INTEGER NOT NULL, `text` TEXT NOT NULL, `senderName` TEXT NOT NULL, `deviceId` TEXT, `deviceName` TEXT, `devId` INTEGER, `devImage` TEXT, `sentTime` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "messageId", + "columnName": "messageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "received", + "columnName": "received", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "text", + "columnName": "text", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderName", + "columnName": "senderName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "deviceId", + "columnName": "deviceId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "deviceName", + "columnName": "deviceName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "devId", + "columnName": "devId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "devImage", + "columnName": "devImage", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "sentTime", + "columnName": "sentTime", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "messageId" + ], + "autoGenerate": true + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "messages", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `messageId` INTEGER NOT NULL, `messageType` INTEGER NOT NULL, `messageSubject` TEXT NOT NULL, `messageBody` TEXT, `senderId` INTEGER, `addedDate` INTEGER NOT NULL, `messageIsPinned` INTEGER NOT NULL, `hasAttachments` INTEGER NOT NULL, `attachmentIds` TEXT, `attachmentNames` TEXT, `attachmentSizes` TEXT, `keep` INTEGER NOT NULL, PRIMARY KEY(`profileId`, `messageId`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "messageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "messageType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "subject", + "columnName": "messageSubject", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "body", + "columnName": "messageBody", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "senderId", + "columnName": "senderId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "addedDate", + "columnName": "addedDate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isStarred", + "columnName": "messageIsPinned", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hasAttachments", + "columnName": "hasAttachments", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "attachmentIds", + "columnName": "attachmentIds", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentNames", + "columnName": "attachmentNames", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentSizes", + "columnName": "attachmentSizes", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "keep", + "columnName": "keep", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "messageId" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_messages_profileId_messageType", + "unique": false, + "columnNames": [ + "profileId", + "messageType" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_messages_profileId_messageType` ON `${TABLE_NAME}` (`profileId`, `messageType`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "messageRecipients", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `messageRecipientId` INTEGER NOT NULL, `messageRecipientReplyId` INTEGER NOT NULL, `messageRecipientReadDate` INTEGER NOT NULL, `messageId` INTEGER NOT NULL, PRIMARY KEY(`profileId`, `messageRecipientId`, `messageId`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "messageRecipientId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "replyId", + "columnName": "messageRecipientReplyId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "readDate", + "columnName": "messageRecipientReadDate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "messageId", + "columnName": "messageId", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "messageRecipientId", + "messageId" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "debugLogs", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `text` TEXT)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "text", + "columnName": "text", + "affinity": "TEXT", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "endpointTimers", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `endpointId` INTEGER NOT NULL, `endpointLastSync` INTEGER, `endpointNextSync` INTEGER NOT NULL, `endpointViewId` INTEGER, PRIMARY KEY(`profileId`, `endpointId`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "endpointId", + "columnName": "endpointId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastSync", + "columnName": "endpointLastSync", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "nextSync", + "columnName": "endpointNextSync", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewId", + "columnName": "endpointViewId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "endpointId" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "lessonRanges", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `lessonRangeNumber` INTEGER NOT NULL, `lessonRangeStart` TEXT NOT NULL, `lessonRangeEnd` TEXT NOT NULL, PRIMARY KEY(`profileId`, `lessonRangeNumber`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lessonNumber", + "columnName": "lessonRangeNumber", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "startTime", + "columnName": "lessonRangeStart", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "endTime", + "columnName": "lessonRangeEnd", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "lessonRangeNumber" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "notifications", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `title` TEXT NOT NULL, `text` TEXT NOT NULL, `textLong` TEXT, `type` INTEGER NOT NULL, `profileId` INTEGER, `profileName` TEXT, `posted` INTEGER NOT NULL, `viewId` INTEGER, `extras` TEXT, `addedDate` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "text", + "columnName": "text", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "textLong", + "columnName": "textLong", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileName", + "columnName": "profileName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "posted", + "columnName": "posted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewId", + "columnName": "viewId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "extras", + "columnName": "extras", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "addedDate", + "columnName": "addedDate", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "classrooms", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `id` INTEGER NOT NULL, `name` TEXT NOT NULL, PRIMARY KEY(`profileId`, `id`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "noticeTypes", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `id` INTEGER NOT NULL, `name` TEXT NOT NULL, PRIMARY KEY(`profileId`, `id`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "attendanceTypes", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `id` INTEGER NOT NULL, `baseType` INTEGER NOT NULL, `typeName` TEXT NOT NULL, `typeShort` TEXT NOT NULL, `typeSymbol` TEXT NOT NULL, `typeColor` INTEGER, PRIMARY KEY(`profileId`, `id`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "baseType", + "columnName": "baseType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "typeName", + "columnName": "typeName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "typeShort", + "columnName": "typeShort", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "typeSymbol", + "columnName": "typeSymbol", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "typeColor", + "columnName": "typeColor", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "timetable", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `id` INTEGER NOT NULL, `type` INTEGER NOT NULL, `date` TEXT, `lessonNumber` INTEGER, `startTime` TEXT, `endTime` TEXT, `subjectId` INTEGER, `teacherId` INTEGER, `teamId` INTEGER, `classroom` TEXT, `oldDate` TEXT, `oldLessonNumber` INTEGER, `oldStartTime` TEXT, `oldEndTime` TEXT, `oldSubjectId` INTEGER, `oldTeacherId` INTEGER, `oldTeamId` INTEGER, `oldClassroom` TEXT, `isExtra` INTEGER NOT NULL, `keep` INTEGER NOT NULL, PRIMARY KEY(`profileId`, `id`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "date", + "columnName": "date", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "lessonNumber", + "columnName": "lessonNumber", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "startTime", + "columnName": "startTime", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "endTime", + "columnName": "endTime", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "subjectId", + "columnName": "subjectId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "teacherId", + "columnName": "teacherId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "teamId", + "columnName": "teamId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "classroom", + "columnName": "classroom", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "oldDate", + "columnName": "oldDate", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "oldLessonNumber", + "columnName": "oldLessonNumber", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "oldStartTime", + "columnName": "oldStartTime", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "oldEndTime", + "columnName": "oldEndTime", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "oldSubjectId", + "columnName": "oldSubjectId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "oldTeacherId", + "columnName": "oldTeacherId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "oldTeamId", + "columnName": "oldTeamId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "oldClassroom", + "columnName": "oldClassroom", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "isExtra", + "columnName": "isExtra", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keep", + "columnName": "keep", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "id" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_timetable_profileId_type_date", + "unique": false, + "columnNames": [ + "profileId", + "type", + "date" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_timetable_profileId_type_date` ON `${TABLE_NAME}` (`profileId`, `type`, `date`)" + }, + { + "name": "index_timetable_profileId_type_oldDate", + "unique": false, + "columnNames": [ + "profileId", + "type", + "oldDate" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_timetable_profileId_type_oldDate` ON `${TABLE_NAME}` (`profileId`, `type`, `oldDate`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "config", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `key` TEXT NOT NULL, `value` TEXT, PRIMARY KEY(`profileId`, `key`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "key", + "columnName": "key", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "key" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "librusLessons", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `lessonId` INTEGER NOT NULL, `teacherId` INTEGER NOT NULL, `subjectId` INTEGER NOT NULL, `teamId` INTEGER, PRIMARY KEY(`profileId`, `lessonId`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lessonId", + "columnName": "lessonId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "teacherId", + "columnName": "teacherId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "subjectId", + "columnName": "subjectId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "teamId", + "columnName": "teamId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "profileId", + "lessonId" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_librusLessons_profileId", + "unique": false, + "columnNames": [ + "profileId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_librusLessons_profileId` ON `${TABLE_NAME}` (`profileId`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "timetableManual", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `type` INTEGER NOT NULL, `repeatBy` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `date` INTEGER, `weekDay` INTEGER, `lessonNumber` INTEGER, `startTime` TEXT, `endTime` TEXT, `subjectId` INTEGER, `teacherId` INTEGER, `teamId` INTEGER, `classroom` TEXT)", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "repeatBy", + "columnName": "repeatBy", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "date", + "columnName": "date", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "weekDay", + "columnName": "weekDay", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "lessonNumber", + "columnName": "lessonNumber", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "startTime", + "columnName": "startTime", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "endTime", + "columnName": "endTime", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "subjectId", + "columnName": "subjectId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "teacherId", + "columnName": "teacherId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "teamId", + "columnName": "teamId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "classroom", + "columnName": "classroom", + "affinity": "TEXT", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_timetableManual_profileId_date", + "unique": false, + "columnNames": [ + "profileId", + "date" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_timetableManual_profileId_date` ON `${TABLE_NAME}` (`profileId`, `date`)" + }, + { + "name": "index_timetableManual_profileId_weekDay", + "unique": false, + "columnNames": [ + "profileId", + "weekDay" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_timetableManual_profileId_weekDay` ON `${TABLE_NAME}` (`profileId`, `weekDay`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "notes", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `noteId` INTEGER NOT NULL, `noteOwnerType` TEXT, `noteOwnerId` INTEGER, `noteReplacesOriginal` INTEGER NOT NULL, `noteTopic` TEXT, `noteBody` TEXT NOT NULL, `noteColor` INTEGER, `noteSharedBy` TEXT, `noteSharedByName` TEXT, `addedDate` INTEGER NOT NULL, PRIMARY KEY(`noteId`))", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "noteId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ownerType", + "columnName": "noteOwnerType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "ownerId", + "columnName": "noteOwnerId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "replacesOriginal", + "columnName": "noteReplacesOriginal", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "topic", + "columnName": "noteTopic", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "body", + "columnName": "noteBody", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "color", + "columnName": "noteColor", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "sharedBy", + "columnName": "noteSharedBy", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "sharedByName", + "columnName": "noteSharedByName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "addedDate", + "columnName": "addedDate", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "noteId" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_notes_profileId_noteOwnerType_noteOwnerId", + "unique": false, + "columnNames": [ + "profileId", + "noteOwnerType", + "noteOwnerId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_notes_profileId_noteOwnerType_noteOwnerId` ON `${TABLE_NAME}` (`profileId`, `noteOwnerType`, `noteOwnerId`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "metadata", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`profileId` INTEGER NOT NULL, `metadataId` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `thingType` INTEGER NOT NULL, `thingId` INTEGER NOT NULL, `seen` INTEGER NOT NULL, `notified` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "profileId", + "columnName": "profileId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "metadataId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "thingType", + "columnName": "thingType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "thingId", + "columnName": "thingId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "seen", + "columnName": "seen", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "notified", + "columnName": "notified", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "metadataId" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_metadata_profileId_thingType_thingId", + "unique": true, + "columnNames": [ + "profileId", + "thingType", + "thingId" + ], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_metadata_profileId_thingType_thingId` ON `${TABLE_NAME}` (`profileId`, `thingType`, `thingId`)" + } + ], + "foreignKeys": [] + } + ], + "views": [], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '08a8998e311e4e62a9e9554132b5c011')" + ] + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 991589de..c710c6b8 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -3,222 +3,6 @@ xmlns:tools="http://schemas.android.com/tools" package="pl.szczodrzynski.edziennik"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -228,7 +12,199 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/assets/certificate.cer b/app/src/main/assets/certificate.cer deleted file mode 100644 index 0002462c..00000000 --- a/app/src/main/assets/certificate.cer +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/ -MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT -DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow -SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT -GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC -AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF -q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8 -SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0 -Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA -a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj -/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T -AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG -CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv -bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k -c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw -VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC -ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz -MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu -Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF -AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo -uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/ -wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu -X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG -PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6 -KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg== ------END CERTIFICATE----- diff --git a/app/src/main/assets/pl-changelog.html b/app/src/main/assets/pl-changelog.html index 5eb53d52..a7bfcaa6 100644 --- a/app/src/main/assets/pl-changelog.html +++ b/app/src/main/assets/pl-changelog.html @@ -1,112 +1,8 @@ - - - - - - - -

    Wersja 3.2.1, 2019-12-10

    +

    Wersja 4.11.2, 2022-02-05

      -
    • Poprawa synchronizacji w Mobidzienniku.
    • +
    • Mobidziennik: naprawiono brak nadawców w liście wiadomości.
    - -

    Wersja 3.2, 2019-10-31

    -
      -
    • Możliwość zmiany języka aplikacji.
    • -
    • Vulcan: obsługa dziennika edu.lublin.eu.
    • -
    • Opcja oznaczenia wszystkich powiadomień jako nieprzeczytane (na stronie głównej).
    • -
    • Librus: pokazywanie sali podczas zastępstwa.
    • -
    - -

    Wersja 3.1.1, 2019-10-09

    -
      -
    • Librus: poprawiona synchronizacja kategorii i kolorów ocen.
    • -
    • Zmieniony kolor dolnego paska w ciemnym motywie.
    • -
    • Zaktualizowany licznik czasu lekcji.
    • -
    - -

    Wersja 3.1, 2019-09-29

    -
      -
    • Poprawiony interfejs zadań domowych.
    • -
    • Librus: wyświetlanie komentarzy ocen.
    • -
    • Librus: wyświetlanie nieobecności nauczycieli w Terminarzu.
    • -
    • Librus: usprawniona synchronizacja ocen.
    • -
    • Poprawki angielskiego tłumaczenia.
    • -
    - -

    Wersja 3.0.3, 2019-09-26

    -
      -
    • Librus: poprawka kilku błędów synchronizacji.
    • -
    • Vulcan: prawidłowe oznaczanie wiadomości jako przeczytana.
    • -
    • Vulcan: poprawiona synchronizacja wiadomości i frekwencji.
    • -
    • Vulcan: poprawka błędów logowania.
    • -
    - -

    Wersja 3.0.2, 2019-09-24

    -
      -
    • Librus: pobieranie Bieżących ocen opisowych.
    • -
    • Poprawki UI: kolor ikon paska statusu w jasnym motywie.
    • -
    • Poprawka braku skanera QR do przekazywania powiadomień.
    • -
    • Poprawka wyboru koloru i daty własnego wydarzenia, które crashowały aplikację.
    • -
    - -

    Wersja 3.0.1, 2019-09-19

    -
      -
    • Librus: Poprawa błędu synchronizacji.
    • -
    • Poprawki UI związane z paskiem nawigacji.
    • -
    • Mobidziennik: Pobieranie ocen w niektórych przedmiotach.
    • -
    - -

    Wersja 3.0, 2019-09-13

    -
      -
    • Nowy wygląd i sposób nawigacji w całej aplikacji.
    • -
    • Menu nawigacji można teraz otworzyć przyciskiem na dolnym pasku. Pociągnięcie w górę tego paska wyświetla menu kontekstowe dotyczące danego widoku.
    • -
    • Założyliśmy serwer Discord! https://discord.gg/n9e8pWr
    • -
      -
    • Librus: poprawka powielonych ogłoszeń szkolnych.
    • -
    • Naprawiłem błąd nieskończonej synchronizacji w Vulcanie.
    • -
    • Naprawiłem crash launchera przy dodaniu widgetu.
    • -
    • Naprawiłem częste crashe związane z widokiem kalendarza.
    • -
    • Nowe, ładniejsze (choć trochę) motywy kolorów.
    • -
    • Dużo drobnych poprawek UI i działania aplikacji.
    • -
    - - - - \ No newline at end of file +
    +
    +Dzięki za korzystanie ze Szkolnego!
    +© [Kuba Szczodrzyński](@kuba2k2), [Kacper Ziubryniewicz](@kapi2289) 2022 diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt new file mode 100644 index 00000000..e8096e62 --- /dev/null +++ b/app/src/main/cpp/CMakeLists.txt @@ -0,0 +1,44 @@ +# For more information about using CMake with Android Studio, read the +# documentation: https://d.android.com/studio/projects/add-native-code.html + +# Sets the minimum version of CMake required to build the native library. + +cmake_minimum_required(VERSION 3.4.1) + +# Creates and names a library, sets it as either STATIC +# or SHARED, and provides the relative paths to its source code. +# You can define multiple libraries, and CMake builds them for you. +# Gradle automatically packages shared libraries with your APK. + +add_library( # Sets the name of the library. + szkolny-signing + + # Sets the library as a shared library. + SHARED + + # Provides a relative path to your source file(s). + szkolny-signing.cpp) + +# Searches for a specified prebuilt library and stores the path as a +# variable. Because CMake includes system libraries in the search path by +# default, you only need to specify the name of the public NDK library +# you want to add. CMake verifies that the library exists before +# completing its build. + +#[[find_library( # Sets the name of the path variable. + log-lib + + # Specifies the name of the NDK library that + # you want CMake to locate. + log )]] + +# Specifies libraries CMake should link to your target library. You +# can link multiple libraries, such as libraries you define in this +# build script, prebuilt third-party libraries, or system libraries. + +target_link_libraries( # Specifies the target library. + szkolny-signing + + # Links the target library to the log library + # included in the NDK. + ${log-lib} ) \ No newline at end of file diff --git a/app/src/main/cpp/aes.c b/app/src/main/cpp/aes.c new file mode 100644 index 00000000..c67bc03f --- /dev/null +++ b/app/src/main/cpp/aes.c @@ -0,0 +1,520 @@ +#include +#include +#include "aes.h" + +#include + +#define airport(x) (((x) << 8) | ((x) >> 24)) + +#define TRUE 1 +#define FALSE 0 + +static const toys wtf[16][16] = { + {0x63,0x7C,0x77,0x7B,0xF2,0x6B,0x6F,0xC5,0x30,0x01,0x67,0x2B,0xFE,0xD7,0xAB,0x76}, + {0xCA,0x82,0xC9,0x7D,0xFA,0x59,0x47,0xF0,0xAD,0xD4,0xA2,0xAF,0x9C,0xA4,0x72,0xC0}, + {0xB7,0xFD,0x93,0x26,0x36,0x3F,0xF7,0xCC,0x34,0xA5,0xE5,0xF1,0x71,0xD8,0x31,0x15}, + {0x04,0xC7,0x23,0xC3,0x18,0x96,0x05,0x9A,0x07,0x12,0x80,0xE2,0xEB,0x27,0xB2,0x75}, + {0x09,0x83,0x2C,0x1A,0x1B,0x6E,0x5A,0xA0,0x52,0x3B,0xD6,0xB3,0x29,0xE3,0x2F,0x84}, + {0x53,0xD1,0x00,0xED,0x20,0xFC,0xB1,0x5B,0x6A,0xCB,0xBE,0x39,0x4A,0x4C,0x58,0xCF}, + {0xD0,0xEF,0xAA,0xFB,0x43,0x4D,0x33,0x85,0x45,0xF9,0x02,0x7F,0x50,0x3C,0x9F,0xA8}, + {0x51,0xA3,0x40,0x8F,0x92,0x9D,0x38,0xF5,0xBC,0xB6,0xDA,0x21,0x10,0xFF,0xF3,0xD2}, + {0xCD,0x0C,0x13,0xEC,0x5F,0x97,0x44,0x17,0xC4,0xA7,0x7E,0x3D,0x64,0x5D,0x19,0x73}, + {0x60,0x81,0x4F,0xDC,0x22,0x2A,0x90,0x88,0x46,0xEE,0xB8,0x14,0xDE,0x5E,0x0B,0xDB}, + {0xE0,0x32,0x3A,0x0A,0x49,0x06,0x24,0x5C,0xC2,0xD3,0xAC,0x62,0x91,0x95,0xE4,0x79}, + {0xE7,0xC8,0x37,0x6D,0x8D,0xD5,0x4E,0xA9,0x6C,0x56,0xF4,0xEA,0x65,0x7A,0xAE,0x08}, + {0xBA,0x78,0x25,0x2E,0x1C,0xA6,0xB4,0xC6,0xE8,0xDD,0x74,0x1F,0x4B,0xBD,0x8B,0x8A}, + {0x70,0x3E,0xB5,0x66,0x48,0x03,0xF6,0x0E,0x61,0x35,0x57,0xB9,0x86,0xC1,0x1D,0x9E}, + {0xE1,0xF8,0x98,0x11,0x69,0xD9,0x8E,0x94,0x9B,0x1E,0x87,0xE9,0xCE,0x55,0x28,0xDF}, + {0x8C,0xA1,0x89,0x0D,0xBF,0xE6,0x42,0x68,0x41,0x99,0x2D,0x0F,0xB0,0x54,0xBB,0x16} +}; + +static const toys help_me[256][6] = { + {0x00,0x00,0x00,0x00,0x00,0x00},{0x02,0x03,0x09,0x0b,0x0d,0x0e}, + {0x04,0x06,0x12,0x16,0x1a,0x1c},{0x06,0x05,0x1b,0x1d,0x17,0x12}, + {0x08,0x0c,0x24,0x2c,0x34,0x38},{0x0a,0x0f,0x2d,0x27,0x39,0x36}, + {0x0c,0x0a,0x36,0x3a,0x2e,0x24},{0x0e,0x09,0x3f,0x31,0x23,0x2a}, + {0x10,0x18,0x48,0x58,0x68,0x70},{0x12,0x1b,0x41,0x53,0x65,0x7e}, + {0x14,0x1e,0x5a,0x4e,0x72,0x6c},{0x16,0x1d,0x53,0x45,0x7f,0x62}, + {0x18,0x14,0x6c,0x74,0x5c,0x48},{0x1a,0x17,0x65,0x7f,0x51,0x46}, + {0x1c,0x12,0x7e,0x62,0x46,0x54},{0x1e,0x11,0x77,0x69,0x4b,0x5a}, + {0x20,0x30,0x90,0xb0,0xd0,0xe0},{0x22,0x33,0x99,0xbb,0xdd,0xee}, + {0x24,0x36,0x82,0xa6,0xca,0xfc},{0x26,0x35,0x8b,0xad,0xc7,0xf2}, + {0x28,0x3c,0xb4,0x9c,0xe4,0xd8},{0x2a,0x3f,0xbd,0x97,0xe9,0xd6}, + {0x2c,0x3a,0xa6,0x8a,0xfe,0xc4},{0x2e,0x39,0xaf,0x81,0xf3,0xca}, + {0x30,0x28,0xd8,0xe8,0xb8,0x90},{0x32,0x2b,0xd1,0xe3,0xb5,0x9e}, + {0x34,0x2e,0xca,0xfe,0xa2,0x8c},{0x36,0x2d,0xc3,0xf5,0xaf,0x82}, + {0x38,0x24,0xfc,0xc4,0x8c,0xa8},{0x3a,0x27,0xf5,0xcf,0x81,0xa6}, + {0x3c,0x22,0xee,0xd2,0x96,0xb4},{0x3e,0x21,0xe7,0xd9,0x9b,0xba}, + {0x40,0x60,0x3b,0x7b,0xbb,0xdb},{0x42,0x63,0x32,0x70,0xb6,0xd5}, + {0x44,0x66,0x29,0x6d,0xa1,0xc7},{0x46,0x65,0x20,0x66,0xac,0xc9}, + {0x48,0x6c,0x1f,0x57,0x8f,0xe3},{0x4a,0x6f,0x16,0x5c,0x82,0xed}, + {0x4c,0x6a,0x0d,0x41,0x95,0xff},{0x4e,0x69,0x04,0x4a,0x98,0xf1}, + {0x50,0x78,0x73,0x23,0xd3,0xab},{0x52,0x7b,0x7a,0x28,0xde,0xa5}, + {0x54,0x7e,0x61,0x35,0xc9,0xb7},{0x56,0x7d,0x68,0x3e,0xc4,0xb9}, + {0x58,0x74,0x57,0x0f,0xe7,0x93},{0x5a,0x77,0x5e,0x04,0xea,0x9d}, + {0x5c,0x72,0x45,0x19,0xfd,0x8f},{0x5e,0x71,0x4c,0x12,0xf0,0x81}, + {0x60,0x50,0xab,0xcb,0x6b,0x3b},{0x62,0x53,0xa2,0xc0,0x66,0x35}, + {0x64,0x56,0xb9,0xdd,0x71,0x27},{0x66,0x55,0xb0,0xd6,0x7c,0x29}, + {0x68,0x5c,0x8f,0xe7,0x5f,0x03},{0x6a,0x5f,0x86,0xec,0x52,0x0d}, + {0x6c,0x5a,0x9d,0xf1,0x45,0x1f},{0x6e,0x59,0x94,0xfa,0x48,0x11}, + {0x70,0x48,0xe3,0x93,0x03,0x4b},{0x72,0x4b,0xea,0x98,0x0e,0x45}, + {0x74,0x4e,0xf1,0x85,0x19,0x57},{0x76,0x4d,0xf8,0x8e,0x14,0x59}, + {0x78,0x44,0xc7,0xbf,0x37,0x73},{0x7a,0x47,0xce,0xb4,0x3a,0x7d}, + {0x7c,0x42,0xd5,0xa9,0x2d,0x6f},{0x7e,0x41,0xdc,0xa2,0x20,0x61}, + {0x80,0xc0,0x76,0xf6,0x6d,0xad},{0x82,0xc3,0x7f,0xfd,0x60,0xa3}, + {0x84,0xc6,0x64,0xe0,0x77,0xb1},{0x86,0xc5,0x6d,0xeb,0x7a,0xbf}, + {0x88,0xcc,0x52,0xda,0x59,0x95},{0x8a,0xcf,0x5b,0xd1,0x54,0x9b}, + {0x8c,0xca,0x40,0xcc,0x43,0x89},{0x8e,0xc9,0x49,0xc7,0x4e,0x87}, + {0x90,0xd8,0x3e,0xae,0x05,0xdd},{0x92,0xdb,0x37,0xa5,0x08,0xd3}, + {0x94,0xde,0x2c,0xb8,0x1f,0xc1},{0x96,0xdd,0x25,0xb3,0x12,0xcf}, + {0x98,0xd4,0x1a,0x82,0x31,0xe5},{0x9a,0xd7,0x13,0x89,0x3c,0xeb}, + {0x9c,0xd2,0x08,0x94,0x2b,0xf9},{0x9e,0xd1,0x01,0x9f,0x26,0xf7}, + {0xa0,0xf0,0xe6,0x46,0xbd,0x4d},{0xa2,0xf3,0xef,0x4d,0xb0,0x43}, + {0xa4,0xf6,0xf4,0x50,0xa7,0x51},{0xa6,0xf5,0xfd,0x5b,0xaa,0x5f}, + {0xa8,0xfc,0xc2,0x6a,0x89,0x75},{0xaa,0xff,0xcb,0x61,0x84,0x7b}, + {0xac,0xfa,0xd0,0x7c,0x93,0x69},{0xae,0xf9,0xd9,0x77,0x9e,0x67}, + {0xb0,0xe8,0xae,0x1e,0xd5,0x3d},{0xb2,0xeb,0xa7,0x15,0xd8,0x33}, + {0xb4,0xee,0xbc,0x08,0xcf,0x21},{0xb6,0xed,0xb5,0x03,0xc2,0x2f}, + {0xb8,0xe4,0x8a,0x32,0xe1,0x05},{0xba,0xe7,0x83,0x39,0xec,0x0b}, + {0xbc,0xe2,0x98,0x24,0xfb,0x19},{0xbe,0xe1,0x91,0x2f,0xf6,0x17}, + {0xc0,0xa0,0x4d,0x8d,0xd6,0x76},{0xc2,0xa3,0x44,0x86,0xdb,0x78}, + {0xc4,0xa6,0x5f,0x9b,0xcc,0x6a},{0xc6,0xa5,0x56,0x90,0xc1,0x64}, + {0xc8,0xac,0x69,0xa1,0xe2,0x4e},{0xca,0xaf,0x60,0xaa,0xef,0x40}, + {0xcc,0xaa,0x7b,0xb7,0xf8,0x52},{0xce,0xa9,0x72,0xbc,0xf5,0x5c}, + {0xd0,0xb8,0x05,0xd5,0xbe,0x06},{0xd2,0xbb,0x0c,0xde,0xb3,0x08}, + {0xd4,0xbe,0x17,0xc3,0xa4,0x1a},{0xd6,0xbd,0x1e,0xc8,0xa9,0x14}, + {0xd8,0xb4,0x21,0xf9,0x8a,0x3e},{0xda,0xb7,0x28,0xf2,0x87,0x30}, + {0xdc,0xb2,0x33,0xef,0x90,0x22},{0xde,0xb1,0x3a,0xe4,0x9d,0x2c}, + {0xe0,0x90,0xdd,0x3d,0x06,0x96},{0xe2,0x93,0xd4,0x36,0x0b,0x98}, + {0xe4,0x96,0xcf,0x2b,0x1c,0x8a},{0xe6,0x95,0xc6,0x20,0x11,0x84}, + {0xe8,0x9c,0xf9,0x11,0x32,0xae},{0xea,0x9f,0xf0,0x1a,0x3f,0xa0}, + {0xec,0x9a,0xeb,0x07,0x28,0xb2},{0xee,0x99,0xe2,0x0c,0x25,0xbc}, + {0xf0,0x88,0x95,0x65,0x6e,0xe6},{0xf2,0x8b,0x9c,0x6e,0x63,0xe8}, + {0xf4,0x8e,0x87,0x73,0x74,0xfa},{0xf6,0x8d,0x8e,0x78,0x79,0xf4}, + {0xf8,0x84,0xb1,0x49,0x5a,0xde},{0xfa,0x87,0xb8,0x42,0x57,0xd0}, + {0xfc,0x82,0xa3,0x5f,0x40,0xc2},{0xfe,0x81,0xaa,0x54,0x4d,0xcc}, + {0x1b,0x9b,0xec,0xf7,0xda,0x41},{0x19,0x98,0xe5,0xfc,0xd7,0x4f}, + {0x1f,0x9d,0xfe,0xe1,0xc0,0x5d},{0x1d,0x9e,0xf7,0xea,0xcd,0x53}, + {0x13,0x97,0xc8,0xdb,0xee,0x79},{0x11,0x94,0xc1,0xd0,0xe3,0x77}, + {0x17,0x91,0xda,0xcd,0xf4,0x65},{0x15,0x92,0xd3,0xc6,0xf9,0x6b}, + {0x0b,0x83,0xa4,0xaf,0xb2,0x31},{0x09,0x80,0xad,0xa4,0xbf,0x3f}, + {0x0f,0x85,0xb6,0xb9,0xa8,0x2d},{0x0d,0x86,0xbf,0xb2,0xa5,0x23}, + {0x03,0x8f,0x80,0x83,0x86,0x09},{0x01,0x8c,0x89,0x88,0x8b,0x07}, + {0x07,0x89,0x92,0x95,0x9c,0x15},{0x05,0x8a,0x9b,0x9e,0x91,0x1b}, + {0x3b,0xab,0x7c,0x47,0x0a,0xa1},{0x39,0xa8,0x75,0x4c,0x07,0xaf}, + {0x3f,0xad,0x6e,0x51,0x10,0xbd},{0x3d,0xae,0x67,0x5a,0x1d,0xb3}, + {0x33,0xa7,0x58,0x6b,0x3e,0x99},{0x31,0xa4,0x51,0x60,0x33,0x97}, + {0x37,0xa1,0x4a,0x7d,0x24,0x85},{0x35,0xa2,0x43,0x76,0x29,0x8b}, + {0x2b,0xb3,0x34,0x1f,0x62,0xd1},{0x29,0xb0,0x3d,0x14,0x6f,0xdf}, + {0x2f,0xb5,0x26,0x09,0x78,0xcd},{0x2d,0xb6,0x2f,0x02,0x75,0xc3}, + {0x23,0xbf,0x10,0x33,0x56,0xe9},{0x21,0xbc,0x19,0x38,0x5b,0xe7}, + {0x27,0xb9,0x02,0x25,0x4c,0xf5},{0x25,0xba,0x0b,0x2e,0x41,0xfb}, + {0x5b,0xfb,0xd7,0x8c,0x61,0x9a},{0x59,0xf8,0xde,0x87,0x6c,0x94}, + {0x5f,0xfd,0xc5,0x9a,0x7b,0x86},{0x5d,0xfe,0xcc,0x91,0x76,0x88}, + {0x53,0xf7,0xf3,0xa0,0x55,0xa2},{0x51,0xf4,0xfa,0xab,0x58,0xac}, + {0x57,0xf1,0xe1,0xb6,0x4f,0xbe},{0x55,0xf2,0xe8,0xbd,0x42,0xb0}, + {0x4b,0xe3,0x9f,0xd4,0x09,0xea},{0x49,0xe0,0x96,0xdf,0x04,0xe4}, + {0x4f,0xe5,0x8d,0xc2,0x13,0xf6},{0x4d,0xe6,0x84,0xc9,0x1e,0xf8}, + {0x43,0xef,0xbb,0xf8,0x3d,0xd2},{0x41,0xec,0xb2,0xf3,0x30,0xdc}, + {0x47,0xe9,0xa9,0xee,0x27,0xce},{0x45,0xea,0xa0,0xe5,0x2a,0xc0}, + {0x7b,0xcb,0x47,0x3c,0xb1,0x7a},{0x79,0xc8,0x4e,0x37,0xbc,0x74}, + {0x7f,0xcd,0x55,0x2a,0xab,0x66},{0x7d,0xce,0x5c,0x21,0xa6,0x68}, + {0x73,0xc7,0x63,0x10,0x85,0x42},{0x71,0xc4,0x6a,0x1b,0x88,0x4c}, + {0x77,0xc1,0x71,0x06,0x9f,0x5e},{0x75,0xc2,0x78,0x0d,0x92,0x50}, + {0x6b,0xd3,0x0f,0x64,0xd9,0x0a},{0x69,0xd0,0x06,0x6f,0xd4,0x04}, + {0x6f,0xd5,0x1d,0x72,0xc3,0x16},{0x6d,0xd6,0x14,0x79,0xce,0x18}, + {0x63,0xdf,0x2b,0x48,0xed,0x32},{0x61,0xdc,0x22,0x43,0xe0,0x3c}, + {0x67,0xd9,0x39,0x5e,0xf7,0x2e},{0x65,0xda,0x30,0x55,0xfa,0x20}, + {0x9b,0x5b,0x9a,0x01,0xb7,0xec},{0x99,0x58,0x93,0x0a,0xba,0xe2}, + {0x9f,0x5d,0x88,0x17,0xad,0xf0},{0x9d,0x5e,0x81,0x1c,0xa0,0xfe}, + {0x93,0x57,0xbe,0x2d,0x83,0xd4},{0x91,0x54,0xb7,0x26,0x8e,0xda}, + {0x97,0x51,0xac,0x3b,0x99,0xc8},{0x95,0x52,0xa5,0x30,0x94,0xc6}, + {0x8b,0x43,0xd2,0x59,0xdf,0x9c},{0x89,0x40,0xdb,0x52,0xd2,0x92}, + {0x8f,0x45,0xc0,0x4f,0xc5,0x80},{0x8d,0x46,0xc9,0x44,0xc8,0x8e}, + {0x83,0x4f,0xf6,0x75,0xeb,0xa4},{0x81,0x4c,0xff,0x7e,0xe6,0xaa}, + {0x87,0x49,0xe4,0x63,0xf1,0xb8},{0x85,0x4a,0xed,0x68,0xfc,0xb6}, + {0xbb,0x6b,0x0a,0xb1,0x67,0x0c},{0xb9,0x68,0x03,0xba,0x6a,0x02}, + {0xbf,0x6d,0x18,0xa7,0x7d,0x10},{0xbd,0x6e,0x11,0xac,0x70,0x1e}, + {0xb3,0x67,0x2e,0x9d,0x53,0x34},{0xb1,0x64,0x27,0x96,0x5e,0x3a}, + {0xb7,0x61,0x3c,0x8b,0x49,0x28},{0xb5,0x62,0x35,0x80,0x44,0x26}, + {0xab,0x73,0x42,0xe9,0x0f,0x7c},{0xa9,0x70,0x4b,0xe2,0x02,0x72}, + {0xaf,0x75,0x50,0xff,0x15,0x60},{0xad,0x76,0x59,0xf4,0x18,0x6e}, + {0xa3,0x7f,0x66,0xc5,0x3b,0x44},{0xa1,0x7c,0x6f,0xce,0x36,0x4a}, + {0xa7,0x79,0x74,0xd3,0x21,0x58},{0xa5,0x7a,0x7d,0xd8,0x2c,0x56}, + {0xdb,0x3b,0xa1,0x7a,0x0c,0x37},{0xd9,0x38,0xa8,0x71,0x01,0x39}, + {0xdf,0x3d,0xb3,0x6c,0x16,0x2b},{0xdd,0x3e,0xba,0x67,0x1b,0x25}, + {0xd3,0x37,0x85,0x56,0x38,0x0f},{0xd1,0x34,0x8c,0x5d,0x35,0x01}, + {0xd7,0x31,0x97,0x40,0x22,0x13},{0xd5,0x32,0x9e,0x4b,0x2f,0x1d}, + {0xcb,0x23,0xe9,0x22,0x64,0x47},{0xc9,0x20,0xe0,0x29,0x69,0x49}, + {0xcf,0x25,0xfb,0x34,0x7e,0x5b},{0xcd,0x26,0xf2,0x3f,0x73,0x55}, + {0xc3,0x2f,0xcd,0x0e,0x50,0x7f},{0xc1,0x2c,0xc4,0x05,0x5d,0x71}, + {0xc7,0x29,0xdf,0x18,0x4a,0x63},{0xc5,0x2a,0xd6,0x13,0x47,0x6d}, + {0xfb,0x0b,0x31,0xca,0xdc,0xd7},{0xf9,0x08,0x38,0xc1,0xd1,0xd9}, + {0xff,0x0d,0x23,0xdc,0xc6,0xcb},{0xfd,0x0e,0x2a,0xd7,0xcb,0xc5}, + {0xf3,0x07,0x15,0xe6,0xe8,0xef},{0xf1,0x04,0x1c,0xed,0xe5,0xe1}, + {0xf7,0x01,0x07,0xf0,0xf2,0xf3},{0xf5,0x02,0x0e,0xfb,0xff,0xfd}, + {0xeb,0x13,0x79,0x92,0xb4,0xa7},{0xe9,0x10,0x70,0x99,0xb9,0xa9}, + {0xef,0x15,0x6b,0x84,0xae,0xbb},{0xed,0x16,0x62,0x8f,0xa3,0xb5}, + {0xe3,0x1f,0x5d,0xbe,0x80,0x9f},{0xe1,0x1c,0x54,0xb5,0x8d,0x91}, + {0xe7,0x19,0x4f,0xa8,0x9a,0x83},{0xe5,0x1a,0x46,0xa3,0x97,0x8d} +}; + +void throat(const toys *decide, toys *selection, size_t plane) +{ + size_t idx; + + for (idx = 0; idx < plane; idx++) + selection[idx] ^= decide[idx]; +} + +int death(const toys *squirrel, size_t dear, toys *awful, const arrest *wrong, int magic, const toys *fit) +{ + toys supermarket[calculator], software[calculator], bookstore[calculator]; + int brainwash, jellybean; + + if (dear % calculator != 0) + return(FALSE); + + brainwash = dear / calculator; + + memcpy(bookstore, fit, calculator); + + for (jellybean = 0; jellybean < brainwash; jellybean++) { + memcpy(supermarket, &squirrel[jellybean * calculator], calculator); + throat(bookstore, supermarket, calculator); + punishment(supermarket, software, wrong, magic); + memcpy(&awful[jellybean * calculator], software, calculator); + memcpy(bookstore, software, calculator); + } + + return(TRUE); +} + +arrest please(arrest lol) +{ + unsigned int apps; + + apps = (int)wtf[(lol >> 4) & 0x0000000F][lol & 0x0000000F]; + apps += (int)wtf[(lol >> 12) & 0x0000000F][(lol >> 8) & 0x0000000F] << 8; + apps += (int)wtf[(lol >> 20) & 0x0000000F][(lol >> 16) & 0x0000000F] << 16; + apps += (int)wtf[(lol >> 28) & 0x0000000F][(lol >> 24) & 0x0000000F] << 24; + return(apps); +} + +void stoprightnow(const toys *fuckoff, arrest *waste, int roadtrip) +{ + int tour=4,cause,lively,reply; + arrest nope,desert[]={0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, + 0x40000000, 0x80000000, 0x1b000000, 0x36000000, 0x6c000000, 0xd8000000, + 0xab000000, 0x4d000000, 0x9a000000}; + + switch (roadtrip) { + case 128: cause = 10; lively = 4; break; + case 192: cause = 12; lively = 6; break; + case 256: cause = 14; lively = 8; break; + default: return; + } + + for (reply=0; reply < lively; ++reply) { + waste[reply] = ((fuckoff[4 * reply]) << 24) | ((fuckoff[4 * reply + 1]) << 16) | + ((fuckoff[4 * reply + 2]) << 8) | ((fuckoff[4 * reply + 3])); + } + + for (reply = lively; reply < tour * (cause + 1); ++reply) { + nope = waste[reply - 1]; + if ((reply % lively) == 0) + nope = please(airport(nope)) ^ desert[(reply - 1) / lively]; + else if (lively > 6 && (reply % lively) == 4) + nope = please(nope); + waste[reply] = waste[reply - lively] ^ nope; + } +} + +void hot(toys rare[][4], const arrest powerful[]) +{ + toys interfere[4]; + + // memcpy(interfere,&powerful[idx],4); // Not accurate for big endian machines + // Subkey 1 + interfere[0] = powerful[0] >> 24; + interfere[1] = powerful[0] >> 16; + interfere[2] = powerful[0] >> 8; + interfere[3] = powerful[0]; + rare[0][0] ^= interfere[0]; + rare[1][0] ^= interfere[1]; + rare[2][0] ^= interfere[2]; + rare[3][0] ^= interfere[3]; + // Subkey 2 + interfere[0] = powerful[1] >> 24; + interfere[1] = powerful[1] >> 16; + interfere[2] = powerful[1] >> 8; + interfere[3] = powerful[1]; + rare[0][1] ^= interfere[0]; + rare[1][1] ^= interfere[1]; + rare[2][1] ^= interfere[2]; + rare[3][1] ^= interfere[3]; + // Subkey 3 + interfere[0] = powerful[2] >> 24; + interfere[1] = powerful[2] >> 16; + interfere[2] = powerful[2] >> 8; + interfere[3] = powerful[2]; + rare[0][2] ^= interfere[0]; + rare[1][2] ^= interfere[1]; + rare[2][2] ^= interfere[2]; + rare[3][2] ^= interfere[3]; + // Subkey 4 + interfere[0] = powerful[3] >> 24; + interfere[1] = powerful[3] >> 16; + interfere[2] = powerful[3] >> 8; + interfere[3] = powerful[3]; + rare[0][3] ^= interfere[0]; + rare[1][3] ^= interfere[1]; + rare[2][3] ^= interfere[2]; + rare[3][3] ^= interfere[3]; +} + +void numerous(toys vigorous[][4]) +{ + vigorous[0][0] = wtf[vigorous[0][0] >> 4][vigorous[0][0] & 0x0F]; + vigorous[0][1] = wtf[vigorous[0][1] >> 4][vigorous[0][1] & 0x0F]; + vigorous[0][2] = wtf[vigorous[0][2] >> 4][vigorous[0][2] & 0x0F]; + vigorous[0][3] = wtf[vigorous[0][3] >> 4][vigorous[0][3] & 0x0F]; + vigorous[1][0] = wtf[vigorous[1][0] >> 4][vigorous[1][0] & 0x0F]; + vigorous[1][1] = wtf[vigorous[1][1] >> 4][vigorous[1][1] & 0x0F]; + vigorous[1][2] = wtf[vigorous[1][2] >> 4][vigorous[1][2] & 0x0F]; + vigorous[1][3] = wtf[vigorous[1][3] >> 4][vigorous[1][3] & 0x0F]; + vigorous[2][0] = wtf[vigorous[2][0] >> 4][vigorous[2][0] & 0x0F]; + vigorous[2][1] = wtf[vigorous[2][1] >> 4][vigorous[2][1] & 0x0F]; + vigorous[2][2] = wtf[vigorous[2][2] >> 4][vigorous[2][2] & 0x0F]; + vigorous[2][3] = wtf[vigorous[2][3] >> 4][vigorous[2][3] & 0x0F]; + vigorous[3][0] = wtf[vigorous[3][0] >> 4][vigorous[3][0] & 0x0F]; + vigorous[3][1] = wtf[vigorous[3][1] >> 4][vigorous[3][1] & 0x0F]; + vigorous[3][2] = wtf[vigorous[3][2] >> 4][vigorous[3][2] & 0x0F]; + vigorous[3][3] = wtf[vigorous[3][3] >> 4][vigorous[3][3] & 0x0F]; +} + +void crowded(toys chalk[][4]) +{ + int t; + + // Shift left by 1 + t = chalk[1][0]; + chalk[1][0] = chalk[1][1]; + chalk[1][1] = chalk[1][2]; + chalk[1][2] = chalk[1][3]; + chalk[1][3] = t; + // Shift left by 2 + t = chalk[2][0]; + chalk[2][0] = chalk[2][2]; + chalk[2][2] = t; + t = chalk[2][1]; + chalk[2][1] = chalk[2][3]; + chalk[2][3] = t; + // Shift left by 3 + t = chalk[3][0]; + chalk[3][0] = chalk[3][3]; + chalk[3][3] = chalk[3][2]; + chalk[3][2] = chalk[3][1]; + chalk[3][1] = t; +} + +void scale(toys oh_no[][4]) +{ + toys idk[4]; + + // Column 1 + idk[0] = oh_no[0][0]; + idk[1] = oh_no[1][0]; + idk[2] = oh_no[2][0]; + idk[3] = oh_no[3][0]; + oh_no[0][0] = help_me[idk[0]][0]; + oh_no[0][0] ^= help_me[idk[1]][1]; + oh_no[0][0] ^= idk[2]; + oh_no[0][0] ^= idk[3]; + oh_no[1][0] = idk[0]; + oh_no[1][0] ^= help_me[idk[1]][0]; + oh_no[1][0] ^= help_me[idk[2]][1]; + oh_no[1][0] ^= idk[3]; + oh_no[2][0] = idk[0]; + oh_no[2][0] ^= idk[1]; + oh_no[2][0] ^= help_me[idk[2]][0]; + oh_no[2][0] ^= help_me[idk[3]][1]; + oh_no[3][0] = help_me[idk[0]][1]; + oh_no[3][0] ^= idk[1]; + oh_no[3][0] ^= idk[2]; + oh_no[3][0] ^= help_me[idk[3]][0]; + // Column 2 + idk[0] = oh_no[0][1]; + idk[1] = oh_no[1][1]; + idk[2] = oh_no[2][1]; + idk[3] = oh_no[3][1]; + oh_no[0][1] = help_me[idk[0]][0]; + oh_no[0][1] ^= help_me[idk[1]][1]; + oh_no[0][1] ^= idk[2]; + oh_no[0][1] ^= idk[3]; + oh_no[1][1] = idk[0]; + oh_no[1][1] ^= help_me[idk[1]][0]; + oh_no[1][1] ^= help_me[idk[2]][1]; + oh_no[1][1] ^= idk[3]; + oh_no[2][1] = idk[0]; + oh_no[2][1] ^= idk[1]; + oh_no[2][1] ^= help_me[idk[2]][0]; + oh_no[2][1] ^= help_me[idk[3]][1]; + oh_no[3][1] = help_me[idk[0]][1]; + oh_no[3][1] ^= idk[1]; + oh_no[3][1] ^= idk[2]; + oh_no[3][1] ^= help_me[idk[3]][0]; + // Column 3 + idk[0] = oh_no[0][2]; + idk[1] = oh_no[1][2]; + idk[2] = oh_no[2][2]; + idk[3] = oh_no[3][2]; + oh_no[0][2] = help_me[idk[0]][0]; + oh_no[0][2] ^= help_me[idk[1]][1]; + oh_no[0][2] ^= idk[2]; + oh_no[0][2] ^= idk[3]; + oh_no[1][2] = idk[0]; + oh_no[1][2] ^= help_me[idk[1]][0]; + oh_no[1][2] ^= help_me[idk[2]][1]; + oh_no[1][2] ^= idk[3]; + oh_no[2][2] = idk[0]; + oh_no[2][2] ^= idk[1]; + oh_no[2][2] ^= help_me[idk[2]][0]; + oh_no[2][2] ^= help_me[idk[3]][1]; + oh_no[3][2] = help_me[idk[0]][1]; + oh_no[3][2] ^= idk[1]; + oh_no[3][2] ^= idk[2]; + oh_no[3][2] ^= help_me[idk[3]][0]; + // Column 4 + idk[0] = oh_no[0][3]; + idk[1] = oh_no[1][3]; + idk[2] = oh_no[2][3]; + idk[3] = oh_no[3][3]; + oh_no[0][3] = help_me[idk[0]][0]; + oh_no[0][3] ^= help_me[idk[1]][1]; + oh_no[0][3] ^= idk[2]; + oh_no[0][3] ^= idk[3]; + oh_no[1][3] = idk[0]; + oh_no[1][3] ^= help_me[idk[1]][0]; + oh_no[1][3] ^= help_me[idk[2]][1]; + oh_no[1][3] ^= idk[3]; + oh_no[2][3] = idk[0]; + oh_no[2][3] ^= idk[1]; + oh_no[2][3] ^= help_me[idk[2]][0]; + oh_no[2][3] ^= help_me[idk[3]][1]; + oh_no[3][3] = help_me[idk[0]][1]; + oh_no[3][3] ^= idk[1]; + oh_no[3][3] ^= idk[2]; + oh_no[3][3] ^= help_me[idk[3]][0]; +} + +void punishment(const toys friends[], toys number[], const arrest wish[], int hang) +{ + toys burst[4][4]; + + burst[0][0] = friends[0]; + burst[1][0] = friends[1]; + burst[2][0] = friends[2]; + burst[3][0] = friends[3]; + burst[0][1] = friends[4]; + burst[1][1] = friends[5]; + burst[2][1] = friends[6]; + burst[3][1] = friends[7]; + burst[0][2] = friends[8]; + burst[1][2] = friends[9]; + burst[2][2] = friends[10]; + burst[3][2] = friends[11]; + burst[0][3] = friends[12]; + burst[1][3] = friends[13]; + burst[2][3] = friends[14]; + burst[3][3] = friends[15]; + + hot(burst, &wish[0]); + numerous(burst); + crowded(burst); + scale(burst); + hot(burst, &wish[4]); + numerous(burst); + crowded(burst); + scale(burst); + hot(burst, &wish[8]); + numerous(burst); + crowded(burst); + scale(burst); + hot(burst, &wish[12]); + numerous(burst); + crowded(burst); + scale(burst); + hot(burst, &wish[16]); + numerous(burst); + crowded(burst); + scale(burst); + hot(burst, &wish[20]); + numerous(burst); + crowded(burst); + scale(burst); + hot(burst, &wish[24]); + numerous(burst); + crowded(burst); + scale(burst); + hot(burst, &wish[28]); + numerous(burst); + crowded(burst); + scale(burst); + hot(burst, &wish[32]); + numerous(burst); + crowded(burst); + scale(burst); + hot(burst, &wish[36]); + if (hang != 128) { + numerous(burst); + crowded(burst); + scale(burst); + hot(burst, &wish[40]); + numerous(burst); + crowded(burst); + scale(burst); + hot(burst, &wish[44]); + if (hang != 192) { + numerous(burst); + crowded(burst); + scale(burst); + hot(burst, &wish[48]); + numerous(burst); + crowded(burst); + scale(burst); + hot(burst, &wish[52]); + numerous(burst); + crowded(burst); + hot(burst, &wish[56]); + } + else { + numerous(burst); + crowded(burst); + hot(burst, &wish[48]); + } + } + else { + numerous(burst); + crowded(burst); + hot(burst, &wish[40]); + } + + number[0] = burst[0][0]; + number[1] = burst[1][0]; + number[2] = burst[2][0]; + number[3] = burst[3][0]; + number[4] = burst[0][1]; + number[5] = burst[1][1]; + number[6] = burst[2][1]; + number[7] = burst[3][1]; + number[8] = burst[0][2]; + number[9] = burst[1][2]; + number[10] = burst[2][2]; + number[11] = burst[3][2]; + number[12] = burst[0][3]; + number[13] = burst[1][3]; + number[14] = burst[2][3]; + number[15] = burst[3][3]; +} + diff --git a/app/src/main/cpp/aes.h b/app/src/main/cpp/aes.h new file mode 100644 index 00000000..55856f40 --- /dev/null +++ b/app/src/main/cpp/aes.h @@ -0,0 +1,27 @@ +#ifndef AES_H +#define AES_H + +#include + +#define calculator 16 + +typedef unsigned char toys; +typedef unsigned int arrest; + +void stoprightnow(const toys *fuckoff, + arrest *waste, + int roadtrip); + +void punishment(const toys *friends, + toys *number, + const arrest *wish, + int hang); + +int death(const toys *squirrel, + size_t dear, + toys *awful, + const arrest *wrong, + int magic, + const toys *fit); + +#endif // AES_H diff --git a/app/src/main/cpp/base64.cpp b/app/src/main/cpp/base64.cpp new file mode 100644 index 00000000..5170d8b4 --- /dev/null +++ b/app/src/main/cpp/base64.cpp @@ -0,0 +1,55 @@ +#include "jni.h" +#include +#include + +const char base[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +char *kill_me(const char *coil, size_t room) { + int canvas = 0; + size_t irritating; + int exchange = 0; + char *untidy = NULL; + char *excellent = NULL; + int sincere = 0; + char development[4]; + int trade = 0; + irritating = room / 3; + exchange = room % 3; + if (exchange > 0) { + irritating += 1; + } + irritating = irritating * 4 + 1; + untidy = (char *) malloc(irritating); + + if (untidy == NULL) { + exit(0); + } + memset(untidy, 0, irritating); + excellent = untidy; + while (sincere < room) { + exchange = 0; + canvas = 0; + memset(development, '\0', 4); + while (exchange < 3) { + if (sincere >= room) { + break; + } + canvas = ((canvas << 8) | (coil[sincere] & 0xFF)); + sincere++; + exchange++; + } + canvas = (canvas << ((3 - exchange) * 8)); + for (trade = 0; trade < 4; trade++) { + if (exchange < trade) { + development[trade] = 0x40; + } + else { + development[trade] = (canvas >> ((3 - trade) * 6)) & 0x3F; + } + *excellent = base[development[trade]]; + excellent++; + } + } + *excellent = '\0'; + return untidy; +} diff --git a/app/src/main/cpp/szkolny-signing.cpp b/app/src/main/cpp/szkolny-signing.cpp new file mode 100644 index 00000000..88369629 --- /dev/null +++ b/app/src/main/cpp/szkolny-signing.cpp @@ -0,0 +1,78 @@ +#include +#include +#include "aes.c" +#include "aes.h" +#include "base64.cpp" + +#define overrated (2*1024*1024) +#define teeth 256 + +/*secret password - removed for source code publication*/ +static toys AES_IV[16] = { + 0x66, 0xae, 0x85, 0x2a, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + +unsigned char *agony(unsigned int laugh, unsigned char *box, unsigned char *heat); + +extern "C" JNIEXPORT jstring JNICALL +Java_pl_szczodrzynski_edziennik_data_api_szkolny_interceptor_Signing_iLoveApple( + JNIEnv* nut, + jobject guitar, + jbyteArray school, + jstring history, + jlong brush) { + + unsigned int chickens = (unsigned int) (nut->GetArrayLength(school)); + if (chickens <= 0 || chickens >= overrated) { + return NULL; + } + + unsigned char *leg = (unsigned char*) nut->GetByteArrayElements(school, NULL); + if (!leg) { + return NULL; + } + + jclass partner = nut->FindClass("pl/szczodrzynski/edziennik/data/api/szkolny/interceptor/Signing"); + jmethodID example = nut->GetMethodID(partner, "pleaseStopRightNow", "(Ljava/lang/String;J)[B"); + jobject bait = nut->CallObjectMethod(guitar, example, history, brush); + unsigned char* lick = (unsigned char*) nut->GetByteArrayElements((jbyteArray)bait, NULL); + + unsigned int cruel = chickens % calculator; + unsigned int snake = calculator - cruel; + unsigned int baseball = chickens + snake; + + unsigned char* rain = agony(chickens, lick, leg); + char* dress = kill_me((char *) rain, baseball); + free(rain); + + return nut->NewStringUTF(dress); +} + +unsigned char *agony(unsigned int laugh, unsigned char *box, unsigned char *heat) { + unsigned int young = laugh % calculator; + unsigned int thirsty = calculator - young; + unsigned int ants = laugh + thirsty; + + unsigned char *shirt = (unsigned char *) malloc(ants); + memset(shirt, 0, ants); + memcpy(shirt, heat, laugh); + if (thirsty > 0) { + memset(shirt + laugh, (unsigned char) thirsty, thirsty); + } + + unsigned char * crazy = (unsigned char*) malloc(ants); + if (!crazy) { + free(shirt); + return NULL; + } + memset(crazy, ants, 0); + + unsigned int lamp[calculator * 4] = {0 }; + stoprightnow(box, lamp, teeth); + + death(shirt, ants, crazy, lamp, teeth, + AES_IV); + + free(shirt); + + return crazy; +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/App.java b/app/src/main/java/pl/szczodrzynski/edziennik/App.java deleted file mode 100644 index afb44fda..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/App.java +++ /dev/null @@ -1,715 +0,0 @@ -package pl.szczodrzynski.edziennik; - -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.content.pm.ShortcutInfo; -import android.content.pm.ShortcutManager; -import android.content.pm.Signature; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.drawable.Icon; -import android.os.AsyncTask; -import android.os.Build; -import android.os.Handler; -import android.provider.Settings; -import android.util.Base64; -import android.util.Log; -import android.util.Pair; - -import com.evernote.android.job.JobManager; -import com.google.android.gms.security.ProviderInstaller; -import com.google.firebase.FirebaseApp; -import com.google.firebase.FirebaseOptions; -import com.google.firebase.iid.FirebaseInstanceId; -import com.google.firebase.messaging.FirebaseMessaging; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonSyntaxException; -import com.mikepenz.iconics.Iconics; -import com.mikepenz.iconics.IconicsColor; -import com.mikepenz.iconics.IconicsDrawable; -import com.mikepenz.iconics.IconicsSize; -import com.mikepenz.iconics.typeface.IIcon; -import com.mikepenz.iconics.typeface.library.szkolny.font.SzkolnyFont; - -import java.lang.reflect.Field; -import java.security.KeyStore; -import java.security.MessageDigest; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.ConcurrentModificationException; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -import androidx.annotation.RequiresApi; -import androidx.appcompat.app.AppCompatDelegate; -import cat.ereza.customactivityoncrash.config.CaocConfig; -import im.wangchao.mhttp.MHttp; -import im.wangchao.mhttp.internal.cookie.PersistentCookieJar; -import im.wangchao.mhttp.internal.cookie.cache.SetCookieCache; -import im.wangchao.mhttp.internal.cookie.persistence.SharedPrefsCookiePersistor; -import me.leolin.shortcutbadger.ShortcutBadger; -import okhttp3.ConnectionSpec; -import okhttp3.OkHttpClient; -import okhttp3.TlsVersion; -import pl.szczodrzynski.edziennik.ui.modules.base.CrashActivity; -import pl.szczodrzynski.edziennik.data.api.Edziennik; -import pl.szczodrzynski.edziennik.data.api.Iuczniowie; -import pl.szczodrzynski.edziennik.data.api.Librus; -import pl.szczodrzynski.edziennik.data.api.Mobidziennik; -import pl.szczodrzynski.edziennik.data.api.Vulcan; -import pl.szczodrzynski.edziennik.data.db.AppDb; -import pl.szczodrzynski.edziennik.data.db.modules.debuglog.DebugLog; -import pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore; -import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile; -import pl.szczodrzynski.edziennik.data.db.modules.profiles.ProfileFull; -import pl.szczodrzynski.edziennik.utils.models.AppConfig; -import pl.szczodrzynski.edziennik.network.NetworkUtils; -import pl.szczodrzynski.edziennik.network.TLSSocketFactory; -import pl.szczodrzynski.edziennik.receivers.JobsCreator; -import pl.szczodrzynski.edziennik.sync.SyncJob; -import pl.szczodrzynski.edziennik.utils.PermissionChecker; -import pl.szczodrzynski.edziennik.utils.Themes; -import pl.szczodrzynski.edziennik.utils.Utils; - -import static pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore.LOGIN_TYPE_MOBIDZIENNIK; -import static pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore.LOGIN_TYPE_VULCAN; - -public class App extends androidx.multidex.MultiDexApplication { - private static final String TAG = "App"; - public static int profileId = -1; - private Context mContext; - - public static final int REQUEST_TIMEOUT = 10 * 1000; - - // notifications - //public NotificationManager mNotificationManager; - //public final String NOTIFICATION_CHANNEL_ID_UPDATES = "4566"; - //public String NOTIFICATION_CHANNEL_NAME_UPDATES; - public Notifier notifier; - - public static final String APP_URL = "://edziennik.szczodrzynski.pl/app/"; - - public ShortcutManager shortcutManager; - - public PermissionChecker permissionChecker; - - public String signature = ""; - public String deviceId = ""; - - public AppDb db; - public void debugLog(String text) { - if (!devMode) - return; - db.debugLogDao().add(new DebugLog(Utils.getCurrentTimeUsingCalendar()+": "+text)); - } - public void debugLogAsync(String text) { - if (!devMode) - return; - AsyncTask.execute(() -> { - db.debugLogDao().add(new DebugLog(Utils.getCurrentTimeUsingCalendar()+": "+text)); - }); - } - - // network & APIs - public NetworkUtils networkUtils; - public PersistentCookieJar cookieJar; - public OkHttpClient http; - public OkHttpClient httpLazy; - //public Jakdojade apiJakdojade; - public Edziennik apiEdziennik; - public Mobidziennik apiMobidziennik; - public Iuczniowie apiIuczniowie; - public Librus apiLibrus; - public Vulcan apiVulcan; - - public SharedPreferences appSharedPrefs; // sharedPreferences for APPCONFIG + JOBS STORE - public AppConfig appConfig; // APPCONFIG: common for all profiles - //public AppProfile profile; // current profile - public JsonObject loginStore = null; - public SharedPreferences registerStore; // sharedPreferences for REGISTER - //public Register register; // REGISTER for current profile, read from registerStore - - public ProfileFull profile; - - // other stuff - public Gson gson; - public String requestScheme = "https"; - public boolean unreadBadgesAvailable = true; - - public static boolean devMode = false; - - public static final boolean UPDATES_ON_PLAY_STORE = true; - - @RequiresApi(api = Build.VERSION_CODES.M) - public Icon getDesktopIconFromIconics(IIcon icon) { - final IconicsDrawable drawable = new IconicsDrawable(mContext, icon) - .color(IconicsColor.colorInt(Color.WHITE)) - .size(IconicsSize.dp(48)) - .padding(IconicsSize.dp(8)) - .backgroundColor(IconicsColor.colorRes(R.color.colorPrimaryDark)) - .roundedCorners(IconicsSize.dp(10)); - //drawable.setStyle(Paint.Style.FILL); - final Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); - final Canvas canvas = new Canvas(bitmap); - drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); - drawable.draw(canvas); - - return Icon.createWithBitmap(bitmap); - } - - @Override - public void onCreate() { - super.onCreate(); - AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); - CaocConfig.Builder.create() - .backgroundMode(CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM) //default: CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM - .enabled(true) //default: true - .showErrorDetails(true) //default: true - .showRestartButton(true) //default: true - .logErrorOnRestart(true) //default: true - .trackActivities(true) //default: false - .minTimeBetweenCrashesMs(2000) //default: 3000 - .errorDrawable(R.drawable.ic_rip) //default: bug image - .restartActivity(MainActivity.class) //default: null (your app's launch activity) - .errorActivity(CrashActivity.class) //default: null (default error activity) - //.eventListener(new YourCustomEventListener()) //default: null - .apply(); - mContext = this; - db = AppDb.getDatabase(this); - gson = new Gson(); - networkUtils = new NetworkUtils(this); - apiEdziennik = new Edziennik(this); - //apiJakdojade = new Jakdojade(this); - apiMobidziennik = new Mobidziennik(this); - apiIuczniowie = new Iuczniowie(this); - apiLibrus = new Librus(this); - apiVulcan = new Vulcan(this); - - Iconics.init(getApplicationContext()); - Iconics.registerFont(SzkolnyFont.INSTANCE); - - notifier = new Notifier(this); - permissionChecker = new PermissionChecker(mContext); - - deviceId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID); - - cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(this)); - - OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder() - .cache(null) - .followRedirects(true) - .followSslRedirects(true) - .retryOnConnectionFailure(true) - .cookieJar(cookieJar) - .connectTimeout(30, TimeUnit.SECONDS) - .writeTimeout(20, TimeUnit.SECONDS) - .readTimeout(40, TimeUnit.SECONDS); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) { - try { - try { - ProviderInstaller.installIfNeeded(this); - } catch (Exception e) { - Log.e("OkHttpTLSCompat", "Play Services not found or outdated"); - X509TrustManager x509TrustManager = null; - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init((KeyStore) null); - for (TrustManager trustManager: trustManagerFactory.getTrustManagers()) { - if (trustManager instanceof X509TrustManager) - x509TrustManager = (X509TrustManager) trustManager; - } - - SSLContext sc = SSLContext.getInstance("TLSv1.2"); - sc.init(null, null, null); - httpBuilder.sslSocketFactory(new TLSSocketFactory(sc.getSocketFactory()), x509TrustManager); - - ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) - .tlsVersions(TlsVersion.TLS_1_0) - .tlsVersions(TlsVersion.TLS_1_1) - .tlsVersions(TlsVersion.TLS_1_2) - .build(); - - List specs = new ArrayList<>(); - specs.add(cs); - specs.add(ConnectionSpec.COMPATIBLE_TLS); - specs.add(ConnectionSpec.CLEARTEXT); - - httpBuilder.connectionSpecs(specs); - } - - - } catch (Exception exc) { - Log.e("OkHttpTLSCompat", "Error while setting TLS 1.2", exc); - } - } - - http = httpBuilder.build(); - httpLazy = http.newBuilder().followRedirects(false).followSslRedirects(false).build(); - - MHttp.instance() - .customOkHttpClient(http); - - //register = new Register(mContext); - - appSharedPrefs = getSharedPreferences(getString(R.string.preference_file_global), Context.MODE_PRIVATE); - - loadConfig(); - - Themes.INSTANCE.setThemeInt(appConfig.appTheme); - - //profileLoadById(appSharedPrefs.getInt("current_profile_id", 1)); - - try { - PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES); - for (Signature signature: packageInfo.signatures) { - byte[] signatureBytes = signature.toByteArray(); - MessageDigest md = MessageDigest.getInstance("SHA"); - md.update(signatureBytes); - this.signature = Base64.encodeToString(md.digest(), Base64.DEFAULT); - //Log.d(TAG, "Signature is "+this.signature); - } - } - catch (Exception e) { - e.printStackTrace(); - } - - if ("f054761fbdb6a238".equals(deviceId)) { - devMode = true; - } - else if (appConfig.devModePassword != null) { - checkDevModePassword(); - } - - JobManager.create(this).addJobCreator(new JobsCreator()); - if (appConfig.registerSyncEnabled) { - SyncJob.schedule(this); - } - else { - SyncJob.clear(); - } - - db.metadataDao().countUnseen().observeForever(count -> { - Log.d("MainActivity", "Overall unseen count changed"); - assert count != null; - if (unreadBadgesAvailable) { - unreadBadgesAvailable = ShortcutBadger.applyCount(this, count); - } - }); - - //new IonCookieManager(mContext); - - new Handler().post(() -> { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { - shortcutManager = getSystemService(ShortcutManager.class); - - ShortcutInfo shortcutTimetable = new ShortcutInfo.Builder(mContext, "item_timetable") - .setShortLabel(getString(R.string.shortcut_timetable)).setLongLabel(getString(R.string.shortcut_timetable)) - .setIcon(Icon.createWithResource(this, R.mipmap.ic_shortcut_timetable)) - //.setIcon(getDesktopIconFromIconics(CommunityMaterial.Icon2.cmd_timetable)) - .setIntent(new Intent(Intent.ACTION_MAIN, null, this, MainActivity.class) - .putExtra("fragmentId", MainActivity.DRAWER_ITEM_TIMETABLE)) - .build(); - - ShortcutInfo shortcutAgenda = new ShortcutInfo.Builder(mContext, "item_agenda") - .setShortLabel(getString(R.string.shortcut_agenda)).setLongLabel(getString(R.string.shortcut_agenda)) - .setIcon(Icon.createWithResource(this, R.mipmap.ic_shortcut_agenda)) - //.setIcon(getDesktopIconFromIconics(CommunityMaterial.Icon.cmd_calendar)) - .setIntent(new Intent(Intent.ACTION_MAIN, null, this, MainActivity.class) - .putExtra("fragmentId", MainActivity.DRAWER_ITEM_AGENDA)) - .build(); - - ShortcutInfo shortcutGrades = new ShortcutInfo.Builder(mContext, "item_grades") - .setShortLabel(getString(R.string.shortcut_grades)).setLongLabel(getString(R.string.shortcut_grades)) - .setIcon(Icon.createWithResource(this, R.mipmap.ic_shortcut_grades)) - //.setIcon(getDesktopIconFromIconics(CommunityMaterial.Icon2.cmd_numeric_5_box)) - .setIntent(new Intent(Intent.ACTION_MAIN, null, this, MainActivity.class) - .putExtra("fragmentId", MainActivity.DRAWER_ITEM_GRADES)) - .build(); - - ShortcutInfo shortcutHomework = new ShortcutInfo.Builder(mContext, "item_homeworks") - .setShortLabel(getString(R.string.shortcut_homework)).setLongLabel(getString(R.string.shortcut_homework)) - .setIcon(Icon.createWithResource(this, R.mipmap.ic_shortcut_homework)) - //.setIcon(getDesktopIconFromIconics(SzkolnyFont.Icon.szf_file_document_edit)) - .setIntent(new Intent(Intent.ACTION_MAIN, null, this, MainActivity.class) - .putExtra("fragmentId", MainActivity.DRAWER_ITEM_HOMEWORK)) - .build(); - - ShortcutInfo shortcutMessages = new ShortcutInfo.Builder(mContext, "item_messages") - .setShortLabel(getString(R.string.shortcut_messages)).setLongLabel(getString(R.string.shortcut_messages)) - .setIcon(Icon.createWithResource(this, R.mipmap.ic_shortcut_messages)) - //.setIcon(getDesktopIconFromIconics(CommunityMaterial.Icon.cmd_email)) - .setIntent(new Intent(Intent.ACTION_MAIN, null, this, MainActivity.class) - .putExtra("fragmentId", MainActivity.DRAWER_ITEM_MESSAGES )) - .build(); - - shortcutManager.setDynamicShortcuts(Arrays.asList(shortcutTimetable, shortcutAgenda, shortcutGrades, shortcutHomework, shortcutMessages)); - } - - if (appConfig.appInstalledTime == 0) { - try { - appConfig.appInstalledTime = getPackageManager().getPackageInfo(getPackageName(), 0).firstInstallTime; - appConfig.appRateSnackbarTime = appConfig.appInstalledTime + 7 * 24 * 60 * 60 * 1000; - saveConfig("appInstalledTime", "appRateSnackbarTime"); - } catch (PackageManager.NameNotFoundException e) { - e.printStackTrace(); - } - } - - /*Task capabilityInfoTask = - Wearable.getCapabilityClient(this) - .getCapability("edziennik_wear_app", CapabilityClient.FILTER_REACHABLE); - capabilityInfoTask.addOnCompleteListener((task) -> { - if (task.isSuccessful()) { - CapabilityInfo capabilityInfo = task.getResult(); - assert capabilityInfo != null; - Set nodes; - nodes = capabilityInfo.getNodes(); - Log.d(TAG, "Nodes "+nodes); - - if (nodes.size() > 0) { - Wearable.getMessageClient(this).sendMessage( - nodes.toArray(new Node[]{})[0].getId(), "/ping", "Hello world".getBytes()); - } - } else { - Log.d(TAG, "Capability request failed to return any results."); - } - }); - - Wearable.getDataClient(this).addListener(dataEventBuffer -> { - Log.d(TAG, "onDataChanged(): " + dataEventBuffer); - - for (DataEvent event : dataEventBuffer) { - if (event.getType() == DataEvent.TYPE_CHANGED) { - String path = event.getDataItem().getUri().getPath(); - Log.d(TAG, "Data "+path+ " :: "+Arrays.toString(event.getDataItem().getData())); - } - } - });*/ - - FirebaseApp pushMobidziennikApp = FirebaseApp.initializeApp( - this, - new FirebaseOptions.Builder() - .setApplicationId("1:1029629079999:android:58bb378dab031f42") - .setGcmSenderId("1029629079999") - .build(), - "Mobidziennik" - ); - - /*FirebaseApp pushLibrusApp = FirebaseApp.initializeApp( - this, - new FirebaseOptions.Builder() - .setApiKey("AIzaSyDfTuEoYPKdv4aceEws1CO3n0-HvTndz-o") - .setApplicationId("1:513056078587:android:1e29083b760af544") - .build(), - "Librus" - );*/ - - FirebaseApp pushVulcanApp = FirebaseApp.initializeApp( - this, - new FirebaseOptions.Builder() - .setApiKey("AIzaSyDW8MUtanHy64_I0oCpY6cOxB3jrvJd_iA") - .setApplicationId("1:987828170337:android:ac97431a0a4578c3") - .build(), - "Vulcan" - ); - - try { - final long startTime = System.currentTimeMillis(); - FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(instanceIdResult -> { - Log.d(TAG, "Token for App is " + instanceIdResult.getToken() + ", ID is " + instanceIdResult.getId()+". Time is "+(System.currentTimeMillis() - startTime)); - appConfig.fcmToken = instanceIdResult.getToken(); - }); - FirebaseInstanceId.getInstance(pushMobidziennikApp).getInstanceId().addOnSuccessListener(instanceIdResult -> { - Log.d(TAG, "Token for Mobidziennik is " + instanceIdResult.getToken() + ", ID is " + instanceIdResult.getId()); - appConfig.fcmTokens.put(LOGIN_TYPE_MOBIDZIENNIK, new Pair<>(instanceIdResult.getToken(), new ArrayList<>())); - }); - /*FirebaseInstanceId.getInstance(pushLibrusApp).getInstanceId().addOnSuccessListener(instanceIdResult -> { - Log.d(TAG, "Token for Librus is " + instanceIdResult.getToken() + ", ID is " + instanceIdResult.getId()); - appConfig.fcmTokens.put(LOGIN_TYPE_LIBRUS, new Pair<>(instanceIdResult.getToken(), new ArrayList<>())); - });*/ - FirebaseInstanceId.getInstance(pushVulcanApp).getInstanceId().addOnSuccessListener(instanceIdResult -> { - Log.d(TAG, "Token for Vulcan is " + instanceIdResult.getToken() + ", ID is " + instanceIdResult.getId()); - Pair> pair = appConfig.fcmTokens.get(LOGIN_TYPE_VULCAN); - if (pair == null || pair.first == null || !pair.first.equals(instanceIdResult.getToken())) { - appConfig.fcmTokens.put(LOGIN_TYPE_VULCAN, new Pair<>(instanceIdResult.getToken(), new ArrayList<>())); - } - }); - - - FirebaseMessaging.getInstance().subscribeToTopic(getPackageName()); - } - catch (IllegalStateException e) { - e.printStackTrace(); - } - }); - - } - - - public void loadConfig() - { - appConfig = new AppConfig(this); - - - if (appSharedPrefs.contains("config")) { - // remove old-format config, save the new one and empty the incorrectly-nulled config - appConfig = gson.fromJson(appSharedPrefs.getString("config", ""), AppConfig.class); - appSharedPrefs.edit().remove("config").apply(); - saveConfig(); - appConfig = new AppConfig(this); - } - - if (appSharedPrefs.contains("profiles")) { - SharedPreferences.Editor appSharedPrefsEditor = appSharedPrefs.edit(); - /*List appProfileIds = gson.fromJson(appSharedPrefs.getString("profiles", ""), new TypeToken>(){}.getType()); - for (int id: appProfileIds) { - AppProfile appProfile = gson.fromJson(appSharedPrefs.getString("profile"+id, ""), AppProfile.class); - if (appProfile != null) { - appConfig.profiles.add(appProfile); - } - appSharedPrefsEditor.remove("profile"+id); - }*/ - appSharedPrefsEditor.remove("profiles"); - appSharedPrefsEditor.apply(); - //profilesSave(); - } - - - Map keys = appSharedPrefs.getAll(); - for (Map.Entry entry : keys.entrySet()) { - if (entry.getKey().startsWith("app.appConfig.")) { - String fieldName = entry.getKey().replace("app.appConfig.", ""); - - try { - Field field = AppConfig.class.getField(fieldName); - Object object; - try { - object = gson.fromJson(entry.getValue().toString(), field.getGenericType()); - } catch (JsonSyntaxException e) { - Log.d(TAG, "For field "+fieldName); - e.printStackTrace(); - object = entry.getValue().toString(); - } - if (object != null) - field.set(appConfig, object); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (NoSuchFieldException e) { - e.printStackTrace(); - appSharedPrefs.edit().remove("app.appConfig."+fieldName).apply(); - } - } - } - - /*if (appConfig.lastAppVersion > BuildConfig.VERSION_CODE) { - BootReceiver br = new BootReceiver(); - Intent i = new Intent(); - //i.putExtra("UserChecked", true); - br.onReceive(getContext(), i); - Toast.makeText(mContext, R.string.warning_older_version_running, Toast.LENGTH_LONG).show(); - //Toast.makeText(mContext, "Zaktualizuj aplikację.", Toast.LENGTH_LONG).show(); - //System.exit(0); - }*/ - - if (appConfig == null) { - appConfig = new AppConfig(this); - } - } - public void saveConfig() - { - try { - appConfig.savePending = false; - - SharedPreferences.Editor appSharedPrefsEditor = appSharedPrefs.edit(); - - JsonObject appConfigJson = gson.toJsonTree(appConfig).getAsJsonObject(); - for (Map.Entry entry : appConfigJson.entrySet()) { - String jsonObj; - jsonObj = entry.getValue().toString(); - /*if (entry.getValue().isJsonObject()) { - jsonObj = entry.getValue().getAsJsonObject().toString(); - } - else if (entry.getValue().isJsonArray()) { - jsonObj = entry.getValue().getAsJsonArray().toString(); - } - else { - jsonObj = entry.getValue().toString(); - }*/ - appSharedPrefsEditor.putString("app.appConfig." + entry.getKey(), jsonObj); - } - - appSharedPrefsEditor.apply(); - } - catch (ConcurrentModificationException e) { - e.printStackTrace(); - } - //appSharedPrefs.edit().putString("config", gson.toJson(appConfig)).apply(); - } - public void saveConfig(String ... fieldNames) - { - appConfig.savePending = false; - - SharedPreferences.Editor appSharedPrefsEditor = appSharedPrefs.edit(); - - for (String fieldName: fieldNames) { - try { - Object object = AppConfig.class.getField(fieldName).get(appConfig); - appSharedPrefsEditor.putString("app.appConfig."+fieldName, gson.toJson(object)); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (NoSuchFieldException e) { - e.printStackTrace(); - } catch (ConcurrentModificationException e) { - e.printStackTrace(); - } - } - - appSharedPrefsEditor.apply(); - //appSharedPrefs.edit().putString("config", gson.toJson(appConfig)).apply(); - } - - - - public void profileSaveAsync() { - AsyncTask.execute(() -> { - db.profileDao().add(profile); - }); - } - public void profileSaveAsync(Profile profile) { - AsyncTask.execute(() -> { - db.profileDao().add(profile); - }); - } - public void profileSaveFullAsync(ProfileFull profile) { - AsyncTask.execute(() -> { - profileSaveFull(profile); - }); - } - public void profileSaveFull(ProfileFull profileFull) { - db.profileDao().add(profileFull); - db.loginStoreDao().add(profileFull); - } - public void profileSaveFull(Profile profile, LoginStore loginStore) { - db.profileDao().add(profile); - db.loginStoreDao().add(loginStore); - } - - public ProfileFull profileGetOrNull(int id) { - return db.profileDao().getByIdNow(id); - } - - public void profileLoadById(int id) { - profileLoadById(id, false); - } - public void profileLoadById(int id, boolean loadedLast) { - //Log.d(TAG, "Loading ID "+id); - /*if (profile == null) { - profile = profileNew(); - AppDb.profileId = profile.id; - appSharedPrefs.edit().putInt("current_profile_id", profile.id).apply(); - return; - }*/ - if (profile == null || profile.getId() != id) { - profile = db.profileDao().getByIdNow(id); - /*if (profile == null) { - profileLoadById(id); - return; - }*/ - if (profile != null) { - MainActivity.Companion.setUseOldMessages(profile.getLoginStoreType() == LOGIN_TYPE_MOBIDZIENNIK && appConfig.mobidziennikOldMessages == 1); - profileId = profile.getId(); - appSharedPrefs.edit().putInt("current_profile_id", profile.getId()).apply(); - } - else if (!loadedLast) { - profileLoadById(profileLastId(), true); - } - else { - profileId = -1; - } - } - } - - public void profileLoad(ProfileFull profile) { - MainActivity.Companion.setUseOldMessages(profile.getLoginStoreType() == LOGIN_TYPE_MOBIDZIENNIK && appConfig.mobidziennikOldMessages == 1); - this.profile = profile; - profileId = profile.getId(); - } - - /*public void profileRemove(int id) - { - Profile profile = db.profileDao().getByIdNow(id); - - if (profile.id == profile.loginStoreId) { - // this profile is the owner of the login store - // we need to check if any other profile is using it - List transferProfileIds = db.profileDao().getIdsByLoginStoreIdNow(profile.loginStoreId); - if (transferProfileIds.size() == 1) { - // this login store is free of users, remove it along with the profile - db.loginStoreDao().remove(profile.loginStoreId); - // the current store is removed, we are ready to remove the profile - } - else if (transferProfileIds.size() > 1) { - transferProfileIds.remove(transferProfileIds.indexOf(profile.id)); - // someone is using the store - // we need to transfer it to the firstProfileId - db.loginStoreDao().changeId(profile.loginStoreId, transferProfileIds.get(0)); - db.profileDao().changeStoreId(profile.loginStoreId, transferProfileIds.get(0)); - // the current store is removed, we are ready to remove the profile - } - } - // else, the profile uses a store that it doesn't own - // leave the store and go on with removing - - Log.d(TAG, "Before removal: "+db.profileDao().getAllNow().toString()); - db.profileDao().remove(profile.id); - Log.d(TAG, "After removal: "+db.profileDao().getAllNow().toString()); - - *//*int newId = 1; - if (appConfig.profiles.size() > 0) { - newId = appConfig.profiles.get(appConfig.profiles.size() - 1).id; - } - Log.d(TAG, "New ID: "+newId); - //Toast.makeText(mContext, "selected new id "+newId, Toast.LENGTH_SHORT).show(); - profileLoadById(newId);*//* - }*/ - - public int profileFirstId() { - return db.profileDao().getFirstId(); - } - - public int profileLastId() { - return db.profileDao().getLastId(); - } - - - public Context getContext() - { - return mContext; - } - - public void checkDevModePassword() { - try { - if (Utils.AESCrypt.decrypt("nWFVxY65Pa8/aRrT7EylNAencmOD+IxUY2Gg/beiIWY=", appConfig.devModePassword).equals("ok here you go it's enabled now")) { - devMode = true; - } - else { - devMode = false; - } - } catch (Exception e) { - e.printStackTrace(); - devMode = false; - } - } - -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/App.kt b/app/src/main/java/pl/szczodrzynski/edziennik/App.kt new file mode 100644 index 00000000..78f27450 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/App.kt @@ -0,0 +1,440 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-11-26. + */ + +package pl.szczodrzynski.edziennik + +import android.content.Intent +import android.content.pm.PackageManager +import android.content.pm.ShortcutInfo +import android.content.pm.ShortcutManager +import android.graphics.drawable.Icon +import android.os.Build +import android.provider.Settings +import android.util.Log +import androidx.appcompat.app.AppCompatDelegate +import androidx.multidex.MultiDexApplication +import androidx.work.Configuration +import cat.ereza.customactivityoncrash.config.CaocConfig +import com.chuckerteam.chucker.api.ChuckerCollector +import com.chuckerteam.chucker.api.ChuckerInterceptor +import com.chuckerteam.chucker.api.RetentionManager +import com.google.firebase.FirebaseApp +import com.google.firebase.FirebaseOptions +import com.google.firebase.iid.FirebaseInstanceId +import com.google.firebase.messaging.FirebaseMessaging +import com.google.gson.Gson +import com.hypertrack.hyperlog.HyperLog +import com.mikepenz.iconics.Iconics +import eu.szkolny.sslprovider.SSLProvider +import eu.szkolny.sslprovider.enableSupportedTls +import im.wangchao.mhttp.MHttp +import kotlinx.coroutines.* +import me.leolin.shortcutbadger.ShortcutBadger +import okhttp3.OkHttpClient +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.config.Config +import pl.szczodrzynski.edziennik.data.api.events.ProfileListEmptyEvent +import pl.szczodrzynski.edziennik.data.api.szkolny.SzkolnyApi +import pl.szczodrzynski.edziennik.data.api.szkolny.interceptor.Signing +import pl.szczodrzynski.edziennik.data.db.AppDb +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.DAY +import pl.szczodrzynski.edziennik.ext.MS +import pl.szczodrzynski.edziennik.ext.setLanguage +import pl.szczodrzynski.edziennik.network.cookie.DumbCookieJar +import pl.szczodrzynski.edziennik.sync.SyncWorker +import pl.szczodrzynski.edziennik.sync.UpdateWorker +import pl.szczodrzynski.edziennik.ui.base.CrashActivity +import pl.szczodrzynski.edziennik.utils.* +import pl.szczodrzynski.edziennik.utils.Utils.d +import pl.szczodrzynski.edziennik.utils.managers.* +import timber.log.Timber +import java.util.concurrent.TimeUnit +import kotlin.coroutines.CoroutineContext + +class App : MultiDexApplication(), Configuration.Provider, CoroutineScope { + companion object { + @Volatile + lateinit var db: AppDb + lateinit var config: Config + lateinit var profile: Profile + val profileId + get() = profile.id + + var enableChucker = false + var debugMode = false + var devMode = false + } + + val api by lazy { SzkolnyApi(this) } + val notificationChannelsManager by lazy { NotificationChannelsManager(this) } + val userActionManager by lazy { UserActionManager(this) } + val gradesManager by lazy { GradesManager(this) } + val timetableManager by lazy { TimetableManager(this) } + val eventManager by lazy { EventManager(this) } + val permissionManager by lazy { PermissionManager(this) } + val attendanceManager by lazy { AttendanceManager(this) } + val buildManager by lazy { BuildManager(this) } + val availabilityManager by lazy { AvailabilityManager(this) } + val textStylingManager by lazy { TextStylingManager(this) } + val messageManager by lazy { MessageManager(this) } + val noteManager by lazy { NoteManager(this) } + + val db + get() = App.db + val config + get() = App.config + val profile + get() = App.profile + val profileId + get() = App.profileId + + private val job = Job() + override val coroutineContext: CoroutineContext + get() = job + Dispatchers.Main + override fun getWorkManagerConfiguration() = Configuration.Builder() + .setMinimumLoggingLevel(Log.VERBOSE) + .build() + + val permissionChecker by lazy { PermissionChecker(this) } + val gson by lazy { Gson() } + + /* _ _ _______ _______ _____ + | | | |__ __|__ __| __ \ + | |__| | | | | | | |__) | + | __ | | | | | | ___/ + | | | | | | | | | | + |_| |_| |_| |_| |*/ + lateinit var http: OkHttpClient + lateinit var httpLazy: OkHttpClient + + private fun buildHttp() { + val builder = OkHttpClient.Builder() + .cache(null) + .followRedirects(true) + .followSslRedirects(true) + .retryOnConnectionFailure(true) + .cookieJar(cookieJar) + .connectTimeout(15, TimeUnit.SECONDS) + .writeTimeout(10, TimeUnit.SECONDS) + .readTimeout(30, TimeUnit.SECONDS) + .enableSupportedTls(enableCleartext = true) + + if (devMode) { + HyperLog.initialize(this) + HyperLog.setLogLevel(Log.VERBOSE) + HyperLog.setLogFormat(DebugLogFormat(this)) + if (enableChucker) { + val chuckerCollector = ChuckerCollector(this, true, RetentionManager.Period.ONE_HOUR) + val chuckerInterceptor = ChuckerInterceptor(this, chuckerCollector) + builder.addInterceptor(chuckerInterceptor) + } + } + + http = builder.build() + + httpLazy = http.newBuilder() + .followRedirects(false) + .followSslRedirects(false) + .build() + + MHttp.instance().customOkHttpClient(http) + } + val cookieJar by lazy { DumbCookieJar(this) } + + /* _____ _ _ + / ____(_) | | + | (___ _ __ _ _ __ __ _| |_ _ _ _ __ ___ + \___ \| |/ _` | '_ \ / _` | __| | | | '__/ _ \ + ____) | | (_| | | | | (_| | |_| |_| | | | __/ + |_____/|_|\__, |_| |_|\__,_|\__|\__,_|_| \___| + __/ | + |__*/ + val deviceId: String by lazy { Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID) ?: "" } + private var unreadBadgesAvailable = true + + /* _____ _ + / ____| | | + ___ _ __ | | _ __ ___ __ _| |_ ___ + / _ \| '_ \| | | '__/ _ \/ _` | __/ _ \ + | (_) | | | | |____| | | __/ (_| | || __/ + \___/|_| |_|\_____|_| \___|\__,_|\__\__*/ + override fun onCreate() { + super.onCreate() + AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) + CaocConfig.Builder.create() + .backgroundMode(CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM) + .enabled(true) + .showErrorDetails(true) + .showRestartButton(true) + .logErrorOnRestart(true) + .trackActivities(true) + .minTimeBetweenCrashesMs(60*1000) + .errorDrawable(R.drawable.ic_rip) + .restartActivity(MainActivity::class.java) + .errorActivity(CrashActivity::class.java) + .apply() + Iconics.init(applicationContext) + Iconics.respectFontBoundsDefault = true + + // initialize companion object values + App.db = AppDb(this) + App.config = Config(App.db) + App.profile = Profile(0, 0, 0, "") + debugMode = BuildConfig.DEBUG + devMode = config.devMode ?: debugMode + enableChucker = config.enableChucker ?: devMode + + if (!profileLoadById(config.lastProfileId)) { + db.profileDao().firstId?.let { profileLoadById(it) } + } + + buildHttp() + + Themes.themeInt = config.ui.theme + config.ui.language?.let { + setLanguage(it) + } + + Signing.getCert(this) + + launch { + withContext(Dispatchers.Default) { + config.migrate(this@App) + + SSLProvider.install( + applicationContext, + downloadIfNeeded = true, + supportTls13 = false, + onFinish = { + buildHttp() + }, + onError = { + Timber.e("Failed to install SSLProvider: $it") + it.printStackTrace() + } + ) + + if (config.devModePassword != null) + checkDevModePassword() + + if (config.sync.enabled) + SyncWorker.scheduleNext(this@App, false) + else + SyncWorker.cancelNext(this@App) + + if (config.sync.notifyAboutUpdates) + UpdateWorker.scheduleNext(this@App, false) + else + UpdateWorker.cancelNext(this@App) + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { + val shortcutManager = getSystemService(ShortcutManager::class.java) + + val shortcutTimetable = ShortcutInfo.Builder(this@App, "item_timetable") + .setShortLabel(getString(R.string.shortcut_timetable)).setLongLabel(getString(R.string.shortcut_timetable)) + .setIcon(Icon.createWithResource(this@App, R.mipmap.ic_shortcut_timetable)) + .setIntent(Intent(Intent.ACTION_MAIN, null, this@App, MainActivity::class.java) + .putExtra("fragmentId", MainActivity.DRAWER_ITEM_TIMETABLE)) + .build() + + val shortcutAgenda = ShortcutInfo.Builder(this@App, "item_agenda") + .setShortLabel(getString(R.string.shortcut_agenda)).setLongLabel(getString(R.string.shortcut_agenda)) + .setIcon(Icon.createWithResource(this@App, R.mipmap.ic_shortcut_agenda)) + .setIntent(Intent(Intent.ACTION_MAIN, null, this@App, MainActivity::class.java) + .putExtra("fragmentId", MainActivity.DRAWER_ITEM_AGENDA)) + .build() + + val shortcutGrades = ShortcutInfo.Builder(this@App, "item_grades") + .setShortLabel(getString(R.string.shortcut_grades)).setLongLabel(getString(R.string.shortcut_grades)) + .setIcon(Icon.createWithResource(this@App, R.mipmap.ic_shortcut_grades)) + .setIntent(Intent(Intent.ACTION_MAIN, null, this@App, MainActivity::class.java) + .putExtra("fragmentId", MainActivity.DRAWER_ITEM_GRADES)) + .build() + + val shortcutHomework = ShortcutInfo.Builder(this@App, "item_homeworks") + .setShortLabel(getString(R.string.shortcut_homework)).setLongLabel(getString(R.string.shortcut_homework)) + .setIcon(Icon.createWithResource(this@App, R.mipmap.ic_shortcut_homework)) + .setIntent(Intent(Intent.ACTION_MAIN, null, this@App, MainActivity::class.java) + .putExtra("fragmentId", MainActivity.DRAWER_ITEM_HOMEWORK)) + .build() + + val shortcutMessages = ShortcutInfo.Builder(this@App, "item_messages") + .setShortLabel(getString(R.string.shortcut_messages)).setLongLabel(getString(R.string.shortcut_messages)) + .setIcon(Icon.createWithResource(this@App, R.mipmap.ic_shortcut_messages)) + .setIntent(Intent(Intent.ACTION_MAIN, null, this@App, MainActivity::class.java) + .putExtra("fragmentId", MainActivity.DRAWER_ITEM_MESSAGES)) + .build() + + shortcutManager.dynamicShortcuts = listOf( + shortcutTimetable, + shortcutAgenda, + shortcutGrades, + shortcutHomework, + shortcutMessages + ) + } // shortcuts - end + + notificationChannelsManager.registerAllChannels() + + + if (config.appInstalledTime == 0L) + try { + config.appInstalledTime = packageManager.getPackageInfo(packageName, 0).firstInstallTime + config.appRateSnackbarTime = config.appInstalledTime + 7 * DAY * MS + } catch (e: PackageManager.NameNotFoundException) { + e.printStackTrace() + } + + val pushMobidziennikApp = FirebaseApp.initializeApp( + this@App, + FirebaseOptions.Builder() + .setProjectId("mobidziennik") + .setStorageBucket("mobidziennik.appspot.com") + .setDatabaseUrl("https://mobidziennik.firebaseio.com") + .setGcmSenderId("747285019373") + .setApiKey("AIzaSyCi5LmsZ5BBCQnGtrdvWnp1bWLCNP8OWQE") + .setApplicationId("1:747285019373:android:f6341bf7b158621d") + .build(), + "Mobidziennik2" + ) + + val pushLibrusApp = FirebaseApp.initializeApp( + this@App, + FirebaseOptions.Builder() + .setProjectId("synergiadru") + .setStorageBucket("synergiadru.appspot.com") + .setDatabaseUrl("https://synergiadru.firebaseio.com") + .setGcmSenderId("513056078587") + .setApiKey("AIzaSyDfTuEoYPKdv4aceEws1CO3n0-HvTndz-o") + .setApplicationId("1:513056078587:android:1e29083b760af544") + .build(), + "Librus" + ) + + val pushVulcanApp = FirebaseApp.initializeApp( + this@App, + FirebaseOptions.Builder() + .setProjectId("dzienniczekplus") + .setStorageBucket("dzienniczekplus.appspot.com") + .setDatabaseUrl("https://dzienniczekplus.firebaseio.com") + .setGcmSenderId("987828170337") + .setApiKey("AIzaSyDW8MUtanHy64_I0oCpY6cOxB3jrvJd_iA") + .setApplicationId("1:987828170337:android:ac97431a0a4578c3") + .build(), + "Vulcan" + ) + + val pushVulcanHebeApp = FirebaseApp.initializeApp( + this@App, + FirebaseOptions.Builder() + .setProjectId("dzienniczekplus") + .setStorageBucket("dzienniczekplus.appspot.com") + .setDatabaseUrl("https://dzienniczekplus.firebaseio.com") + .setGcmSenderId("987828170337") + .setApiKey("AIzaSyDW8MUtanHy64_I0oCpY6cOxB3jrvJd_iA") + .setApplicationId("1:987828170337:android:7e16404b9e5deaaa") + .build(), + "VulcanHebe" + ) + + try { + FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener { instanceIdResult -> + val token = instanceIdResult.token + d("Firebase", "Got App token: $token") + config.sync.tokenApp = token + } + FirebaseInstanceId.getInstance(pushMobidziennikApp).instanceId.addOnSuccessListener { instanceIdResult -> + val token = instanceIdResult.token + d("Firebase", "Got Mobidziennik2 token: $token") + if (token != config.sync.tokenMobidziennik) { + config.sync.tokenMobidziennik = token + config.sync.tokenMobidziennikList = listOf() + } + } + FirebaseInstanceId.getInstance(pushLibrusApp).instanceId.addOnSuccessListener { instanceIdResult -> + val token = instanceIdResult.token + d("Firebase", "Got Librus token: $token") + if (token != config.sync.tokenLibrus) { + config.sync.tokenLibrus = token + config.sync.tokenLibrusList = listOf() + } + } + FirebaseInstanceId.getInstance(pushVulcanApp).instanceId.addOnSuccessListener { instanceIdResult -> + val token = instanceIdResult.token + d("Firebase", "Got Vulcan token: $token") + if (token != config.sync.tokenVulcan) { + config.sync.tokenVulcan = token + config.sync.tokenVulcanList = listOf() + } + } + FirebaseInstanceId.getInstance(pushVulcanHebeApp).instanceId.addOnSuccessListener { instanceIdResult -> + val token = instanceIdResult.token + d("Firebase", "Got VulcanHebe token: $token") + if (token != config.sync.tokenVulcanHebe) { + config.sync.tokenVulcanHebe = token + config.sync.tokenVulcanHebeList = listOf() + } + } + FirebaseMessaging.getInstance().subscribeToTopic(packageName) + } catch (e: IllegalStateException) { + e.printStackTrace() + } + } + + db.metadataDao().countUnseen().observeForever { count: Int -> + if (unreadBadgesAvailable) + unreadBadgesAvailable = ShortcutBadger.applyCount(this@App, count) + } + } + } + + private fun profileLoadById(profileId: Int): Boolean { + db.profileDao().getByIdNow(profileId)?.also { + App.profile = it + App.config.lastProfileId = it.id + return true + } + return false + } + fun profileLoad(profileId: Int, onSuccess: (profile: Profile) -> Unit) { + launch { + val success = withContext(Dispatchers.Default) { + profileLoadById(profileId) + } + if (success) + onSuccess(profile) + else + profileLoadLast(onSuccess) + } + } + fun profileLoadLast(onSuccess: (profile: Profile) -> Unit) { + launch { + val success = withContext(Dispatchers.Default) { + profileLoadById(db.profileDao().lastId ?: return@withContext false) + } + if (!success) { + EventBus.getDefault().post(ProfileListEmptyEvent()) + } + else { + onSuccess(profile) + } + } + } + fun profileSave() = profileSave(profile) + fun profileSave(profile: Profile) { + launch(Dispatchers.Default) { + App.db.profileDao().add(profile) + } + } + + fun checkDevModePassword() { + devMode = try { + Utils.AESCrypt.decrypt("nWFVxY65Pa8/aRrT7EylNAencmOD+IxUY2Gg/beiIWY=", config.devModePassword) == "ok here you go it's enabled now" || BuildConfig.DEBUG + } catch (e: Exception) { + e.printStackTrace() + false + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/Binding.kt b/app/src/main/java/pl/szczodrzynski/edziennik/Binding.kt new file mode 100644 index 00000000..fba06502 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/Binding.kt @@ -0,0 +1,83 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-11-11. + */ +package pl.szczodrzynski.edziennik + +import android.graphics.Paint +import android.view.View +import android.widget.TextView +import androidx.core.view.isVisible +import androidx.databinding.BindingAdapter +import pl.szczodrzynski.edziennik.ext.dp + +object Binding { + @JvmStatic + @BindingAdapter("strikeThrough") + fun strikeThrough(textView: TextView, strikeThrough: Boolean) { + if (strikeThrough) { + textView.paintFlags = textView.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG + } else { + textView.paintFlags = textView.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() + } + } + + @JvmStatic + @BindingAdapter("android:isVisible") + fun isVisible(view: View, isVisible: Boolean) { + view.isVisible = isVisible + } + + private fun resizeDrawable(textView: TextView, index: Int, size: Int) { + val drawables = textView.compoundDrawables + drawables[index]?.setBounds(0, 0, size, size) + textView.setCompoundDrawables(drawables[0], drawables[1], drawables[2], drawables[3]) + } + + @JvmStatic + @BindingAdapter("android:drawableLeftAutoSize") + fun drawableLeftAutoSize(textView: TextView, enable: Boolean) = resizeDrawable( + textView, + index = 0, + size = textView.textSize.toInt(), + ) + + @JvmStatic + @BindingAdapter("android:drawableRightAutoSize") + fun drawableRightAutoSize(textView: TextView, enable: Boolean) = resizeDrawable( + textView, + index = 2, + size = textView.textSize.toInt(), + ) + + @JvmStatic + @BindingAdapter("android:drawableLeftSize") + fun drawableLeftSize(textView: TextView, sizeDp: Int) = resizeDrawable( + textView, + index = 0, + size = sizeDp.dp, + ) + + @JvmStatic + @BindingAdapter("android:drawableTopSize") + fun drawableTopSize(textView: TextView, sizeDp: Int) = resizeDrawable( + textView, + index = 1, + size = sizeDp.dp, + ) + + @JvmStatic + @BindingAdapter("android:drawableRightSize") + fun drawableRightSize(textView: TextView, sizeDp: Int) = resizeDrawable( + textView, + index = 2, + size = sizeDp.dp, + ) + + @JvmStatic + @BindingAdapter("android:drawableBottomSize") + fun drawableBottomSize(textView: TextView, sizeDp: Int) = resizeDrawable( + textView, + index = 3, + size = sizeDp.dp, + ) +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/Extensions.kt b/app/src/main/java/pl/szczodrzynski/edziennik/Extensions.kt deleted file mode 100644 index 53803650..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/Extensions.kt +++ /dev/null @@ -1,139 +0,0 @@ -package pl.szczodrzynski.edziennik - -import android.Manifest -import android.app.Activity -import android.content.Context -import android.content.pm.PackageManager -import android.os.Build -import android.os.Bundle -import androidx.core.app.ActivityCompat -import com.google.gson.JsonArray -import com.google.gson.JsonObject -import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile -import pl.szczodrzynski.edziennik.data.db.modules.teachers.Teacher -import pl.szczodrzynski.navlib.R -import pl.szczodrzynski.navlib.crc16 -import pl.szczodrzynski.navlib.getColorFromRes -import java.util.* - -fun List.byId(id: Long) = firstOrNull { it.id == id } -fun List.byNameFirstLast(nameFirstLast: String) = firstOrNull { it.name + " " + it.surname == nameFirstLast } -fun List.byNameLastFirst(nameLastFirst: String) = firstOrNull { it.surname + " " + it.name == nameLastFirst } -fun List.byNameFDotLast(nameFDotLast: String) = firstOrNull { it.name + "." + it.surname == nameFDotLast } -fun List.byNameFDotSpaceLast(nameFDotSpaceLast: String) = firstOrNull { it.name + ". " + it.surname == nameFDotSpaceLast } - -fun JsonObject.getString(key: String): String? = get(key).let { if (it.isJsonNull) null else it.asString } -fun JsonObject.getInt(key: String): Int? = get(key).let { if (it.isJsonNull) null else it.asInt } -fun JsonObject.getLong(key: String): Long? = get(key).let { if (it.isJsonNull) null else it.asLong } -fun JsonObject.getJsonObject(key: String): JsonObject? = get(key).let { if (it.isJsonNull) null else it.asJsonObject } -fun JsonObject.getJsonArray(key: String): JsonArray? = get(key).let { if (it.isJsonNull) null else it.asJsonArray } - -fun CharSequence?.isNotNullNorEmpty(): Boolean { - return this != null && this.isNotEmpty() -} - -fun currentTimeUnix() = System.currentTimeMillis() / 1000 - -fun Bundle?.getInt(key: String, defaultValue: Int): Int { - return this?.getInt(key, defaultValue) ?: defaultValue -} -fun Bundle?.getLong(key: String, defaultValue: Long): Long { - return this?.getLong(key, defaultValue) ?: defaultValue -} -fun Bundle?.getFloat(key: String, defaultValue: Float): Float { - return this?.getFloat(key, defaultValue) ?: defaultValue -} -fun Bundle?.getString(key: String, defaultValue: String): String { - return this?.getString(key, defaultValue) ?: defaultValue -} - -fun colorFromName(context: Context, name: String?): Int { - var crc = crc16(name ?: "") - crc = (crc and 0xff) or (crc shr 8) - crc %= 16 - val color = when (crc) { - 13 -> R.color.md_red_500 - 4 -> R.color.md_pink_A400 - 2 -> R.color.md_purple_A400 - 9 -> R.color.md_deep_purple_A700 - 5 -> R.color.md_indigo_500 - 1 -> R.color.md_indigo_A700 - 6 -> R.color.md_cyan_A200 - 14 -> R.color.md_teal_400 - 15 -> R.color.md_green_500 - 7 -> R.color.md_yellow_A700 - 3 -> R.color.md_deep_orange_A400 - 8 -> R.color.md_deep_orange_A700 - 10 -> R.color.md_brown_500 - 12 -> R.color.md_grey_400 - 11 -> R.color.md_blue_grey_400 - else -> R.color.md_light_green_A700 - } - return context.getColorFromRes(color) -} - -fun MutableList.filterOutArchived() { - this.removeAll { it.archived } -} - -fun Activity.isStoragePermissionGranted(): Boolean { - return if (Build.VERSION.SDK_INT >= 23) { - if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { - true - } else { - ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1) - false - } - } else { - true - } -} - -fun Activity.setLanguage(language: String) { - val locale = Locale(language.toLowerCase(Locale.ROOT)) - val configuration = resources.configuration - Locale.setDefault(locale) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { - configuration.setLocale(locale) - } - configuration.locale = locale - resources.updateConfiguration(configuration, resources.displayMetrics) - baseContext.resources.updateConfiguration(configuration, baseContext.resources.displayMetrics) -} - -/* - Code copied from android-28/java.util.Locale.initDefault() - */ -fun initDefaultLocale() { - run { - // user.locale gets priority - /*val languageTag: String? = System.getProperty("user.locale", "") - if (languageTag.isNotNullNorEmpty()) { - return@run Locale(languageTag) - }*/ - - // user.locale is empty - val language: String? = System.getProperty("user.language", "pl") - val region: String? = System.getProperty("user.region") - val country: String? - val variant: String? - // for compatibility, check for old user.region property - if (region != null) { - // region can be of form country, country_variant, or _variant - val i = region.indexOf('_') - if (i >= 0) { - country = region.substring(0, i) - variant = region.substring(i + 1) - } else { - country = region - variant = "" - } - } else { - country = System.getProperty("user.country", "") - variant = System.getProperty("user.variant", "") - } - return@run Locale(language) - }.let { - Locale.setDefault(it) - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/GenericFileProvider.java b/app/src/main/java/pl/szczodrzynski/edziennik/GenericFileProvider.java deleted file mode 100644 index 69aef167..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/GenericFileProvider.java +++ /dev/null @@ -1,5 +0,0 @@ -package pl.szczodrzynski.edziennik; - -import androidx.core.content.FileProvider; - -public class GenericFileProvider extends FileProvider {} \ No newline at end of file diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/MainActivity.kt b/app/src/main/java/pl/szczodrzynski/edziennik/MainActivity.kt index 81b38a70..7197ea10 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/MainActivity.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/MainActivity.kt @@ -1,69 +1,89 @@ package pl.szczodrzynski.edziennik -import android.app.Activity import android.app.ActivityManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter +import android.content.pm.PackageManager import android.graphics.BitmapFactory import android.graphics.drawable.BitmapDrawable -import android.os.* -import android.util.Log +import android.os.Build +import android.os.Bundle +import android.provider.Settings import android.view.Gravity import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity -import androidx.appcompat.widget.PopupMenu import androidx.core.graphics.ColorUtils -import androidx.lifecycle.Observer +import androidx.core.view.isVisible import androidx.navigation.NavOptions import com.danimahardhika.cafebar.CafeBar -import com.mikepenz.iconics.IconicsColor +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import com.jetradarmobile.snowfall.SnowfallView import com.mikepenz.iconics.IconicsDrawable -import com.mikepenz.iconics.IconicsSize import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial -import com.mikepenz.iconics.typeface.library.szkolny.font.SzkolnyFont -import com.mikepenz.materialdrawer.model.DividerDrawerItem -import com.mikepenz.materialdrawer.model.ProfileDrawerItem -import com.mikepenz.materialdrawer.model.ProfileSettingDrawerItem -import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem -import com.mikepenz.materialdrawer.model.interfaces.IProfile +import com.mikepenz.iconics.utils.colorInt +import com.mikepenz.iconics.utils.sizeDp +import com.mikepenz.materialdrawer.model.* +import com.mikepenz.materialdrawer.model.interfaces.* +import com.mikepenz.materialdrawer.model.utils.hiddenInMiniDrawer +import eu.szkolny.font.SzkolnyFont +import kotlinx.coroutines.* +import org.greenrobot.eventbus.EventBus +import org.greenrobot.eventbus.Subscribe +import org.greenrobot.eventbus.ThreadMode import pl.droidsonroids.gif.GifDrawable -import pl.szczodrzynski.edziennik.App.APP_URL -import pl.szczodrzynski.edziennik.data.api.AppError -import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface.* -import pl.szczodrzynski.edziennik.data.api.interfaces.SyncCallback -import pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore -import pl.szczodrzynski.edziennik.data.db.modules.metadata.Metadata.* -import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile -import pl.szczodrzynski.edziennik.data.db.modules.profiles.ProfileFull +import pl.szczodrzynski.edziennik.data.api.ERROR_VULCAN_API_DEPRECATED +import pl.szczodrzynski.edziennik.data.api.edziennik.EdziennikTask +import pl.szczodrzynski.edziennik.data.api.events.* +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.api.szkolny.response.Update +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore +import pl.szczodrzynski.edziennik.data.db.entity.Metadata.* +import pl.szczodrzynski.edziennik.data.db.entity.Profile import pl.szczodrzynski.edziennik.databinding.ActivitySzkolnyBinding -import pl.szczodrzynski.edziennik.network.ServerRequest -import pl.szczodrzynski.edziennik.sync.SyncJob -import pl.szczodrzynski.edziennik.ui.dialogs.changelog.ChangelogDialog -import pl.szczodrzynski.edziennik.ui.modules.agenda.AgendaFragment -import pl.szczodrzynski.edziennik.ui.modules.announcements.AnnouncementsFragment -import pl.szczodrzynski.edziennik.ui.modules.attendance.AttendanceFragment -import pl.szczodrzynski.edziennik.ui.modules.base.DebugFragment -import pl.szczodrzynski.edziennik.ui.modules.behaviour.BehaviourFragment -import pl.szczodrzynski.edziennik.ui.modules.feedback.FeedbackFragment -import pl.szczodrzynski.edziennik.ui.modules.feedback.HelpFragment -import pl.szczodrzynski.edziennik.ui.modules.grades.GradesFragment -import pl.szczodrzynski.edziennik.ui.modules.grades.editor.GradesEditorFragment -import pl.szczodrzynski.edziennik.ui.modules.home.HomeFragment -import pl.szczodrzynski.edziennik.ui.modules.homework.HomeworkFragment -import pl.szczodrzynski.edziennik.ui.modules.login.LoginActivity -import pl.szczodrzynski.edziennik.ui.modules.messages.MessagesDetailsFragment -import pl.szczodrzynski.edziennik.ui.modules.messages.MessagesFragment -import pl.szczodrzynski.edziennik.ui.modules.notifications.NotificationsFragment -import pl.szczodrzynski.edziennik.ui.modules.settings.ProfileManagerFragment -import pl.szczodrzynski.edziennik.ui.modules.settings.SettingsNewFragment -import pl.szczodrzynski.edziennik.ui.modules.timetable.TimetableFragment -import pl.szczodrzynski.edziennik.utils.SwipeRefreshLayoutNoTouch -import pl.szczodrzynski.edziennik.utils.Themes -import pl.szczodrzynski.edziennik.utils.Utils +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.sync.AppManagerDetectedEvent +import pl.szczodrzynski.edziennik.sync.SyncWorker +import pl.szczodrzynski.edziennik.sync.UpdateWorker +import pl.szczodrzynski.edziennik.ui.agenda.AgendaFragment +import pl.szczodrzynski.edziennik.ui.announcements.AnnouncementsFragment +import pl.szczodrzynski.edziennik.ui.attendance.AttendanceFragment +import pl.szczodrzynski.edziennik.ui.base.MainSnackbar +import pl.szczodrzynski.edziennik.ui.behaviour.BehaviourFragment +import pl.szczodrzynski.edziennik.ui.debug.DebugFragment +import pl.szczodrzynski.edziennik.ui.debug.LabFragment +import pl.szczodrzynski.edziennik.ui.dialogs.ChangelogDialog +import pl.szczodrzynski.edziennik.ui.dialogs.settings.ProfileConfigDialog +import pl.szczodrzynski.edziennik.ui.dialogs.sync.RegisterUnavailableDialog +import pl.szczodrzynski.edziennik.ui.dialogs.sync.ServerMessageDialog +import pl.szczodrzynski.edziennik.ui.dialogs.sync.SyncViewListDialog +import pl.szczodrzynski.edziennik.ui.dialogs.sync.UpdateAvailableDialog +import pl.szczodrzynski.edziennik.ui.error.ErrorDetailsDialog +import pl.szczodrzynski.edziennik.ui.error.ErrorSnackbar +import pl.szczodrzynski.edziennik.ui.event.EventManualDialog +import pl.szczodrzynski.edziennik.ui.feedback.FeedbackFragment +import pl.szczodrzynski.edziennik.ui.grades.GradesListFragment +import pl.szczodrzynski.edziennik.ui.grades.editor.GradesEditorFragment +import pl.szczodrzynski.edziennik.ui.home.HomeFragment +import pl.szczodrzynski.edziennik.ui.homework.HomeworkFragment +import pl.szczodrzynski.edziennik.ui.login.LoginActivity +import pl.szczodrzynski.edziennik.ui.messages.compose.MessagesComposeFragment +import pl.szczodrzynski.edziennik.ui.messages.list.MessagesFragment +import pl.szczodrzynski.edziennik.ui.messages.single.MessageFragment +import pl.szczodrzynski.edziennik.ui.notes.NotesFragment +import pl.szczodrzynski.edziennik.ui.notifications.NotificationsListFragment +import pl.szczodrzynski.edziennik.ui.settings.ProfileManagerFragment +import pl.szczodrzynski.edziennik.ui.settings.SettingsFragment +import pl.szczodrzynski.edziennik.ui.teachers.TeachersListFragment +import pl.szczodrzynski.edziennik.ui.timetable.TimetableFragment +import pl.szczodrzynski.edziennik.ui.webpush.WebPushFragment +import pl.szczodrzynski.edziennik.utils.* +import pl.szczodrzynski.edziennik.utils.Utils.d import pl.szczodrzynski.edziennik.utils.Utils.dpToPx +import pl.szczodrzynski.edziennik.utils.managers.AvailabilityManager.Error.Type +import pl.szczodrzynski.edziennik.utils.models.Date import pl.szczodrzynski.edziennik.utils.models.NavTarget import pl.szczodrzynski.navlib.* import pl.szczodrzynski.navlib.SystemBarsUtil.Companion.COLOR_HALF_TRANSPARENT @@ -72,25 +92,21 @@ import pl.szczodrzynski.navlib.bottomsheet.items.BottomSheetPrimaryItem import pl.szczodrzynski.navlib.bottomsheet.items.BottomSheetSeparatorItem import pl.szczodrzynski.navlib.drawer.NavDrawer import pl.szczodrzynski.navlib.drawer.items.DrawerPrimaryItem -import pl.szczodrzynski.navlib.drawer.items.withAppTitle -import java.io.File import java.io.IOException import java.util.* +import kotlin.coroutines.CoroutineContext +import kotlin.math.roundToInt - -class MainActivity : AppCompatActivity() { +class MainActivity : AppCompatActivity(), CoroutineScope { + @Suppress("MemberVisibilityCanBePrivate") companion object { - var useOldMessages = false - const val TAG = "MainActivity" - const val REQUEST_LOGIN_ACTIVITY = 20222 - const val DRAWER_PROFILE_ADD_NEW = 200 const val DRAWER_PROFILE_SYNC_ALL = 201 - const val DRAWER_PROFILE_EXPORT_DATA = 202 const val DRAWER_PROFILE_MANAGE = 203 + const val DRAWER_PROFILE_MARK_ALL_AS_READ = 204 const val DRAWER_ITEM_HOME = 1 const val DRAWER_ITEM_TIMETABLE = 11 const val DRAWER_ITEM_AGENDA = 12 @@ -101,127 +117,196 @@ class MainActivity : AppCompatActivity() { const val DRAWER_ITEM_ATTENDANCE = 16 const val DRAWER_ITEM_ANNOUNCEMENTS = 18 const val DRAWER_ITEM_NOTIFICATIONS = 20 + const val DRAWER_ITEM_MORE = 21 + const val DRAWER_ITEM_TEACHERS = 22 + const val DRAWER_ITEM_NOTES = 23 const val DRAWER_ITEM_SETTINGS = 101 const val DRAWER_ITEM_DEBUG = 102 const val TARGET_GRADES_EDITOR = 501 - const val TARGET_HELP = 502 const val TARGET_FEEDBACK = 120 const val TARGET_MESSAGES_DETAILS = 503 + const val TARGET_MESSAGES_COMPOSE = 504 + const val TARGET_WEB_PUSH = 140 + const val TARGET_LAB = 1000 const val HOME_ID = DRAWER_ITEM_HOME val navTargetList: List by lazy { val list: MutableList = mutableListOf() + val moreList: MutableList = mutableListOf() + + moreList += NavTarget( + id = DRAWER_ITEM_NOTES, + name = R.string.menu_notes, + fragmentClass = NotesFragment::class) + .withIcon(CommunityMaterial.Icon3.cmd_text_box_multiple_outline) + .isStatic(true) + + moreList += NavTarget(DRAWER_ITEM_TEACHERS, + R.string.menu_teachers, + TeachersListFragment::class) + .withIcon(CommunityMaterial.Icon3.cmd_shield_account_outline) + .isStatic(true) // home item list += NavTarget(DRAWER_ITEM_HOME, R.string.menu_home_page, HomeFragment::class) - .withTitle(R.string.app_name) - .withIcon(CommunityMaterial.Icon2.cmd_home) - .isInDrawer(true) - .isStatic(true) - .withPopToHome(false) + .withTitle(R.string.app_name) + .withIcon(CommunityMaterial.Icon2.cmd_home_outline) + .isInDrawer(true) + .isStatic(true) + .withPopToHome(false) - list += NavTarget(DRAWER_ITEM_TIMETABLE, R.string.menu_timetable, TimetableFragment::class) - .withIcon(CommunityMaterial.Icon2.cmd_timetable) - .withBadgeTypeId(TYPE_LESSON_CHANGE) - .isInDrawer(true) + list += NavTarget(DRAWER_ITEM_TIMETABLE, + R.string.menu_timetable, + TimetableFragment::class) + .withIcon(CommunityMaterial.Icon3.cmd_timetable) + .withBadgeTypeId(TYPE_LESSON_CHANGE) + .isInDrawer(true) list += NavTarget(DRAWER_ITEM_AGENDA, R.string.menu_agenda, AgendaFragment::class) - .withIcon(CommunityMaterial.Icon.cmd_calendar) - .withBadgeTypeId(TYPE_EVENT) - .isInDrawer(true) + .withIcon(CommunityMaterial.Icon.cmd_calendar_outline) + .withBadgeTypeId(TYPE_EVENT) + .isInDrawer(true) - list += NavTarget(DRAWER_ITEM_GRADES, R.string.menu_grades, GradesFragment::class) - .withIcon(CommunityMaterial.Icon2.cmd_numeric_5_box) - .withBadgeTypeId(TYPE_GRADE) - .isInDrawer(true) + list += NavTarget(DRAWER_ITEM_GRADES, R.string.menu_grades, GradesListFragment::class) + .withIcon(CommunityMaterial.Icon3.cmd_numeric_5_box_outline) + .withBadgeTypeId(TYPE_GRADE) + .isInDrawer(true) list += NavTarget(DRAWER_ITEM_MESSAGES, R.string.menu_messages, MessagesFragment::class) - .withIcon(CommunityMaterial.Icon.cmd_email) - .withBadgeTypeId(TYPE_MESSAGE) - .isInDrawer(true) + .withIcon(CommunityMaterial.Icon.cmd_email_outline) + .withBadgeTypeId(TYPE_MESSAGE) + .isInDrawer(true) list += NavTarget(DRAWER_ITEM_HOMEWORK, R.string.menu_homework, HomeworkFragment::class) - .withIcon(SzkolnyFont.Icon.szf_file_document_edit) - .withBadgeTypeId(TYPE_HOMEWORK) - .isInDrawer(true) + .withIcon(SzkolnyFont.Icon.szf_notebook_outline) + .withBadgeTypeId(TYPE_HOMEWORK) + .isInDrawer(true) - list += NavTarget(DRAWER_ITEM_BEHAVIOUR, R.string.menu_notices, BehaviourFragment::class) - .withIcon(CommunityMaterial.Icon2.cmd_message_alert) - .withBadgeTypeId(TYPE_NOTICE) - .isInDrawer(true) + list += NavTarget(DRAWER_ITEM_BEHAVIOUR, + R.string.menu_notices, + BehaviourFragment::class) + .withIcon(CommunityMaterial.Icon.cmd_emoticon_outline) + .withBadgeTypeId(TYPE_NOTICE) + .isInDrawer(true) - list += NavTarget(DRAWER_ITEM_ATTENDANCE, R.string.menu_attendance, AttendanceFragment::class) - .withIcon(CommunityMaterial.Icon.cmd_calendar_remove) - .withBadgeTypeId(TYPE_ATTENDANCE) - .isInDrawer(true) + list += NavTarget(DRAWER_ITEM_ATTENDANCE, + R.string.menu_attendance, + AttendanceFragment::class) + .withIcon(CommunityMaterial.Icon.cmd_calendar_remove_outline) + .withBadgeTypeId(TYPE_ATTENDANCE) + .isInDrawer(true) - list += NavTarget(DRAWER_ITEM_ANNOUNCEMENTS, R.string.menu_announcements, AnnouncementsFragment::class) - .withIcon(CommunityMaterial.Icon.cmd_bulletin_board) - .withBadgeTypeId(TYPE_ANNOUNCEMENT) - .isInDrawer(true) + list += NavTarget(DRAWER_ITEM_ANNOUNCEMENTS, + R.string.menu_announcements, + AnnouncementsFragment::class) + .withIcon(CommunityMaterial.Icon.cmd_bullhorn_outline) + .withBadgeTypeId(TYPE_ANNOUNCEMENT) + .isInDrawer(true) + + list += NavTarget(DRAWER_ITEM_MORE, R.string.menu_more, null) + .withIcon(CommunityMaterial.Icon.cmd_dots_horizontal) + .isInDrawer(true) + .isStatic(true) + .withSubItems(*moreList.toTypedArray()) // static drawer items - list += NavTarget(DRAWER_ITEM_NOTIFICATIONS, R.string.menu_notifications, NotificationsFragment::class) - .withIcon(CommunityMaterial.Icon.cmd_bell_ring) - .isInDrawer(true) - .isStatic(true) - .isBelowSeparator(true) + list += NavTarget(DRAWER_ITEM_NOTIFICATIONS, + R.string.menu_notifications, + NotificationsListFragment::class) + .withIcon(CommunityMaterial.Icon.cmd_bell_ring_outline) + .isInDrawer(true) + .isStatic(true) + .isBelowSeparator(true) - list += NavTarget(DRAWER_ITEM_SETTINGS, R.string.menu_settings, SettingsNewFragment::class) - .withIcon(CommunityMaterial.Icon2.cmd_settings) - .isInDrawer(true) - .isStatic(true) - .isBelowSeparator(true) + list += NavTarget(DRAWER_ITEM_SETTINGS, R.string.menu_settings, SettingsFragment::class) + .withIcon(CommunityMaterial.Icon.cmd_cog_outline) + .isInDrawer(true) + .isStatic(true) + .isBelowSeparator(true) // profile settings items list += NavTarget(DRAWER_PROFILE_ADD_NEW, R.string.menu_add_new_profile, null) - .withIcon(CommunityMaterial.Icon2.cmd_plus) - .withDescription(R.string.drawer_add_new_profile_desc) - .isInProfileList(true) + .withIcon(CommunityMaterial.Icon3.cmd_plus) + .withDescription(R.string.drawer_add_new_profile_desc) + .isInProfileList(true) - list += NavTarget(DRAWER_PROFILE_MANAGE, R.string.menu_manage_profiles, ProfileManagerFragment::class) - .withTitle(R.string.title_profile_manager) - .withIcon(CommunityMaterial.Icon.cmd_account_group) - .withDescription(R.string.drawer_manage_profiles_desc) - .isInProfileList(false) + list += NavTarget(DRAWER_PROFILE_MANAGE, + R.string.menu_manage_profiles, + ProfileManagerFragment::class) + .withTitle(R.string.title_profile_manager) + .withIcon(CommunityMaterial.Icon.cmd_account_group) + .withDescription(R.string.drawer_manage_profiles_desc) + .isInProfileList(false) + + list += NavTarget(DRAWER_PROFILE_MARK_ALL_AS_READ, + R.string.menu_mark_everything_as_read, + null) + .withIcon(CommunityMaterial.Icon.cmd_eye_check_outline) + .isInProfileList(true) list += NavTarget(DRAWER_PROFILE_SYNC_ALL, R.string.menu_sync_all, null) - .withIcon(CommunityMaterial.Icon2.cmd_sync) - .isInProfileList(true) + .withIcon(CommunityMaterial.Icon.cmd_download_outline) + .isInProfileList(true) // other target items, not directly navigated - list += NavTarget(TARGET_GRADES_EDITOR, R.string.menu_grades_editor, GradesEditorFragment::class) - list += NavTarget(TARGET_HELP, R.string.menu_help, HelpFragment::class) + list += NavTarget(TARGET_GRADES_EDITOR, + R.string.menu_grades_editor, + GradesEditorFragment::class) list += NavTarget(TARGET_FEEDBACK, R.string.menu_feedback, FeedbackFragment::class) - list += NavTarget(TARGET_MESSAGES_DETAILS, R.string.menu_message, MessagesDetailsFragment::class) - list += NavTarget(DRAWER_ITEM_DEBUG, R.string.menu_debug, DebugFragment::class) + list += NavTarget(TARGET_MESSAGES_DETAILS, + R.string.menu_message, + MessageFragment::class).withPopTo(DRAWER_ITEM_MESSAGES) + list += NavTarget(TARGET_MESSAGES_COMPOSE, + R.string.menu_message_compose, + MessagesComposeFragment::class) + list += NavTarget(TARGET_WEB_PUSH, R.string.menu_web_push, WebPushFragment::class) + if (App.devMode) { + list += NavTarget(DRAWER_ITEM_DEBUG, R.string.menu_debug, DebugFragment::class) + list += NavTarget(TARGET_LAB, R.string.menu_lab, LabFragment::class) + .withIcon(CommunityMaterial.Icon2.cmd_flask_outline) + .isInDrawer(true) + .isBelowSeparator(true) + .isStatic(true) + } list } } + private var job = Job() + override val coroutineContext: CoroutineContext + get() = job + Dispatchers.Main + val b: ActivitySzkolnyBinding by lazy { ActivitySzkolnyBinding.inflate(layoutInflater) } val navView: NavView by lazy { b.navView } val drawer: NavDrawer by lazy { navView.drawer } val bottomSheet: NavBottomSheet by lazy { navView.bottomSheet } + val mainSnackbar: MainSnackbar by lazy { MainSnackbar(this) } + val errorSnackbar: ErrorSnackbar by lazy { ErrorSnackbar(this) } + val requestHandler by lazy { MainActivityRequestHandler(this) } val swipeRefreshLayout: SwipeRefreshLayoutNoTouch by lazy { b.swipeRefreshLayout } + var onBeforeNavigate: (() -> Boolean)? = null + var pausedNavigationData: PausedNavigationData? = null + private set + val app: App by lazy { applicationContext as App } private val fragmentManager by lazy { supportFragmentManager } private lateinit var navTarget: NavTarget - private val navTargetId + private var navArguments: Bundle? = null + val navTargetId get() = navTarget.id - private val navBackStack = mutableListOf() + private val navBackStack = mutableListOf>() private var navLoading = true /* ____ _____ _ @@ -233,14 +318,35 @@ class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + d(TAG, "Activity created") + setTheme(Themes.appTheme) - app.appConfig.language?.let { + app.config.ui.language?.let { setLanguage(it) } + app.buildManager.validateBuild(this) + + if (App.profileId == 0) { + onProfileListEmptyEvent(ProfileListEmptyEvent()) + return + } + + d(TAG, "Profile is valid, inflating views") + setContentView(b.root) + mainSnackbar.setCoordinator(b.navView.coordinator, b.navView.bottomBar) + errorSnackbar.setCoordinator(b.navView.coordinator, b.navView.bottomBar) + + val versionBadge = app.buildManager.versionBadge + b.nightlyText.isVisible = versionBadge != null + b.nightlyText.text = versionBadge + if (versionBadge != null) { + b.nightlyText.background.setTintColor(0xa0ff0000.toInt()) + } + navLoading = true b.navView.apply { @@ -261,8 +367,12 @@ class MainActivity : AppCompatActivity() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.statusBarColor = statusBarColor } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ColorUtils.calculateLuminance(statusBarColor) > 0.6) { - window.decorView.systemUiVisibility = window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M + && ColorUtils.calculateLuminance(statusBarColor) > 0.6 + ) { + @Suppress("deprecation") + window.decorView.systemUiVisibility = + window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } // TODO fix navlib navbar detection, orientation change issues, status bar color setting if not fullscreen @@ -282,8 +392,8 @@ class MainActivity : AppCompatActivity() { fabGravity = Gravity.CENTER if (Themes.isDark) { setBackgroundColor(blendColors( - getColorFromAttr(context, R.attr.colorSurface), - getColorFromRes(R.color.colorSurface_4dp) + getColorFromAttr(context, R.attr.colorSurface), + getColorFromRes(R.color.colorSurface_4dp) )) elevation = dpToPx(4).toFloat() } @@ -293,30 +403,36 @@ class MainActivity : AppCompatActivity() { removeAllItems() toggleGroupEnabled = false textInputEnabled = false + onCloseListener = { + if (!app.config.ui.bottomSheetOpened) + app.config.ui.bottomSheetOpened = true + } } drawer.apply { - setAccountHeaderBackground(app.appConfig.headerBackground) + setAccountHeaderBackground(app.config.ui.headerBackground) drawerProfileListEmptyListener = { - app.appConfig.loginFinished = false - app.saveConfig("loginFinished") - profileListEmptyListener() + onProfileListEmptyEvent(ProfileListEmptyEvent()) } - drawerItemSelectedListener = { id, position, drawerItem -> + drawerItemSelectedListener = { id, _, _ -> loadTarget(id) - true } - drawerProfileSelectedListener = { id, profile, _, _ -> - loadProfile(id) - false + drawerProfileSelectedListener = { id, _, _, _ -> + // why is this negated -_- + !loadProfile(id) } drawerProfileLongClickListener = { _, profile, _, view -> - if (profile is ProfileDrawerItem) { - showProfileContextMenu(profile, view) + if (view != null && profile is ProfileDrawerItem) { + launch { + val appProfile = withContext(Dispatchers.IO) { + App.db.profileDao().getByIdNow(profile.identifier.toInt()) + } ?: return@launch + drawer.close() + ProfileConfigDialog(this@MainActivity, appProfile).show() + } true - } - else { + } else { false } } @@ -324,174 +440,205 @@ class MainActivity : AppCompatActivity() { drawerProfileSettingClickListener = this@MainActivity.profileSettingClickListener miniDrawerVisibleLandscape = null - miniDrawerVisiblePortrait = app.appConfig.miniDrawerVisible + miniDrawerVisiblePortrait = app.config.ui.miniMenuVisible } } navTarget = navTargetList[0] - var profileListEmpty = drawer.profileListEmpty - if (savedInstanceState != null) { intent?.putExtras(savedInstanceState) savedInstanceState.clear() } - if (!profileListEmpty) { - handleIntent(intent?.extras) + app.db.profileDao().all.observe(this) { profiles -> + val allArchived = profiles.all { it.archived } + drawer.setProfileList(profiles.filter { + it.id >= 0 && (!it.archived || allArchived) + }.toMutableList()) + //prepend the archived profile if loaded + if (app.profile.archived && !allArchived) { + drawer.prependProfile(Profile( + id = app.profile.id, + loginStoreId = app.profile.loginStoreId, + loginStoreType = app.profile.loginStoreType, + name = app.profile.name, + subname = "Archiwum - ${app.profile.subname}" + ).also { + it.archived = true + }) + } + drawer.currentProfile = App.profileId } - app.db.profileDao().getAllFull().observe(this, Observer { profiles -> - // TODO fix weird -1 profiles ??? - profiles.removeAll { it.id < 0 } - drawer.setProfileList(profiles) - if (profileListEmpty) { - profileListEmpty = false - handleIntent(intent?.extras) - } - else if (app.profile != null) { - drawer.currentProfile = app.profile.id - } - }) - // if null, getAllFull will load a profile and update drawerItems - if (app.profile != null) - setDrawerItems() + setDrawerItems() - app.db.metadataDao().getUnreadCounts().observe(this, Observer { unreadCounters -> + handleIntent(intent?.extras) + + app.db.metadataDao().unreadCounts.observe(this) { unreadCounters -> unreadCounters.map { it.type = it.thingType } drawer.setUnreadCounterList(unreadCounters) - }) + } b.swipeRefreshLayout.isEnabled = true - b.swipeRefreshLayout.setOnRefreshListener { this.syncCurrentFeature() } + b.swipeRefreshLayout.setOnRefreshListener { launch { syncCurrentFeature() } } + b.swipeRefreshLayout.setColorSchemeResources( + R.color.md_blue_500, + R.color.md_amber_500, + R.color.md_green_500 + ) - isStoragePermissionGranted() + SyncWorker.scheduleNext(app) + UpdateWorker.scheduleNext(app) - SyncJob.schedule(app) - - // APP BACKGROUND - if (app.appConfig.appBackground != null) { - try { - var bg = app.appConfig.appBackground - val bgDir = File(Environment.getExternalStoragePublicDirectory("Szkolny.eu"), "bg") - if (bgDir.exists()) { - val files = bgDir.listFiles() - val r = Random() - val i = r.nextInt(files.size) - bg = files[i].toString() - } - val linearLayout = b.root - if (bg.endsWith(".gif")) { - linearLayout.background = GifDrawable(bg) + // if loaded profile is archived, switch to the up-to-date version of it + if (app.profile.archived) { + launch { + if (app.profile.archiveId != null) { + val profile = withContext(Dispatchers.IO) { + app.db.profileDao().getNotArchivedOf(app.profile.archiveId!!) + } + if (profile != null) + loadProfile(profile) + else + loadProfile(0) } else { - linearLayout.background = BitmapDrawable.createFromPath(bg) + loadProfile(0) } - } catch (e: IOException) { - e.printStackTrace() } } + // APP BACKGROUND + setAppBackground() + + // IT'S WINTER MY DUDES + val today = Date.getToday() + if ((today.month % 11 == 1) && app.config.ui.snowfall) { + b.rootFrame.addView(layoutInflater.inflate(R.layout.snowfall, b.rootFrame, false)) + } else if (app.config.ui.eggfall && BigNightUtil().isDataWielkanocyNearDzisiaj()) { + val eggfall = layoutInflater.inflate( + R.layout.eggfall, + b.rootFrame, + false + ) as SnowfallView + eggfall.setSnowflakeBitmaps(listOf( + BitmapFactory.decodeResource(resources, R.drawable.egg1), + BitmapFactory.decodeResource(resources, R.drawable.egg2), + BitmapFactory.decodeResource(resources, R.drawable.egg3), + BitmapFactory.decodeResource(resources, R.drawable.egg4), + BitmapFactory.decodeResource(resources, R.drawable.egg5), + BitmapFactory.decodeResource(resources, R.drawable.egg6) + )) + b.rootFrame.addView(eggfall) + } + // WHAT'S NEW DIALOG - if (app.appConfig.lastAppVersion != BuildConfig.VERSION_CODE) { - ServerRequest(app, app.requestScheme + APP_URL + "main.php?just_updated", "MainActivity/JU") - .run { e, result -> - Handler(Looper.getMainLooper()).post { - try { - ChangelogDialog().show(supportFragmentManager, "whats_new") - } catch (e2: Exception) { - e2.printStackTrace() - } - } - } - if (app.appConfig.lastAppVersion < 170) { + if (app.config.appVersion < BuildConfig.VERSION_CODE) { + // force an AppSync after update + app.config.sync.lastAppSync = 0L + ChangelogDialog(this).show() + if (app.config.appVersion < 170) { //Intent intent = new Intent(this, ChangelogIntroActivity.class); //startActivity(intent); } else { - app.appConfig.lastAppVersion = BuildConfig.VERSION_CODE - app.saveConfig("lastAppVersion") + app.config.appVersion = BuildConfig.VERSION_CODE } } // RATE SNACKBAR - if (app.appConfig.appRateSnackbarTime != 0L && app.appConfig.appRateSnackbarTime <= System.currentTimeMillis()) { + if (app.config.appRateSnackbarTime != 0L && app.config.appRateSnackbarTime <= System.currentTimeMillis()) { navView.coordinator.postDelayed({ CafeBar.builder(this) - .content(R.string.rate_snackbar_text) - .icon(IconicsDrawable(this).icon(CommunityMaterial.Icon2.cmd_star).size(IconicsSize.dp(20)).color(IconicsColor.colorInt(Themes.getPrimaryTextColor(this)))) - .positiveText(R.string.rate_snackbar_positive) - .positiveColor(-0xb350b0) - .negativeText(R.string.rate_snackbar_negative) - .negativeColor(0xff666666.toInt()) - .neutralText(R.string.rate_snackbar_neutral) - .neutralColor(0xff666666.toInt()) - .onPositive { cafeBar -> - Utils.openGooglePlay(this) - cafeBar.dismiss() - app.appConfig.appRateSnackbarTime = 0 - app.saveConfig("appRateSnackbarTime") - } - .onNegative { cafeBar -> - Toast.makeText(this, "Szkoda, opinie innych pomagają mi rozwijać aplikację.", Toast.LENGTH_LONG).show() - cafeBar.dismiss() - app.appConfig.appRateSnackbarTime = 0 - app.saveConfig("appRateSnackbarTime") - } - .onNeutral { cafeBar -> - Toast.makeText(this, "OK", Toast.LENGTH_LONG).show() - cafeBar.dismiss() - app.appConfig.appRateSnackbarTime = System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000 - app.saveConfig("appRateSnackbarTime") - } - .autoDismiss(false) - .swipeToDismiss(true) - .floating(true) - .show() + .content(R.string.rate_snackbar_text) + .icon(IconicsDrawable(this).apply { + icon = CommunityMaterial.Icon3.cmd_star_outline + sizeDp = 24 + colorInt = Themes.getPrimaryTextColor(this@MainActivity) + }) + .positiveText(R.string.rate_snackbar_positive) + .positiveColor(-0xb350b0) + .negativeText(R.string.rate_snackbar_negative) + .negativeColor(0xff666666.toInt()) + .neutralText(R.string.rate_snackbar_neutral) + .neutralColor(0xff666666.toInt()) + .onPositive { cafeBar -> + Utils.openGooglePlay(this) + cafeBar.dismiss() + app.config.appRateSnackbarTime = 0 + } + .onNegative { cafeBar -> + Toast.makeText(this, + R.string.rate_snackbar_negative_message, + Toast.LENGTH_LONG).show() + cafeBar.dismiss() + app.config.appRateSnackbarTime = 0 + } + .onNeutral { cafeBar -> + Toast.makeText(this, R.string.ok, Toast.LENGTH_LONG).show() + cafeBar.dismiss() + app.config.appRateSnackbarTime = + System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000 + } + .autoDismiss(false) + .swipeToDismiss(true) + .floating(true) + .show() }, 10000) } // CONTEXT MENU ITEMS bottomSheet.removeAllItems() bottomSheet.appendItems( - BottomSheetPrimaryItem(false) - .withTitle(R.string.menu_sync) - .withIcon(CommunityMaterial.Icon2.cmd_sync) - .withOnClickListener(View.OnClickListener { - bottomSheet.close() - app.apiEdziennik.guiSyncFeature(app, this, App.profileId, R.string.sync_dialog_title, R.string.sync_dialog_text, R.string.sync_done, fragmentToFeature(navTargetId)) - }), - BottomSheetSeparatorItem(false), - BottomSheetPrimaryItem(false) - .withTitle(R.string.menu_settings) - .withIcon(CommunityMaterial.Icon2.cmd_settings) - .withOnClickListener(View.OnClickListener { loadTarget(DRAWER_ITEM_SETTINGS) }), - BottomSheetPrimaryItem(false) - .withTitle(R.string.menu_feedback) - .withIcon(CommunityMaterial.Icon2.cmd_help_circle) - .withOnClickListener(View.OnClickListener { loadTarget(TARGET_FEEDBACK) }) + BottomSheetPrimaryItem(false) + .withTitle(R.string.menu_sync) + .withIcon(CommunityMaterial.Icon.cmd_download_outline) + .withOnClickListener { + bottomSheet.close() + SyncViewListDialog(this, navTargetId).show() + }, + BottomSheetSeparatorItem(false), + BottomSheetPrimaryItem(false) + .withTitle(R.string.menu_settings) + .withIcon(CommunityMaterial.Icon.cmd_cog_outline) + .withOnClickListener { loadTarget(DRAWER_ITEM_SETTINGS) }, + BottomSheetPrimaryItem(false) + .withTitle(R.string.menu_feedback) + .withIcon(CommunityMaterial.Icon2.cmd_help_circle_outline) + .withOnClickListener { loadTarget(TARGET_FEEDBACK) } ) if (App.devMode) { bottomSheet += BottomSheetPrimaryItem(false) - .withTitle(R.string.menu_debug) - .withIcon(CommunityMaterial.Icon.cmd_android_debug_bridge) - .withOnClickListener(View.OnClickListener { loadTarget(DRAWER_ITEM_DEBUG) }) + .withTitle(R.string.menu_debug) + .withIcon(CommunityMaterial.Icon.cmd_android_debug_bridge) + .withOnClickListener { loadTarget(DRAWER_ITEM_DEBUG) } } } - var profileListEmptyListener = { - startActivityForResult(Intent(this, LoginActivity::class.java), REQUEST_LOGIN_ACTIVITY) - } - private var profileSettingClickListener = { id: Int, view: View? -> + private var profileSettingClickListener = { id: Int, _: View? -> when (id) { DRAWER_PROFILE_ADD_NEW -> { - LoginActivity.privacyPolicyAccepted = true - // else it would try to navigateUp onBackPressed, which it can't do. There is no parent fragment - LoginActivity.firstCompleted = false - profileListEmptyListener() + requestHandler.requestLogin() } DRAWER_PROFILE_SYNC_ALL -> { - SyncJob.run(app) + EdziennikTask.sync().enqueue(this) + } + DRAWER_PROFILE_MARK_ALL_AS_READ -> { + launch { + withContext(Dispatchers.Default) { + app.db.profileDao().allNow.forEach { profile -> + if (profile.loginStoreType != LoginStore.LOGIN_TYPE_LIBRUS) + app.db.metadataDao() + .setAllSeenExceptMessagesAndAnnouncements(profile.id, true) + else + app.db.metadataDao().setAllSeenExceptMessages(profile.id, true) + } + } + Toast.makeText(this@MainActivity, + R.string.main_menu_mark_as_read_success, + Toast.LENGTH_SHORT).show() + } } else -> { loadTarget(id) @@ -508,55 +655,207 @@ class MainActivity : AppCompatActivity() { |_____/ \__, |_| |_|\___| __/ | |__*/ - fun syncCurrentFeature() { + private suspend fun syncCurrentFeature() { + if (app.profile.archived) { + MaterialAlertDialogBuilder(this) + .setTitle(R.string.profile_archived_title) + .setMessage( + R.string.profile_archived_text, + app.profile.studentSchoolYearStart, + app.profile.studentSchoolYearStart + 1 + ) + .setPositiveButton(R.string.ok, null) + .show() + swipeRefreshLayout.isRefreshing = false + return + } + if (app.profile.shouldArchive()) { + MaterialAlertDialogBuilder(this) + .setTitle(R.string.profile_archiving_title) + .setMessage( + R.string.profile_archiving_format, + app.profile.dateYearEnd.formattedString + ) + .setPositiveButton(R.string.ok, null) + .show() + } + if (app.profile.isBeforeYear()) { + MaterialAlertDialogBuilder(this) + .setTitle(R.string.profile_year_not_started_title) + .setMessage( + R.string.profile_year_not_started_format, + app.profile.dateSemester1Start.formattedString + ) + .setPositiveButton(R.string.ok, null) + .show() + swipeRefreshLayout.isRefreshing = false + return + } + + val error = withContext(Dispatchers.IO) { + app.availabilityManager.check(app.profile) + } + when (error?.type) { + Type.NOT_AVAILABLE -> { + swipeRefreshLayout.isRefreshing = false + loadTarget(DRAWER_ITEM_HOME) + RegisterUnavailableDialog(this, error.status!!).show() + return + } + Type.API_ERROR -> { + errorSnackbar.addError(error.apiError!!).show() + return + } + Type.NO_API_ACCESS -> { + Toast.makeText(this, R.string.error_no_api_access, Toast.LENGTH_SHORT).show() + } + } + swipeRefreshLayout.isRefreshing = true Toast.makeText(this, fragmentToSyncName(navTargetId), Toast.LENGTH_SHORT).show() - val callback = object : SyncCallback { - override fun onLoginFirst(profileList: List, loginStore: LoginStore) { - - } - - override fun onSuccess(activityContext: Context, profileFull: ProfileFull) { - swipeRefreshLayout.isRefreshing = false - } - - override fun onError(activityContext: Context, error: AppError) { - swipeRefreshLayout.isRefreshing = false - app.apiEdziennik.guiShowErrorSnackbar(this@MainActivity, error) - } - - override fun onProgress(progressStep: Int) { - - } - - override fun onActionStarted(stringResId: Int) { - - } + val fragmentParam = when (navTargetId) { + DRAWER_ITEM_MESSAGES -> MessagesFragment.pageSelection + else -> 0 } - val feature = fragmentToFeature(navTargetId) - if (feature == FEATURE_ALL) { - swipeRefreshLayout.isRefreshing = false - app.apiEdziennik.guiSync(app, this, App.profileId, R.string.sync_dialog_title, R.string.sync_dialog_text, R.string.sync_done) - } else { - app.apiEdziennik.guiSyncSilent(app, this, App.profileId, callback, feature) + val arguments = when (navTargetId) { + DRAWER_ITEM_TIMETABLE -> JsonObject("weekStart" to TimetableFragment.pageSelection?.weekStart?.stringY_m_d) + else -> null + } + EdziennikTask.syncProfile( + App.profileId, + listOf(navTargetId to fragmentParam), + arguments = arguments + ).enqueue(this) + } + + @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) + fun onUpdateEvent(event: Update) { + EventBus.getDefault().removeStickyEvent(event) + UpdateAvailableDialog(this, event).show() + } + + @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) + fun onRegisterAvailabilityEvent(event: RegisterAvailabilityEvent) { + EventBus.getDefault().removeStickyEvent(event) + val error = app.availabilityManager.check(app.profile, cacheOnly = true) + if (error != null) { + RegisterUnavailableDialog(this, error.status!!).show() } } - private fun fragmentToFeature(currentFragment: Int): Int { - return when (currentFragment) { - DRAWER_ITEM_TIMETABLE -> FEATURE_TIMETABLE - DRAWER_ITEM_AGENDA -> FEATURE_AGENDA - DRAWER_ITEM_GRADES -> FEATURE_GRADES - DRAWER_ITEM_HOMEWORK -> FEATURE_HOMEWORK - DRAWER_ITEM_BEHAVIOUR -> FEATURE_NOTICES - DRAWER_ITEM_ATTENDANCE -> FEATURE_ATTENDANCE - DRAWER_ITEM_MESSAGES -> when (MessagesFragment.pageSelection) { - 1 -> FEATURE_MESSAGES_OUTBOX - else -> FEATURE_MESSAGES_INBOX + + @Subscribe(threadMode = ThreadMode.MAIN) + fun onApiTaskStartedEvent(event: ApiTaskStartedEvent) { + swipeRefreshLayout.isRefreshing = true + if (event.profileId == App.profileId) { + navView.toolbar.apply { + subtitleFormat = null + subtitleFormatWithUnread = null + subtitle = getString(R.string.toolbar_subtitle_syncing) } - DRAWER_ITEM_ANNOUNCEMENTS -> FEATURE_ANNOUNCEMENTS - else -> FEATURE_ALL } } + + @Subscribe(threadMode = ThreadMode.MAIN) + fun onProfileListEmptyEvent(event: ProfileListEmptyEvent) { + d(TAG, "Profile list is empty. Launch LoginActivity.") + app.config.loginFinished = false + startActivity(Intent(this, LoginActivity::class.java)) + finish() + } + + @Subscribe(threadMode = ThreadMode.MAIN) + fun onApiTaskProgressEvent(event: ApiTaskProgressEvent) { + if (event.profileId == App.profileId) { + navView.toolbar.apply { + subtitleFormat = null + subtitleFormatWithUnread = null + subtitle = if (event.progress < 0f) + event.progressText ?: "" + else + getString( + R.string.toolbar_subtitle_syncing_format, + event.progress.roundToInt(), + event.progressText ?: "", + ) + + } + } + } + + @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) + fun onApiTaskFinishedEvent(event: ApiTaskFinishedEvent) { + EventBus.getDefault().removeStickyEvent(event) + if (event.profileId == App.profileId) { + navView.toolbar.apply { + subtitleFormat = R.string.toolbar_subtitle + subtitleFormatWithUnread = R.plurals.toolbar_subtitle_with_unread + subtitle = "Gotowe" + } + } + } + + @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) + fun onApiTaskAllFinishedEvent(event: ApiTaskAllFinishedEvent) { + EventBus.getDefault().removeStickyEvent(event) + swipeRefreshLayout.isRefreshing = false + } + + @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) + fun onApiTaskErrorEvent(event: ApiTaskErrorEvent) { + EventBus.getDefault().removeStickyEvent(event) + if (event.error.errorCode == ERROR_VULCAN_API_DEPRECATED) { + if (event.error.profileId != App.profileId) + return + ErrorDetailsDialog(this, listOf(event.error)).show() + } + navView.toolbar.apply { + subtitleFormat = R.string.toolbar_subtitle + subtitleFormatWithUnread = R.plurals.toolbar_subtitle_with_unread + subtitle = "Gotowe" + } + mainSnackbar.dismiss() + errorSnackbar.addError(event.error).show() + } + + @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) + fun onAppManagerDetectedEvent(event: AppManagerDetectedEvent) { + EventBus.getDefault().removeStickyEvent(event) + if (app.config.sync.dontShowAppManagerDialog) + return + MaterialAlertDialogBuilder(this) + .setTitle(R.string.app_manager_dialog_title) + .setMessage(R.string.app_manager_dialog_text) + .setPositiveButton(R.string.ok) { _, _ -> + try { + for (intent in appManagerIntentList) { + if (packageManager.resolveActivity(intent, + PackageManager.MATCH_DEFAULT_ONLY) != null + ) { + startActivity(intent) + } + } + } catch (e: Exception) { + try { + startActivity(Intent(Settings.ACTION_SETTINGS)) + } catch (e: Exception) { + e.printStackTrace() + Toast.makeText(this, R.string.app_manager_open_failed, Toast.LENGTH_SHORT) + .show() + } + } + } + .setNeutralButton(R.string.dont_ask_again) { _, _ -> + app.config.sync.dontShowAppManagerDialog = true + } + .setCancelable(false) + .show() + } + + @Subscribe(threadMode = ThreadMode.MAIN) + fun onUserActionRequiredEvent(event: UserActionRequiredEvent) { + app.userActionManager.execute(this, event.profileId, event.type) + } + private fun fragmentToSyncName(currentFragment: Int): Int { return when (currentFragment) { DRAWER_ITEM_TIMETABLE -> R.string.sync_feature_timetable @@ -585,34 +884,75 @@ class MainActivity : AppCompatActivity() { handleIntent(intent?.extras) } } - private fun handleIntent(extras: Bundle?) { - Log.d(TAG, "handleIntent() {") + fun handleIntent(extras: Bundle?) { + + d(TAG, "handleIntent() {") extras?.keySet()?.forEach { key -> - Log.d(TAG, " \"$key\": "+extras.get(key)) + d(TAG, " \"$key\": " + extras.get(key)) + } + d(TAG, "}") + + var intentProfileId = -1 + var intentTargetId = -1 + + if (extras?.containsKey("action") == true) { + val handled = when (extras.getString("action")) { + "serverMessage" -> { + ServerMessageDialog( + this, + extras.getString("serverMessageTitle") ?: getString(R.string.app_name), + extras.getString("serverMessageText") ?: "" + ).show() + true + } + "feedbackMessage" -> { + intentTargetId = TARGET_FEEDBACK + false + } + "userActionRequired" -> { + app.userActionManager.execute( + this, + extras.getInt("profileId"), + extras.getInt("type") + ) + true + } + "createManualEvent" -> { + val date = extras.getString("eventDate") + ?.let { Date.fromY_m_d(it) } + ?: Date.getToday() + EventManualDialog( + this, + App.profileId, + defaultDate = date + ).show() + true + } + else -> false + } + if (handled && !navLoading) { + return + } } - Log.d(TAG, "}") if (extras?.containsKey("reloadProfileId") == true) { val reloadProfileId = extras.getInt("reloadProfileId", -1) extras.remove("reloadProfileId") - if (reloadProfileId == -1 || (app.profile != null && app.profile.id == reloadProfileId)) { + if (reloadProfileId == -1 || app.profile.id == reloadProfileId) { reloadTarget() return } } - var intentProfileId = -1 - var intentTargetId = -1 - - if (extras?.containsKey("profileId") == true) { + if (extras?.getInt("profileId", -1) != -1) { intentProfileId = extras.getInt("profileId", -1) - extras.remove("profileId") + extras?.remove("profileId") } - if (extras?.containsKey("fragmentId") == true) { + if (extras?.getInt("fragmentId", -1) != -1) { intentTargetId = extras.getInt("fragmentId", -1) - extras.remove("fragmentId") + extras?.remove("fragmentId") } /*if (intentTargetId == -1 && navController.currentDestination?.id == R.id.loadingFragment) { @@ -620,37 +960,43 @@ class MainActivity : AppCompatActivity() { }*/ if (navLoading) { - navLoading = false b.fragment.removeAllViews() if (intentTargetId == -1) intentTargetId = HOME_ID } when { - app.profile == null -> { + app.profile.id == 0 -> { if (intentProfileId == -1) - intentProfileId = app.appSharedPrefs.getInt("current_profile_id", 1) - loadProfile(intentProfileId, intentTargetId) + intentProfileId = app.config.lastProfileId + loadProfile(intentProfileId, intentTargetId, extras) } intentProfileId != -1 -> { - loadProfile(intentProfileId, intentTargetId) + if (app.profile.id != intentProfileId) + loadProfile(intentProfileId, intentTargetId, extras) + else + loadTarget(intentTargetId, extras) } intentTargetId != -1 -> { drawer.currentProfile = app.profile.id - loadTarget(intentTargetId, extras) + if (navTargetId != intentTargetId || navLoading) + loadTarget(intentTargetId, extras) } else -> { drawer.currentProfile = app.profile.id } } + navLoading = false } override fun recreate() { recreate(navTargetId) } + fun recreate(targetId: Int) { recreate(targetId, null) } + fun recreate(targetId: Int? = null, arguments: Bundle? = null) { val intent = Intent(this, MainActivity::class.java) if (arguments != null) @@ -663,17 +1009,37 @@ class MainActivity : AppCompatActivity() { startActivity(intent) } + override fun onStart() { + d(TAG, "Activity started") + super.onStart() + } + + override fun onStop() { + d(TAG, "Activity stopped") + super.onStop() + } + override fun onResume() { + d(TAG, "Activity resumed") val filter = IntentFilter() filter.addAction(Intent.ACTION_MAIN) registerReceiver(intentReceiver, filter) + EventBus.getDefault().register(this) super.onResume() } + override fun onPause() { + d(TAG, "Activity paused") unregisterReceiver(intentReceiver) + EventBus.getDefault().unregister(this) super.onPause() } + override fun onDestroy() { + d(TAG, "Activity destroyed") + super.onDestroy() + } + override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt("fragmentId", navTargetId) @@ -683,20 +1049,11 @@ class MainActivity : AppCompatActivity() { super.onNewIntent(intent) handleIntent(intent?.extras) } + + @Suppress("deprecation") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) - if (requestCode == REQUEST_LOGIN_ACTIVITY) { - if (resultCode == Activity.RESULT_CANCELED && false) { - finish() - } - else { - if (!app.appConfig.loginFinished) - finish() - else { - handleIntent(data?.extras) - } - } - } + requestHandler.handleResult(requestCode, resultCode, data) } /* _ _ _ _ _ @@ -706,89 +1063,200 @@ class MainActivity : AppCompatActivity() { | |___| (_) | (_| | (_| | | | | | | | __/ |_| | | | (_) | (_| \__ \ |______\___/ \__,_|\__,_| |_| |_| |_|\___|\__|_| |_|\___/ \__,_|__*/ val navOptions = NavOptions.Builder() - .setEnterAnim(R.anim.task_open_enter) // new fragment enter - .setExitAnim(R.anim.task_open_exit) // old fragment exit - .setPopEnterAnim(R.anim.task_close_enter) // old fragment enter back - .setPopExitAnim(R.anim.task_close_exit) // new fragment exit - .build() + .setEnterAnim(R.anim.task_open_enter) // new fragment enter + .setExitAnim(R.anim.task_open_exit) // old fragment exit + .setPopEnterAnim(R.anim.task_close_enter) // old fragment enter back + .setPopExitAnim(R.anim.task_close_exit) // new fragment exit + .build() - fun loadProfile(id: Int) = loadProfile(id, navTargetId) - fun loadProfile(id: Int, arguments: Bundle?) = loadProfile(id, navTargetId, arguments) - fun loadProfile(id: Int, drawerSelection: Int, arguments: Bundle? = null) { - Log.d("NavDebug", "loadProfile(id = $id, drawerSelection = $drawerSelection)") - if (app.profile != null && App.profileId == id) { - drawer.currentProfile = app.profile.id - loadTarget(drawerSelection, arguments) - return - } - AsyncTask.execute { - app.profileLoadById(id) + private fun canNavigate(): Boolean = onBeforeNavigate?.invoke() != false - this.runOnUiThread { - if (app.profile == null) { - LoginActivity.firstCompleted = false - if (app.appConfig.loginFinished) { - // this shouldn't run - profileListEmptyListener() - } - } else { - setDrawerItems() - drawer.currentProfile = app.profile.id - loadTarget(drawerSelection, arguments) - } + fun resumePausedNavigation(): Boolean { + if (pausedNavigationData == null) + return false + pausedNavigationData?.let { data -> + when (data) { + is PausedNavigationData.LoadProfile -> loadProfile( + id = data.id, + drawerSelection = data.drawerSelection, + arguments = data.arguments, + skipBeforeNavigate = true, + ) + is PausedNavigationData.LoadTarget -> loadTarget( + id = data.id, + arguments = data.arguments, + skipBeforeNavigate = true, + ) + else -> return false } } + pausedNavigationData = null + return true } - fun loadTarget(id: Int, arguments: Bundle? = null) { + + fun loadProfile(id: Int) = loadProfile(id, navTargetId) + + // fun loadProfile(id: Int, arguments: Bundle?) = loadProfile(id, navTargetId, arguments) + fun loadProfile(profile: Profile): Boolean { + if (!canNavigate()) { + pausedNavigationData = PausedNavigationData.LoadProfile( + id = profile.id, + drawerSelection = navTargetId, + arguments = null, + ) + return false + } + + loadProfile(profile, navTargetId, null) + return true + } + + private fun loadProfile( + id: Int, + drawerSelection: Int, + arguments: Bundle? = null, + skipBeforeNavigate: Boolean = false, + ): Boolean { + if (!skipBeforeNavigate && !canNavigate()) { + drawer.close() + // restore the previous profile after changing it with the drawer + // well, it still does not change the toolbar profile image, + // but that's now NavView's problem, not mine. + drawer.currentProfile = app.profile.id + pausedNavigationData = PausedNavigationData.LoadProfile( + id = id, + drawerSelection = drawerSelection, + arguments = arguments, + ) + return false + } + + if (App.profileId == id) { + drawer.currentProfile = app.profile.id + // skipBeforeNavigate because it's checked above already + loadTarget(drawerSelection, arguments, skipBeforeNavigate = true) + return true + } + app.profileLoad(id) { + loadProfile(it, drawerSelection, arguments) + } + return true + } + + private fun loadProfile(profile: Profile, drawerSelection: Int, arguments: Bundle?) { + App.profile = profile + MessagesFragment.pageSelection = -1 + + setDrawerItems() + + val previousArchivedId = if (app.profile.archived) app.profile.id else null + if (previousArchivedId != null) { + // prevents accidentally removing the first item if the archived profile is not shown + drawer.removeProfileById(previousArchivedId) + } + if (profile.archived) { + drawer.prependProfile(Profile( + id = profile.id, + loginStoreId = profile.loginStoreId, + loginStoreType = profile.loginStoreType, + name = profile.name, + subname = "Archiwum - ${profile.subname}" + ).also { + it.archived = true + }) + } + + // the drawer profile is updated automatically when the drawer item is clicked + // update it manually when switching profiles from other source + //if (drawer.currentProfile != app.profile.id) + drawer.currentProfile = app.profileId + loadTarget(drawerSelection, arguments, skipBeforeNavigate = true) + } + + fun loadTarget( + id: Int, + arguments: Bundle? = null, + skipBeforeNavigate: Boolean = false, + ): Boolean { var loadId = id if (loadId == -1) { loadId = DRAWER_ITEM_HOME } - val target = navTargetList - .singleOrNull { it.id == loadId } - if (target == null) { - Toast.makeText(this, getString(R.string.error_invalid_fragment, id), Toast.LENGTH_LONG).show() - loadTarget(navTargetList.first(), arguments) - } - else { - loadTarget(target, arguments) + val targets = navTargetList + .flatMap { it.subItems?.toList() ?: emptyList() } + .plus(navTargetList) + val target = targets.firstOrNull { it.id == loadId } + return when { + target == null -> { + Toast.makeText( + this, + getString(R.string.error_invalid_fragment, id), + Toast.LENGTH_LONG, + ).show() + loadTarget(navTargetList.first(), arguments, skipBeforeNavigate) + } + target.fragmentClass != null -> { + loadTarget(target, arguments, skipBeforeNavigate) + } + else -> { + false + } } } - private fun loadTarget(target: NavTarget, arguments: Bundle? = null) { - Log.d("NavDebug", "loadItem(id = ${target.id})") + private fun loadTarget( + target: NavTarget, + args: Bundle? = null, + skipBeforeNavigate: Boolean = false, + ): Boolean { + d("NavDebug", "loadTarget(target = $target, args = $args)") + + if (!skipBeforeNavigate && !canNavigate()) { + bottomSheet.close() + drawer.close() + pausedNavigationData = PausedNavigationData.LoadTarget( + id = target.id, + arguments = args, + ) + return false + } + pausedNavigationData = null + + val arguments = args + ?: navBackStack.firstOrNull { it.first.id == target.id }?.second + ?: Bundle() bottomSheet.close() bottomSheet.removeAllContextual() bottomSheet.toggleGroupEnabled = false - bottomSheet.onCloseListener = null drawer.close() - drawer.setSelection(target.id, fireOnClick = false) + if (drawer.getSelection() != target.id) + drawer.setSelection(target.id, fireOnClick = false) navView.toolbar.setTitle(target.title ?: target.name) navView.bottomBar.fabEnable = false navView.bottomBar.fabExtended = false navView.bottomBar.setFabOnClickListener(null) - Log.d("NavDebug", "Navigating from ${navTarget.fragmentClass?.java?.simpleName} to ${target.fragmentClass?.java?.simpleName}") + d("NavDebug", + "Navigating from ${navTarget.fragmentClass?.java?.simpleName} to ${target.fragmentClass?.java?.simpleName}") - val fragment = target.fragmentClass?.java?.newInstance() ?: return + val fragment = target.fragmentClass?.java?.newInstance() ?: return false fragment.arguments = arguments val transaction = fragmentManager.beginTransaction() if (navTarget == target) { // just reload the current target transaction.setCustomAnimations( - R.anim.fade_in, - R.anim.fade_out + R.anim.fade_in, + R.anim.fade_out ) - } - else { - navBackStack.lastIndexOf(target).let { + } else { + navBackStack.keys().lastIndexOf(target).let { if (it == -1) return@let target // pop the back stack up until that target transaction.setCustomAnimations( - R.anim.task_close_enter, - R.anim.task_close_exit + R.anim.task_close_enter, + R.anim.task_close_exit ) // navigating grades_add -> grades @@ -804,17 +1272,19 @@ class MainActivity : AppCompatActivity() { navBackStack.removeAt(navBackStack.lastIndex) } navTarget = target + navArguments = arguments return@let null }?.let { // target is neither current nor in the back stack // so navigate to it transaction.setCustomAnimations( - R.anim.task_open_enter, - R.anim.task_open_exit + R.anim.task_open_enter, + R.anim.task_open_exit ) - navBackStack.add(navTarget) + navBackStack.add(navTarget to navArguments) navTarget = target + navArguments = arguments } } @@ -827,9 +1297,10 @@ class MainActivity : AppCompatActivity() { } } - Log.d("NavDebug", "Current fragment ${navTarget.fragmentClass?.java?.simpleName}, pop to home ${navTarget.popToHome}, back stack:") + d("NavDebug", + "Current fragment ${navTarget.fragmentClass?.java?.simpleName}, pop to home ${navTarget.popToHome}, back stack:") navBackStack.forEachIndexed { index, target2 -> - Log.d("NavDebug", " - $index: ${target2.fragmentClass?.java?.simpleName}") + d("NavDebug", " - $index: ${target2.first.fragmentClass?.java?.simpleName}") } transaction.replace(R.id.fragment, fragment) @@ -838,32 +1309,46 @@ class MainActivity : AppCompatActivity() { // TASK DESCRIPTION if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val bm = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher) + + @Suppress("deprecation") val taskDesc = ActivityManager.TaskDescription( - if (target.id == HOME_ID) getString(R.string.app_name) else getString(R.string.app_task_format, getString(target.name)), - bm, - getColorFromAttr(this, R.attr.colorSurface) + if (target.id == HOME_ID) + getString(R.string.app_name) + else + getString(R.string.app_task_format, getString(target.name)), + bm, + getColorFromAttr(this, R.attr.colorSurface) ) setTaskDescription(taskDesc) } - + return true } + fun reloadTarget() = loadTarget(navTarget) - private fun popBackStack(): Boolean { + private fun popBackStack(skipBeforeNavigate: Boolean = false): Boolean { if (navBackStack.size == 0) { return false } // TODO back stack argument support - if (navTarget.popToHome) { - loadTarget(HOME_ID) - } - else { - loadTarget(navBackStack.last()) + when { + navTarget.popToHome -> { + loadTarget(HOME_ID, skipBeforeNavigate = skipBeforeNavigate) + } + navTarget.popTo != null -> { + loadTarget(navTarget.popTo ?: HOME_ID, skipBeforeNavigate = skipBeforeNavigate) + } + else -> { + navBackStack.last().let { + loadTarget(it.first, it.second, skipBeforeNavigate = skipBeforeNavigate) + } + } } return true } - fun navigateUp() { - if (!popBackStack()) { + + fun navigateUp(skipBeforeNavigate: Boolean = false) { + if (!popBackStack(skipBeforeNavigate)) { super.onBackPressed() } } @@ -873,9 +1358,11 @@ class MainActivity : AppCompatActivity() { * that something has changed in the bottom sheet. */ fun gainAttention() { - /*b.navView.postDelayed({ + if (app.config.ui.bottomSheetOpened) + return + b.navView.postDelayed({ navView.gainAttentionOnBottomBar() - }, 2000)*/ + }, 2000) } fun gainAttentionFAB() { @@ -890,42 +1377,62 @@ class MainActivity : AppCompatActivity() { }, 3000) } + fun setAppBackground() { + try { + b.root.background = app.config.ui.appBackground?.let { + if (it.endsWith(".gif")) + GifDrawable(it) + else + BitmapDrawable.createFromPath(it) + } + } catch (e: IOException) { + e.printStackTrace() + } + } + /* _____ _ _ | __ \ (_) | | | | |_ __ __ ___ _____ _ __ _| |_ ___ _ __ ___ ___ | | | | '__/ _` \ \ /\ / / _ \ '__| | | __/ _ \ '_ ` _ \/ __| | |__| | | | (_| |\ V V / __/ | | | || __/ | | | | \__ \ |_____/|_| \__,_| \_/\_/ \___|_| |_|\__\___|_| |_| |_|__*/ + @Suppress("UNUSED_PARAMETER") private fun createDrawerItem(target: NavTarget, level: Int = 1): IDrawerItem<*> { - val item = DrawerPrimaryItem() - .withIdentifier(target.id.toLong()) - .withName(target.name) - .withHiddenInMiniDrawer(!app.appConfig.miniDrawerButtonIds.contains(target.id)) - .also { if (target.description != null) it.withDescription(target.description!!) } - .also { if (target.icon != null) it.withIcon(target.icon!!) } - .also { if (target.title != null) it.withAppTitle(getString(target.title!!)) } - .also { if (target.badgeTypeId != null) it.withBadgeStyle(drawer.badgeStyle)} + val item = when { + target.subItems != null -> ExpandableDrawerItem() + level > 1 -> SecondaryDrawerItem() + else -> DrawerPrimaryItem() + } + item.also { + it.identifier = target.id.toLong() + it.nameRes = target.name + it.hiddenInMiniDrawer = !app.config.ui.miniMenuButtons.contains(target.id) + it.description = target.description?.toStringHolder() + it.icon = target.icon?.toImageHolder() + if (it is DrawerPrimaryItem) + it.appTitle = target.title?.resolveString(this) + if (it is ColorfulBadgeable && target.badgeTypeId != null) + it.badgeStyle = drawer.badgeStyle + it.isSelectedBackgroundAnimated = false + it.level = level + } if (target.badgeTypeId != null) drawer.addUnreadCounterType(target.badgeTypeId!!, target.id) - // TODO sub items - /* - if (target.subItems != null) { - for (subItem in target.subItems!!) { - item.subItems += createDrawerItem(subItem, level+1) - } - }*/ + + item.subItems = target.subItems?.map { + createDrawerItem(it, level + 1) + }?.toMutableList() ?: mutableListOf() return item } fun setDrawerItems() { - Log.d("NavDebug", "setDrawerItems() app.profile = ${app.profile ?: "null"}") + d("NavDebug", "setDrawerItems() app.profile = ${app.profile}") val drawerItems = arrayListOf>() val drawerProfiles = arrayListOf() - val supportedFragments = if (app.profile == null) arrayListOf() - else app.profile.supportedFragments + val supportedFragments = app.profile.supportedFragments targetPopToHomeList.clear() @@ -940,7 +1447,11 @@ class MainActivity : AppCompatActivity() { if (target.popToHome) targetPopToHomeList += target.id - if (target.isInDrawer && (target.isStatic || supportedFragments.isEmpty() || supportedFragments.contains(target.id))) { + if (target.isInDrawer && ( + target.isStatic + || supportedFragments.isEmpty() + || supportedFragments.contains(target.id)) + ) { drawerItems += createDrawerItem(target) if (target.id == 1) { targetHomeId = target.id @@ -948,11 +1459,14 @@ class MainActivity : AppCompatActivity() { } if (target.isInProfileList) { - drawerProfiles += ProfileSettingDrawerItem() - .withIdentifier(target.id.toLong()) - .withName(target.name) - .also { if (target.description != null) it.withDescription(target.description!!) } - .also { if (target.icon != null) it.withIcon(target.icon!!) } + drawerProfiles += ProfileSettingDrawerItem().apply { + identifier = target.id.toLong() + nameRes = target.name + if (target.description != null) + descriptionRes = target.description!! + if (target.icon != null) + withIcon(target.icon!!) + } } } @@ -965,54 +1479,26 @@ class MainActivity : AppCompatActivity() { drawer.addProfileSettings(*drawerProfiles.toTypedArray()) } - private fun showProfileContextMenu(profile: IProfile<*>, view: View) { - val profileId = profile.identifier.toInt() - val popupMenu = PopupMenu(this, view) - popupMenu.menu.add(0, 1, 1, R.string.profile_menu_open_settings) - popupMenu.menu.add(0, 2, 2, R.string.profile_menu_remove) - popupMenu.setOnMenuItemClickListener { item -> - if (item.itemId == 1) { - if (profileId != app.profile.id) { - loadProfile(profileId, DRAWER_ITEM_SETTINGS) - return@setOnMenuItemClickListener true - } - loadTarget(DRAWER_ITEM_SETTINGS, null) - } else if (item.itemId == 2) { - app.apiEdziennik.guiRemoveProfile(this@MainActivity, profileId, profile.name?.getText(this).toString()) - } - true - } - popupMenu.show() - } - private val targetPopToHomeList = arrayListOf() private var targetHomeId: Int = -1 override fun onBackPressed() { if (!b.navView.onBackPressed()) { - - navigateUp() - - /*val currentDestinationId = navController.currentDestination?.id - - if (if (targetHomeId != -1 && targetPopToHomeList.contains(navController.currentDestination?.id)) { - if (!navController.popBackStack(targetHomeId, false)) { - navController.navigateUp() - } - true - } else { - navController.navigateUp() - }) { - val currentId = navController.currentDestination?.id ?: -1 - val drawerSelection = navTargetList - .singleOrNull { - it.navGraphId == currentId - }?.also { - navView.toolbar.setTitle(it.title ?: it.name) - }?.id ?: -1 - drawer.setSelection(drawerSelection, false) + if (App.config.ui.openDrawerOnBackPressed && ((navTarget.popTo == null && navTarget.popToHome) + || navTarget.id == DRAWER_ITEM_HOME) + ) { + b.navView.drawer.toggle() } else { - super.onBackPressed() - }*/ + navigateUp() + } } } + + fun error(error: ApiError) = errorSnackbar.addError(error).show() + fun snackbar( + text: String, + actionText: String? = null, + onClick: (() -> Unit)? = null, + ) = mainSnackbar.snackbar(text, actionText, onClick) + + fun snackbarDismiss() = mainSnackbar.dismiss() } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/MainActivityRequestHandler.kt b/app/src/main/java/pl/szczodrzynski/edziennik/MainActivityRequestHandler.kt new file mode 100644 index 00000000..ff165a46 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/MainActivityRequestHandler.kt @@ -0,0 +1,220 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-3-23. + */ + +package pl.szczodrzynski.edziennik + +import android.app.Activity +import android.content.Intent +import android.net.Uri +import android.provider.OpenableColumns +import com.canhub.cropper.CropImage +import com.canhub.cropper.CropImageView +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ui.login.LoginActivity +import java.io.File +import java.io.FileOutputStream + +class MainActivityRequestHandler(val activity: MainActivity) { + companion object { + private const val REQUEST_LOGIN_ACTIVITY = 2000 + private const val REQUEST_FILE_HEADER_BACKGROUND = 3000 + private const val REQUEST_FILE_APP_BACKGROUND = 4000 + private const val REQUEST_FILE_PROFILE_IMAGE = 5000 + private const val REQUEST_CROP_HEADER_BACKGROUND = 3100 + private const val REQUEST_CROP_APP_BACKGROUND = 4100 + private const val REQUEST_CROP_PROFILE_IMAGE = 5100 + } + + private val app = activity.app + private val requestData = mutableMapOf() + private val listeners = mutableMapOf Unit>() + + private val manager + get() = app.permissionManager + + fun requestLogin() = activity.startActivityForResult( + Intent(activity, LoginActivity::class.java), + REQUEST_LOGIN_ACTIVITY + ) + + fun requestHeaderBackground(listener: (Any?) -> Unit) = + manager.requestCameraPermission( + activity, 0, isRequired = false + ) { + listeners[REQUEST_FILE_HEADER_BACKGROUND] = listener + activity.startActivityForResult( + CropImage.getPickImageChooserIntent( + activity, + activity.getString(R.string.pick_image_intent_chooser_title), + true, + true + ), + REQUEST_FILE_HEADER_BACKGROUND + ) + } + + fun requestAppBackground(listener: (Any?) -> Unit) = + manager.requestCameraPermission( + activity, 0, isRequired = false + ) { + listeners[REQUEST_FILE_APP_BACKGROUND] = listener + activity.startActivityForResult( + CropImage.getPickImageChooserIntent( + activity, + activity.getString(R.string.pick_image_intent_chooser_title), + true, + true + ), + REQUEST_FILE_APP_BACKGROUND + ) + } + + fun requestProfileImage(profile: Profile, listener: (Any?) -> Unit) = + manager.requestCameraPermission( + activity, 0, isRequired = false + ) { + listeners[REQUEST_FILE_PROFILE_IMAGE] = listener + requestData[REQUEST_FILE_PROFILE_IMAGE] = profile + activity.startActivityForResult( + CropImage.getPickImageChooserIntent( + activity, + activity.getString(R.string.pick_image_intent_chooser_title), + true, + true + ), + REQUEST_FILE_PROFILE_IMAGE + ) + } + + private fun getFileInfo(uri: Uri): Pair { + if (uri.scheme == "file") { + return (uri.lastPathSegment ?: "unknown") to null + } + val cursor = activity.contentResolver.query( + uri, + null, + null, + null, + null, + null + ) + + return cursor?.use { + if (it.moveToFirst()) { + val name = it.getString(it.getColumnIndex(OpenableColumns.DISPLAY_NAME)) + val mimeIndex = it.getColumnIndex("mime_type") + val mimeType = if (mimeIndex != -1) it.getString(mimeIndex) else null + + name to mimeType + } else + null + } ?: "unknown" to null + } + + private fun shouldCrop(uri: Uri): Boolean { + val (filename, mimeType) = getFileInfo(uri) + return !filename.endsWith(".gif") && mimeType?.endsWith("/gif") != true + } + + private fun saveFile(uri: Uri, name: String): String { + val (filename, _) = getFileInfo(uri) + val extension = filename.substringAfterLast('.') + val file = File(activity.filesDir, "$name.$extension") + activity.contentResolver.openInputStream(uri)?.use { input -> + FileOutputStream(file).use { output -> + input.copyTo(output) + } + } + return file.absolutePath + } + + fun handleResult(requestCode: Int, resultCode: Int, data: Intent?) { + if (resultCode != Activity.RESULT_OK) + return + var uri = CropImage.getPickImageResultUri(activity, data) + when (requestCode) { + REQUEST_LOGIN_ACTIVITY -> { + if (!app.config.loginFinished) + activity.finish() + else { + activity.handleIntent(data?.extras) + } + } + REQUEST_FILE_HEADER_BACKGROUND -> { + if (uri == null) + return // TODO: 2021-03-24 if the app returns no data + if (shouldCrop(uri)) { + val intent = CropImage.activity(uri) + .setAspectRatio(512, 288) + .setGuidelines(CropImageView.Guidelines.ON_TOUCH) + .setAllowFlipping(true) + .setAllowRotation(true) + .setRequestedSize(512, 288) + .getIntent(activity) + activity.startActivityForResult(intent, REQUEST_CROP_HEADER_BACKGROUND) + } else { + val path = saveFile(uri, "header") + app.config.ui.headerBackground = path + listeners.remove(REQUEST_FILE_HEADER_BACKGROUND)?.invoke(path) + } + } + REQUEST_FILE_APP_BACKGROUND -> { + if (uri == null) + return + if (shouldCrop(uri)) { + val intent = CropImage.activity(uri) + .setGuidelines(CropImageView.Guidelines.ON_TOUCH) + .setAllowFlipping(true) + .setAllowRotation(true) + .getIntent(activity) + activity.startActivityForResult(intent, REQUEST_CROP_APP_BACKGROUND) + } else { + val path = saveFile(uri, "background") + app.config.ui.appBackground = path + listeners.remove(REQUEST_FILE_APP_BACKGROUND)?.invoke(path) + } + } + REQUEST_FILE_PROFILE_IMAGE -> { + if (uri == null) + return + if (shouldCrop(uri)) { + val intent = CropImage.activity(uri) + .setAspectRatio(1, 1) + .setCropShape(CropImageView.CropShape.OVAL) + .setGuidelines(CropImageView.Guidelines.ON_TOUCH) + .setAllowFlipping(true) + .setAllowRotation(true) + .setRequestedSize(512, 512) + .getIntent(activity) + activity.startActivityForResult(intent, REQUEST_CROP_PROFILE_IMAGE) + } else { + val profile = + requestData.remove(REQUEST_FILE_PROFILE_IMAGE) as? Profile ?: return + val path = saveFile(uri, "profile${profile.id}") + profile.image = path + listeners.remove(REQUEST_FILE_PROFILE_IMAGE)?.invoke(profile) + } + } + REQUEST_CROP_HEADER_BACKGROUND -> { + uri = CropImage.getActivityResult(data)?.uri ?: return + val path = saveFile(uri, "header") + app.config.ui.headerBackground = path + listeners.remove(REQUEST_FILE_HEADER_BACKGROUND)?.invoke(path) + } + REQUEST_CROP_APP_BACKGROUND -> { + uri = CropImage.getActivityResult(data)?.uri ?: return + val path = saveFile(uri, "background") + app.config.ui.appBackground = path + listeners.remove(REQUEST_FILE_APP_BACKGROUND)?.invoke(path) + } + REQUEST_CROP_PROFILE_IMAGE -> { + uri = CropImage.getActivityResult(data)?.uri ?: return + val profile = requestData.remove(REQUEST_FILE_PROFILE_IMAGE) as? Profile ?: return + val path = saveFile(uri, "profile${profile.id}") + profile.image = path + listeners.remove(REQUEST_FILE_PROFILE_IMAGE)?.invoke(profile) + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/Notifier.java b/app/src/main/java/pl/szczodrzynski/edziennik/Notifier.java deleted file mode 100644 index cc2237c3..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/Notifier.java +++ /dev/null @@ -1,356 +0,0 @@ -package pl.szczodrzynski.edziennik; - -import android.app.IntentService; -import android.app.Notification; -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.os.Build; -import androidx.core.app.NotificationCompat; -import androidx.core.content.ContextCompat; -import android.util.Log; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import pl.szczodrzynski.edziennik.data.db.modules.profiles.ProfileFull; -import pl.szczodrzynski.edziennik.utils.models.Date; -import pl.szczodrzynski.edziennik.utils.models.Time; -import pl.szczodrzynski.edziennik.receivers.BootReceiver; -import pl.szczodrzynski.edziennik.sync.SyncJob; -import pl.szczodrzynski.edziennik.sync.SyncService; - -import static androidx.core.app.NotificationCompat.PRIORITY_DEFAULT; -import static androidx.core.app.NotificationCompat.PRIORITY_MAX; -import static pl.szczodrzynski.edziennik.sync.SyncService.ACTION_CANCEL; - -public class Notifier { - - private static final String TAG = "Notifier"; - public static final int ID_GET_DATA = 1337000; - public static final int ID_GET_DATA_ERROR = 1337001; - private static String CHANNEL_GET_DATA_NAME; - private static String CHANNEL_GET_DATA_DESC; - private static final String GROUP_KEY_GET_DATA = "pl.szczodrzynski.edziennik.GET_DATA"; - - private static final int ID_NOTIFICATIONS = 1337002; - private static String CHANNEL_NOTIFICATIONS_NAME; - private static String CHANNEL_NOTIFICATIONS_DESC; - public static final String GROUP_KEY_NOTIFICATIONS = "pl.szczodrzynski.edziennik.NOTIFICATIONS"; - - private static final int ID_NOTIFICATIONS_QUIET = 1337002; - private static String CHANNEL_NOTIFICATIONS_QUIET_NAME; - private static String CHANNEL_NOTIFICATIONS_QUIET_DESC; - public static final String GROUP_KEY_NOTIFICATIONS_QUIET = "pl.szczodrzynski.edziennik.NOTIFICATIONS_QUIET"; - - private static final int ID_UPDATES = 1337003; - private static String CHANNEL_UPDATES_NAME; - private static String CHANNEL_UPDATES_DESC; - private static final String GROUP_KEY_UPDATES = "pl.szczodrzynski.edziennik.UPDATES"; - - private App app; - private NotificationManager notificationManager; - private NotificationCompat.Builder getDataNotificationBuilder; - private int notificationColor; - - Notifier(App _app) { - this.app = _app; - - CHANNEL_GET_DATA_NAME = app.getString(R.string.notification_channel_get_data_name); - CHANNEL_GET_DATA_DESC = app.getString(R.string.notification_channel_get_data_desc); - CHANNEL_NOTIFICATIONS_NAME = app.getString(R.string.notification_channel_notifications_name); - CHANNEL_NOTIFICATIONS_DESC = app.getString(R.string.notification_channel_notifications_desc); - CHANNEL_NOTIFICATIONS_QUIET_NAME = app.getString(R.string.notification_channel_notifications_quiet_name); - CHANNEL_NOTIFICATIONS_QUIET_DESC = app.getString(R.string.notification_channel_notifications_quiet_desc); - CHANNEL_UPDATES_NAME = app.getString(R.string.notification_channel_updates_name); - CHANNEL_UPDATES_DESC = app.getString(R.string.notification_channel_updates_desc); - - notificationColor = ContextCompat.getColor(app.getContext(), R.color.colorPrimary); - notificationManager = (NotificationManager) app.getSystemService(Context.NOTIFICATION_SERVICE); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - NotificationChannel channelGetData = new NotificationChannel(GROUP_KEY_GET_DATA, CHANNEL_GET_DATA_NAME, NotificationManager.IMPORTANCE_LOW); - channelGetData.setDescription(CHANNEL_GET_DATA_DESC); - notificationManager.createNotificationChannel(channelGetData); - - NotificationChannel channelNotifications = new NotificationChannel(GROUP_KEY_NOTIFICATIONS, CHANNEL_NOTIFICATIONS_NAME, NotificationManager.IMPORTANCE_HIGH); - channelNotifications.setDescription(CHANNEL_NOTIFICATIONS_DESC); - channelNotifications.enableLights(true); - channelNotifications.setLightColor(notificationColor); - notificationManager.createNotificationChannel(channelNotifications); - - NotificationChannel channelNotificationsQuiet = new NotificationChannel(GROUP_KEY_NOTIFICATIONS_QUIET, CHANNEL_NOTIFICATIONS_QUIET_NAME, NotificationManager.IMPORTANCE_DEFAULT); - channelNotificationsQuiet.setDescription(CHANNEL_NOTIFICATIONS_QUIET_DESC); - channelNotificationsQuiet.setSound(null, null); - channelNotificationsQuiet.enableVibration(false); - notificationManager.createNotificationChannel(channelNotificationsQuiet); - - NotificationChannel channelUpdates = new NotificationChannel(GROUP_KEY_UPDATES, CHANNEL_UPDATES_NAME, NotificationManager.IMPORTANCE_HIGH); - channelUpdates.setDescription(CHANNEL_UPDATES_DESC); - notificationManager.createNotificationChannel(channelUpdates); - } - } - - public boolean shouldBeQuiet() { - long now = Time.getNow().getInMillis(); - long start = app.appConfig.quietHoursStart; - long end = app.appConfig.quietHoursEnd; - if (start > end) { - end += 1000 * 60 * 60 * 24; - //Log.d(TAG, "Night passing"); - } - if (start > now) { - now += 1000 * 60 * 60 * 24; - //Log.d(TAG, "Now is smaller"); - } - //Log.d(TAG, "Start is "+start+", now is "+now+", end is "+end); - return app.appConfig.quietHoursStart > 0 && now >= start && now <= end; - } - - private int getNotificationDefaults() { - return (shouldBeQuiet() ? 0 : Notification.DEFAULT_ALL); - } - private String getNotificationGroup() { - return shouldBeQuiet() ? GROUP_KEY_NOTIFICATIONS_QUIET : GROUP_KEY_NOTIFICATIONS; - } - private int getNotificationPriority() { - return shouldBeQuiet() ? PRIORITY_DEFAULT : PRIORITY_MAX; - } - - /* _____ _ _____ _ - | __ \ | | / ____| | | - | | | | __ _| |_ __ _ | | __ ___| |_ - | | | |/ _` | __/ _` | | | |_ |/ _ \ __| - | |__| | (_| | || (_| | | |__| | __/ |_ - |_____/ \__,_|\__\__,_| \_____|\___|\_*/ - public Notification notificationGetDataShow(int maxProgress) { - Intent notificationIntent = new Intent(app.getContext(), SyncService.class); - notificationIntent.setAction(ACTION_CANCEL); - PendingIntent pendingIntent = PendingIntent.getService(app.getContext(), 0, - notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); - - getDataNotificationBuilder = new NotificationCompat.Builder(app, GROUP_KEY_GET_DATA) - .setSmallIcon(android.R.drawable.stat_sys_download) - .setColor(notificationColor) - .setContentTitle(app.getString(R.string.notification_get_data_title)) - .setContentText(app.getString(R.string.notification_get_data_text)) - .addAction(R.drawable.ic_notification, app.getString(R.string.notification_get_data_cancel), pendingIntent) - //.setGroup(GROUP_KEY_GET_DATA) - .setOngoing(true) - .setProgress(maxProgress, 0, false) - .setTicker(app.getString(R.string.notification_get_data_summary)) - .setPriority(NotificationCompat.PRIORITY_LOW); - return getDataNotificationBuilder.build(); - } - - public Notification notificationGetDataProgress(int progress, int maxProgress) { - getDataNotificationBuilder.setProgress(maxProgress, progress, false); - return getDataNotificationBuilder.build(); - } - - public Notification notificationGetDataAction(int stringResId) { - getDataNotificationBuilder.setContentTitle(app.getString(R.string.sync_action_format, app.getString(stringResId))); - return getDataNotificationBuilder.build(); - } - - public Notification notificationGetDataProfile(String profileName) { - getDataNotificationBuilder.setContentText(profileName); - return getDataNotificationBuilder.build(); - } - - public Notification notificationGetDataError(String profileName, String error, int failedProfileId) { - Intent notificationIntent = new Intent(app.getContext(), Notifier.GetDataRetryService.class); - notificationIntent.putExtra("failedProfileId", failedProfileId); - PendingIntent pendingIntent = PendingIntent.getService(app.getContext(), 0, - notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); - - getDataNotificationBuilder.mActions.clear(); - /*try { - //Use reflection clean up old actions - Field f = getDataNotificationBuilder.getClass().getDeclaredField("mActions"); - f.setAccessible(true); - f.set(getDataNotificationBuilder, new ArrayList()); - } catch (Exception e) { - e.printStackTrace(); - }*/ - - getDataNotificationBuilder.setProgress(0, 0, false) - .setTicker(app.getString(R.string.notification_get_data_error_summary)) - .setSmallIcon(android.R.drawable.stat_sys_warning) - .addAction(R.drawable.ic_notification, app.getString(R.string.notification_get_data_once_again), pendingIntent) - .setContentTitle(app.getString(R.string.notification_get_data_error_title, profileName)) - .setContentText(error) - .setStyle(new NotificationCompat.BigTextStyle().bigText(error)) - .setOngoing(false); - return getDataNotificationBuilder.build(); - } - - public void notificationPost(int id, Notification notification) { - notificationManager.notify(id, notification); - } - - public void notificationCancel(int id) { - notificationManager.cancel(id); - } - - //public void notificationGetDataHide() { - // notificationManager.cancel(ID_GET_DATA); - // } - - public static class GetDataRetryService extends IntentService { - private static final String TAG = "Notifier/GetDataRetry"; - - public GetDataRetryService() { - super(Notifier.GetDataRetryService.class.getSimpleName()); - } - - @Override - protected void onHandleIntent(Intent intent) { - SyncJob.run((App) getApplication(), intent.getExtras().getInt("failedProfileId", -1), -1); - NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - assert notificationManager != null; - notificationManager.cancel(ID_GET_DATA_ERROR); - } - } - - /* _ _ _ _ __ _ _ _ - | \ | | | | (_)/ _(_) | | (_) - | \| | ___ | |_ _| |_ _ ___ __ _| |_ _ ___ _ __ - | . ` |/ _ \| __| | _| |/ __/ _` | __| |/ _ \| '_ \ - | |\ | (_) | |_| | | | | (_| (_| | |_| | (_) | | | | - |_| \_|\___/ \__|_|_| |_|\___\__,_|\__|_|\___/|_| |*/ - public void add(pl.szczodrzynski.edziennik.utils.models.Notification notification) { - app.appConfig.notifications.add(notification); - } - - public void postAll(ProfileFull profile) { - Collections.sort(app.appConfig.notifications, (o1, o2) -> (o2.addedDate - o1.addedDate > 0) ? 1 : (o2.addedDate - o1.addedDate < 0) ? -1 : 0); - if (profile != null && !profile.getSyncNotifications()) - return; - - if (app.appConfig.notifications.size() > 40) { - app.appConfig.notifications.subList(40, app.appConfig.notifications.size() - 1).clear(); - } - - int unreadCount = 0; - List notificationList = new ArrayList<>(); - for (pl.szczodrzynski.edziennik.utils.models.Notification notification: app.appConfig.notifications) { - if (!notification.notified) { - notification.seen = false; - notification.notified = true; - unreadCount++; - if (notificationList.size() < 10) { - notificationList.add(notification); - } - } - else { - notification.seen = true; - } - } - - for (pl.szczodrzynski.edziennik.utils.models.Notification notification: notificationList) { - Intent intent = new Intent(app, MainActivity.class); - notification.fillIntent(intent); - PendingIntent pendingIntent = PendingIntent.getActivity(app, notification.id, intent, 0); - NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(app, getNotificationGroup()) - // title, text, type, date - .setContentTitle(notification.title) - .setContentText(notification.text) - .setSubText(pl.szczodrzynski.edziennik.utils.models.Notification.stringType(app, notification.type)) - .setWhen(notification.addedDate) - .setTicker(app.getString(R.string.notification_ticker_format, pl.szczodrzynski.edziennik.utils.models.Notification.stringType(app, notification.type))) - // icon, color, lights, priority - .setSmallIcon(R.drawable.ic_notification) - .setColor(notificationColor) - .setLights(0xFF00FFFF, 2000, 2000) - .setPriority(getNotificationPriority()) - // channel, group, style - .setChannelId(getNotificationGroup()) - .setGroup(getNotificationGroup()) - .setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY) - .setStyle(new NotificationCompat.BigTextStyle().bigText(notification.text)) - // intent, auto cancel - .setContentIntent(pendingIntent) - .setAutoCancel(true); - if (!shouldBeQuiet()) { - notificationBuilder.setDefaults(getNotificationDefaults()); - } - notificationManager.notify(notification.id, notificationBuilder.build()); - } - - if (notificationList.size() > 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - Intent intent = new Intent(app, MainActivity.class); - intent.setAction("android.intent.action.MAIN"); - intent.putExtra("fragmentId", MainActivity.DRAWER_ITEM_NOTIFICATIONS); - PendingIntent pendingIntent = PendingIntent.getActivity(app, ID_NOTIFICATIONS, - intent, 0); - - NotificationCompat.Builder groupBuilder = - new NotificationCompat.Builder(app, getNotificationGroup()) - .setSmallIcon(R.drawable.ic_notification) - .setColor(notificationColor) - .setContentTitle(app.getString(R.string.notification_new_notification_title_format, unreadCount)) - .setGroupSummary(true) - .setAutoCancel(true) - .setChannelId(getNotificationGroup()) - .setGroup(getNotificationGroup()) - .setLights(0xFF00FFFF, 2000, 2000) - .setPriority(getNotificationPriority()) - .setContentIntent(pendingIntent) - .setStyle(new NotificationCompat.BigTextStyle()); - if (!shouldBeQuiet()) { - groupBuilder.setDefaults(getNotificationDefaults()); - } - notificationManager.notify(ID_NOTIFICATIONS, groupBuilder.build()); - } - } - - /* _ _ _ _ - | | | | | | | | - | | | |_ __ __| | __ _| |_ ___ ___ - | | | | '_ \ / _` |/ _` | __/ _ \/ __| - | |__| | |_) | (_| | (_| | || __/\__ \ - \____/| .__/ \__,_|\__,_|\__\___||___/ - | | - |*/ - public void notificationUpdatesShow(String updateVersion, String updateUrl, String updateFilename) { - if (!app.appConfig.notifyAboutUpdates) - return; - Intent notificationIntent = new Intent(app.getContext(), BootReceiver.NotificationActionService.class) - .putExtra("update_version", updateVersion) - .putExtra("update_url", updateUrl) - .putExtra("update_filename", updateFilename); - - PendingIntent pendingIntent = PendingIntent.getService(app.getContext(), 0, - notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); - - NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(app, GROUP_KEY_UPDATES) - .setSmallIcon(android.R.drawable.stat_sys_download_done) - .setColor(notificationColor) - .setContentTitle(app.getString(R.string.notification_updates_title)) - .setContentText(app.getString(R.string.notification_updates_text, updateVersion)) - .setLights(0xFF00FFFF, 2000, 2000) - .setContentIntent(pendingIntent) - .setTicker(app.getString(R.string.notification_updates_summary)) - .setPriority(PRIORITY_MAX) - .setAutoCancel(true); - if (!shouldBeQuiet()) { - notificationBuilder.setDefaults(getNotificationDefaults()); - } - notificationManager.notify(ID_UPDATES, notificationBuilder.build()); - } - - public void notificationUpdatesHide() { - if (!app.appConfig.notifyAboutUpdates) - return; - notificationManager.cancel(ID_UPDATES); - } - - public void dump() { - for (pl.szczodrzynski.edziennik.utils.models.Notification notification: app.appConfig.notifications) { - Log.d(TAG, "Profile"+notification.profileId+" Notification from "+ Date.fromMillis(notification.addedDate).getFormattedString()+" "+ Time.fromMillis(notification.addedDate).getStringHMS()+" - "+notification.text); - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/WidgetTimetable.java b/app/src/main/java/pl/szczodrzynski/edziennik/WidgetTimetable.java deleted file mode 100644 index 36296e39..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/WidgetTimetable.java +++ /dev/null @@ -1,450 +0,0 @@ -package pl.szczodrzynski.edziennik; - -import android.app.PendingIntent; -import android.appwidget.AppWidgetManager; -import android.appwidget.AppWidgetProvider; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.PorterDuff; -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; -import android.net.Uri; -import android.os.Build; -import android.util.SparseArray; -import android.view.View; -import android.widget.RemoteViews; - -import com.mikepenz.iconics.IconicsColor; -import com.mikepenz.iconics.IconicsDrawable; -import com.mikepenz.iconics.IconicsSize; -import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -import pl.szczodrzynski.edziennik.data.db.modules.events.EventFull; -import pl.szczodrzynski.edziennik.data.db.modules.lessons.LessonChange; -import pl.szczodrzynski.edziennik.data.db.modules.lessons.LessonFull; -import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile; -import pl.szczodrzynski.edziennik.ui.modules.home.HomeFragment; -import pl.szczodrzynski.edziennik.utils.models.Date; -import pl.szczodrzynski.edziennik.utils.models.ItemWidgetTimetableModel; -import pl.szczodrzynski.edziennik.utils.models.Time; -import pl.szczodrzynski.edziennik.utils.models.Week; -import pl.szczodrzynski.edziennik.widgets.WidgetConfig; -import pl.szczodrzynski.edziennik.sync.SyncJob; -import pl.szczodrzynski.edziennik.widgets.timetable.LessonDetailsActivity; -import pl.szczodrzynski.edziennik.widgets.timetable.WidgetTimetableService; - -import static pl.szczodrzynski.edziennik.ExtensionsKt.filterOutArchived; -import static pl.szczodrzynski.edziennik.data.db.modules.events.Event.TYPE_HOMEWORK; -import static pl.szczodrzynski.edziennik.utils.Utils.bs; - - -public class WidgetTimetable extends AppWidgetProvider { - - - public static final String ACTION_SYNC_DATA = "ACTION_SYNC_DATA"; - private static final String TAG = "WidgetTimetable"; - private static int modeInt = 0; - - public WidgetTimetable() { - // Start the worker thread - //HandlerThread sWorkerThread = new HandlerThread("WidgetTimetable-worker"); - //sWorkerThread.start(); - //Handler sWorkerQueue = new Handler(sWorkerThread.getLooper()); - } - - public static SparseArray> timetables = null; - - @Override - public void onReceive(Context context, Intent intent) { - if (ACTION_SYNC_DATA.equals(intent.getAction())){ - SyncJob.run((App) context.getApplicationContext()); - } - super.onReceive(context, intent); - } - - public static PendingIntent getPendingSelfIntent(Context context, String action) { - Intent intent = new Intent(context, WidgetTimetable.class); - intent.setAction(action); - return getPendingSelfIntent(context, intent); - } - public static PendingIntent getPendingSelfIntent(Context context, Intent intent) { - return PendingIntent.getBroadcast(context, 0, intent, 0); - } - - public static Bitmap drawableToBitmap (Drawable drawable) { - - if (drawable instanceof BitmapDrawable) { - return ((BitmapDrawable)drawable).getBitmap(); - } - - Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); - Canvas canvas = new Canvas(bitmap); - drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); - drawable.draw(canvas); - - return bitmap; - } - - @Override - public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { - ComponentName thisWidget = new ComponentName(context, WidgetTimetable.class); - - timetables = new SparseArray<>(); - //timetables.clear(); - - App app = (App)context.getApplicationContext(); - - int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget); - // There may be multiple widgets active, so update all of them - for (int appWidgetId : allWidgetIds) { - - //d(TAG, "thr "+Thread.currentThread().getName()); - - WidgetConfig widgetConfig = app.appConfig.widgetTimetableConfigs.get(appWidgetId); - if (widgetConfig == null) { - widgetConfig = new WidgetConfig(app.profileFirstId()); - app.appConfig.widgetTimetableConfigs.put(appWidgetId, widgetConfig); - app.appConfig.savePending = true; - } - - RemoteViews views; - if (widgetConfig.bigStyle) { - views = new RemoteViews(context.getPackageName(), widgetConfig.darkTheme ? R.layout.widget_timetable_dark_big : R.layout.widget_timetable_big); - } - else { - views = new RemoteViews(context.getPackageName(), widgetConfig.darkTheme ? R.layout.widget_timetable_dark : R.layout.widget_timetable); - } - - PorterDuff.Mode mode = PorterDuff.Mode.DST_IN; - /*if (widgetConfig.darkTheme) { - switch (modeInt) { - case 0: - mode = PorterDuff.Mode.ADD; - d(TAG, "ADD"); - break; - case 1: - mode = PorterDuff.Mode.DST_ATOP; - d(TAG, "DST_ATOP"); - break; - case 2: - mode = PorterDuff.Mode.DST_IN; - d(TAG, "DST_IN"); - break; - case 3: - mode = PorterDuff.Mode.DST_OUT; - d(TAG, "DST_OUT"); - break; - case 4: - mode = PorterDuff.Mode.DST_OVER; - d(TAG, "DST_OVER"); - break; - case 5: - mode = PorterDuff.Mode.LIGHTEN; - d(TAG, "LIGHTEN"); - break; - case 6: - mode = PorterDuff.Mode.MULTIPLY; - d(TAG, "MULTIPLY"); - break; - case 7: - mode = PorterDuff.Mode.OVERLAY; - d(TAG, "OVERLAY"); - break; - case 8: - mode = PorterDuff.Mode.SCREEN; - d(TAG, "SCREEN"); - break; - case 9: - mode = PorterDuff.Mode.SRC_ATOP; - d(TAG, "SRC_ATOP"); - break; - case 10: - mode = PorterDuff.Mode.SRC_IN; - d(TAG, "SRC_IN"); - break; - case 11: - mode = PorterDuff.Mode.SRC_OUT; - d(TAG, "SRC_OUT"); - break; - case 12: - mode = PorterDuff.Mode.SRC_OVER; - d(TAG, "SRC_OVER"); - break; - case 13: - mode = PorterDuff.Mode.XOR; - d(TAG, "XOR"); - break; - default: - modeInt = 0; - mode = PorterDuff.Mode.ADD; - d(TAG, "ADD"); - break; - } - }*/ - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { - // this code seems to crash the launcher on >= P - float transparency = widgetConfig.opacity; //0...1 - long colorFilter = 0x01000000L * (long) (255f * transparency); - try { - final Method[] declaredMethods = Class.forName("android.widget.RemoteViews").getDeclaredMethods(); - final int len = declaredMethods.length; - if (len > 0) { - for (int m = 0; m < len; m++) { - final Method method = declaredMethods[m]; - if (method.getName().equals("setDrawableParameters")) { - method.setAccessible(true); - method.invoke(views, R.id.widgetTimetableListView, true, -1, (int) colorFilter, mode, -1); - method.invoke(views, R.id.widgetTimetableHeader, true, -1, (int) colorFilter, mode, -1); - break; - } - } - } - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } - } - - Intent refreshIntent = new Intent(context, WidgetTimetable.class); - refreshIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); - refreshIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds); - PendingIntent pendingRefreshIntent = PendingIntent.getBroadcast(context, - 0, refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT); - views.setOnClickPendingIntent(R.id.widgetTimetableRefresh, pendingRefreshIntent); - - views.setOnClickPendingIntent(R.id.widgetTimetableSync, WidgetTimetable.getPendingSelfIntent(context, ACTION_SYNC_DATA)); - - views.setImageViewBitmap(R.id.widgetTimetableRefresh, new IconicsDrawable(context, CommunityMaterial.Icon2.cmd_refresh) - .color(IconicsColor.colorInt(Color.WHITE)) - .size(IconicsSize.dp(widgetConfig.bigStyle ? 24 : 16)).toBitmap()); - - views.setImageViewBitmap(R.id.widgetTimetableSync, new IconicsDrawable(context, CommunityMaterial.Icon2.cmd_sync) - .color(IconicsColor.colorInt(Color.WHITE)) - .size(IconicsSize.dp(widgetConfig.bigStyle ? 24 : 16)).toBitmap()); - - boolean unified = widgetConfig.profileId == -1; - - List profileList = new ArrayList<>(); - if (unified) { - profileList = app.db.profileDao().getAllNow(); - filterOutArchived(profileList); - } - else { - Profile profile = app.db.profileDao().getByIdNow(widgetConfig.profileId); - if (profile != null) { - profileList.add(profile); - } - } - - //d(TAG, "Profiles: "+ Arrays.toString(profileList.toArray())); - - if (profileList == null || profileList.size() == 0) { - views.setViewVisibility(R.id.widgetTimetableLoading, View.VISIBLE); - views.setTextViewText(R.id.widgetTimetableLoading, app.getString(R.string.widget_timetable_profile_doesnt_exist)); - } - else { - views.setViewVisibility(R.id.widgetTimetableLoading, View.GONE); - //Register profile; - - long bellSyncDiffMillis = 0; - if (app.appConfig.bellSyncDiff != null) { - bellSyncDiffMillis = app.appConfig.bellSyncDiff.hour * 60 * 60 * 1000 + app.appConfig.bellSyncDiff.minute * 60 * 1000 + app.appConfig.bellSyncDiff.second * 1000; - bellSyncDiffMillis *= app.appConfig.bellSyncMultiplier; - bellSyncDiffMillis *= -1; - } - - List lessonList = new ArrayList<>(); - - Time syncedNow = Time.fromMillis(Time.getNow().getInMillis() + bellSyncDiffMillis); - - Date today = Date.getToday(); - - int openProfileId = -1; - Date displayingDate = null; - int displayingWeekDay = 0; - if (unified) { - views.setTextViewText(R.id.widgetTimetableSubtitle, app.getString(R.string.widget_timetable_title_unified)); - } - else { - views.setTextViewText(R.id.widgetTimetableSubtitle, profileList.get(0).getName()); - openProfileId = profileList.get(0).getId(); - } - - List lessons = app.db.lessonDao().getAllWeekNow(unified ? -1 : openProfileId, today.clone().stepForward(0, 0, -today.getWeekDay()), today); - - int scrollPos = 0; - - for (Profile profile: profileList) { - Date profileDisplayingDate = HomeFragment.findDateWithLessons(profile.getId(), lessons, syncedNow, 1); - int profileDisplayingWeekDay = profileDisplayingDate.getWeekDay(); - int dayDiff = Date.diffDays(profileDisplayingDate, Date.getToday()); - - //d(TAG, "For profile "+profile.name+" displayingDate is "+profileDisplayingDate.getStringY_m_d()); - if (displayingDate == null || profileDisplayingDate.getValue() < displayingDate.getValue()) { - displayingDate = profileDisplayingDate; - displayingWeekDay = profileDisplayingWeekDay; - //d(TAG, "Setting as global dd"); - if (dayDiff == 0) { - views.setTextViewText(R.id.widgetTimetableTitle, app.getString(R.string.day_today_format, Week.getFullDayName(displayingWeekDay))); - } else if (dayDiff == 1) { - views.setTextViewText(R.id.widgetTimetableTitle, app.getString(R.string.day_tomorrow_format, Week.getFullDayName(displayingWeekDay))); - } else { - views.setTextViewText(R.id.widgetTimetableTitle, Week.getFullDayName(displayingWeekDay) + " " + profileDisplayingDate.getStringDm()); - } - } - } - - for (Profile profile: profileList) { - int pos = 0; - - List events = app.db.eventDao().getAllByDateNow(profile.getId(), displayingDate); - if (events == null) - events = new ArrayList<>(); - - if (unified) { - ItemWidgetTimetableModel separator = new ItemWidgetTimetableModel(); - separator.profileId = profile.getId(); - separator.bigStyle = widgetConfig.bigStyle; - separator.darkTheme = widgetConfig.darkTheme; - separator.separatorProfileName = profile.getName(); - lessonList.add(separator); - } - - for (LessonFull lesson : lessons) { - //d(TAG, "Profile "+profile.id+" Lesson profileId "+lesson.profileId+" weekDay "+lesson.weekDay+", "+lesson); - if (profile.getId() != lesson.profileId || displayingWeekDay != lesson.weekDay) - continue; - //d(TAG, "Not skipped"); - ItemWidgetTimetableModel model = new ItemWidgetTimetableModel(); - - model.bigStyle = widgetConfig.bigStyle; - model.darkTheme = widgetConfig.darkTheme; - - model.profileId = profile.getId(); - - model.lessonDate = displayingDate; - model.startTime = lesson.startTime; - model.endTime = lesson.endTime; - - model.lessonPassed = (syncedNow.getValue() > lesson.endTime.getValue()) && displayingWeekDay == Week.getTodayWeekDay(); - model.lessonCurrent = (Time.inRange(lesson.startTime, lesson.endTime, syncedNow)) && displayingWeekDay == Week.getTodayWeekDay(); - - if (model.lessonCurrent) { - scrollPos = pos; - } else if (model.lessonPassed) { - scrollPos = pos + 1; - } - pos++; - - model.subjectName = bs(lesson.subjectLongName); - model.classroomName = lesson.classroomName; - - model.bellSyncDiffMillis = bellSyncDiffMillis; - - if (lesson.changeId != 0) { - if (lesson.changeType == LessonChange.TYPE_CHANGE) { - model.lessonChange = true; - if (lesson.changedClassroomName()) { - model.newClassroomName = lesson.changeClassroomName; - } - - if (lesson.changedSubjectLongName()) { - model.newSubjectName = lesson.changeSubjectLongName; - } - } - if (lesson.changeType == LessonChange.TYPE_CANCELLED) { - model.lessonCancelled = true; - } - } - - for (EventFull event : events) { - if (event.startTime == null) - continue; - if (event.eventDate.getValue() == displayingDate.getValue() - && event.startTime.getValue() == lesson.startTime.getValue()) { - model.eventColors.add(event.type == TYPE_HOMEWORK ? ItemWidgetTimetableModel.EVENT_COLOR_HOMEWORK : event.getColor()); - } - } - - lessonList.add(model); - } - } - - if (lessonList.size() == 0) { - views.setViewVisibility(R.id.widgetTimetableLoading, View.VISIBLE); - views.setRemoteAdapter(R.id.widgetTimetableListView, new Intent()); - views.setTextViewText(R.id.widgetTimetableLoading, app.getString(R.string.widget_timetable_no_lessons)); - appWidgetManager.updateAppWidget(appWidgetId, views); - } - else { - views.setViewVisibility(R.id.widgetTimetableLoading, View.GONE); - - timetables.put(appWidgetId, lessonList); - //WidgetTimetableListProvider.widgetsLessons.put(appWidgetId, lessons); - //views.setRemoteAdapter(R.id.widgetTimetableListView, new Intent()); - Intent listIntent = new Intent(context, WidgetTimetableService.class); - listIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); - listIntent.setData(Uri.parse(listIntent.toUri(Intent.URI_INTENT_SCHEME))); - views.setRemoteAdapter(R.id.widgetTimetableListView, listIntent); - - // template to handle the click listener for each item - Intent intentTemplate = new Intent(context, LessonDetailsActivity.class); - // Old activities shouldn't be in the history stack - intentTemplate.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); - PendingIntent pendingIntentTimetable = PendingIntent.getActivity(context, - 0, - intentTemplate, - 0); - views.setPendingIntentTemplate(R.id.widgetTimetableListView, pendingIntentTimetable); - - Intent openIntent = new Intent(context, MainActivity.class); - openIntent.setAction("android.intent.action.MAIN"); - if (!unified) { - openIntent.putExtra("profileId", openProfileId); - openIntent.putExtra("timetableDate", displayingDate.getValue()); - } - openIntent.putExtra("fragmentId", MainActivity.DRAWER_ITEM_TIMETABLE); - PendingIntent pendingOpenIntent = PendingIntent.getActivity(context, - appWidgetId, openIntent, PendingIntent.FLAG_UPDATE_CURRENT); - views.setOnClickPendingIntent(R.id.widgetTimetableHeader, pendingOpenIntent); - - if (!unified) - views.setScrollPosition(R.id.widgetTimetableListView, scrollPos); - } - } - - appWidgetManager.updateAppWidget(appWidgetId, views); - appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.widgetTimetableListView); - } - //modeInt++; - } - - @Override - public void onEnabled(Context context) { - // Enter relevant functionality for when the first widget is created - } - - @Override - public void onDeleted(Context context, int[] appWidgetIds) { - App app = (App) context.getApplicationContext(); - for (int appWidgetId: appWidgetIds) { - app.appConfig.widgetTimetableConfigs.remove(appWidgetId); - } - app.saveConfig("widgetTimetableConfigs"); - } -} - diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/AbstractConfig.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/AbstractConfig.kt new file mode 100644 index 00000000..d597a119 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/AbstractConfig.kt @@ -0,0 +1,9 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-11-27. + */ + +package pl.szczodrzynski.edziennik.config + +interface AbstractConfig { + fun set(key: String, value: String?) +} \ No newline at end of file diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/Config.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/Config.kt new file mode 100644 index 00000000..e29d93ad --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/Config.kt @@ -0,0 +1,155 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-11-26. + */ + +package pl.szczodrzynski.edziennik.config + +import com.google.gson.JsonObject +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.BuildConfig +import pl.szczodrzynski.edziennik.config.db.ConfigEntry +import pl.szczodrzynski.edziennik.config.utils.* +import pl.szczodrzynski.edziennik.data.api.szkolny.response.Update +import pl.szczodrzynski.edziennik.data.db.AppDb +import kotlin.coroutines.CoroutineContext + +class Config(val db: AppDb) : CoroutineScope, AbstractConfig { + companion object { + const val DATA_VERSION = 12 + } + + private val job = Job() + override val coroutineContext: CoroutineContext + get() = job + Dispatchers.Default + + val values: HashMap = hashMapOf() + + val ui by lazy { ConfigUI(this) } + val sync by lazy { ConfigSync(this) } + val timetable by lazy { ConfigTimetable(this) } + val grades by lazy { ConfigGrades(this) } + + private var mDataVersion: Int? = null + var dataVersion: Int + get() { mDataVersion = mDataVersion ?: values.get("dataVersion", 0); return mDataVersion ?: 0 } + set(value) { set("dataVersion", value); mDataVersion = value } + + private var mHash: String? = null + var hash: String + get() { mHash = mHash ?: values.get("hash", ""); return mHash ?: "" } + set(value) { set("hash", value); mHash = value } + + private var mLastProfileId: Int? = null + var lastProfileId: Int + get() { mLastProfileId = mLastProfileId ?: values.get("lastProfileId", 0); return mLastProfileId ?: 0 } + set(value) { set("lastProfileId", value); mLastProfileId = value } + + private var mUpdatesChannel: String? = null + var updatesChannel: String + get() { mUpdatesChannel = mUpdatesChannel ?: values.get("updatesChannel", "release"); return mUpdatesChannel ?: "release" } + set(value) { set("updatesChannel", value); mUpdatesChannel = value } + private var mUpdate: Update? = null + var update: Update? + get() { mUpdate = mUpdate ?: values.get("update", null as Update?); return mUpdate ?: null as Update? } + set(value) { set("update", value); mUpdate = value } + + private var mAppVersion: Int? = null + var appVersion: Int + get() { mAppVersion = mAppVersion ?: values.get("appVersion", BuildConfig.VERSION_CODE); return mAppVersion ?: BuildConfig.VERSION_CODE } + set(value) { set("appVersion", value); mAppVersion = value } + + private var mLoginFinished: Boolean? = null + var loginFinished: Boolean + get() { mLoginFinished = mLoginFinished ?: values.get("loginFinished", false); return mLoginFinished ?: false } + set(value) { set("loginFinished", value); mLoginFinished = value } + + private var mPrivacyPolicyAccepted: Boolean? = null + var privacyPolicyAccepted: Boolean + get() { mPrivacyPolicyAccepted = mPrivacyPolicyAccepted ?: values.get("privacyPolicyAccepted", false); return mPrivacyPolicyAccepted ?: false } + set(value) { set("privacyPolicyAccepted", value); mPrivacyPolicyAccepted = value } + + private var mDevMode: Boolean? = null + var devMode: Boolean? + get() { mDevMode = mDevMode ?: values.getBooleanOrNull("debugMode"); return mDevMode } + set(value) { set("debugMode", value?.toString()); mDevMode = value } + + private var mEnableChucker: Boolean? = null + var enableChucker: Boolean? + get() { mEnableChucker = mEnableChucker ?: values.getBooleanOrNull("enableChucker"); return mEnableChucker } + set(value) { set("enableChucker", value?.toString()); mEnableChucker = value } + + private var mDevModePassword: String? = null + var devModePassword: String? + get() { mDevModePassword = mDevModePassword ?: values.get("devModePassword", null as String?); return mDevModePassword } + set(value) { set("devModePassword", value); mDevModePassword = value } + + private var mAppInstalledTime: Long? = null + var appInstalledTime: Long + get() { mAppInstalledTime = mAppInstalledTime ?: values.get("appInstalledTime", 0L); return mAppInstalledTime ?: 0L } + set(value) { set("appInstalledTime", value); mAppInstalledTime = value } + + private var mAppRateSnackbarTime: Long? = null + var appRateSnackbarTime: Long + get() { mAppRateSnackbarTime = mAppRateSnackbarTime ?: values.get("appRateSnackbarTime", 0L); return mAppRateSnackbarTime ?: 0L } + set(value) { set("appRateSnackbarTime", value); mAppRateSnackbarTime = value } + + private var mRunSync: Boolean? = null + var runSync: Boolean + get() { mRunSync = mRunSync ?: values.get("runSync", false); return mRunSync ?: false } + set(value) { set("runSync", value); mRunSync = value } + + private var mWidgetConfigs: JsonObject? = null + var widgetConfigs: JsonObject + get() { mWidgetConfigs = mWidgetConfigs ?: values.get("widgetConfigs", JsonObject()); return mWidgetConfigs ?: JsonObject() } + set(value) { set("widgetConfigs", value); mWidgetConfigs = value } + + private var mArchiverEnabled: Boolean? = null + var archiverEnabled: Boolean + get() { mArchiverEnabled = mArchiverEnabled ?: values.get("archiverEnabled", true); return mArchiverEnabled ?: true } + set(value) { set("archiverEnabled", value); mArchiverEnabled = value } + + private var mValidation: String? = null + var validation: String? + get() { mValidation = mValidation ?: values["buildValidation"]; return mValidation } + set(value) { set("buildValidation", value); mValidation = value } + + private var mApiInvalidCert: String? = null + var apiInvalidCert: String? + get() { mApiInvalidCert = mApiInvalidCert ?: values["apiInvalidCert"]; return mApiInvalidCert } + set(value) { set("apiInvalidCert", value); mApiInvalidCert = value } + + private var mApiAvailabilityCheck: Boolean? = null + var apiAvailabilityCheck: Boolean + get() { mApiAvailabilityCheck = mApiAvailabilityCheck ?: values.get("apiAvailabilityCheck", true); return mApiAvailabilityCheck ?: true } + set(value) { set("apiAvailabilityCheck", value); mApiAvailabilityCheck = value } + + private var rawEntries: List = db.configDao().getAllNow() + private val profileConfigs: HashMap = hashMapOf() + init { + rawEntries.toHashMap(-1, values) + } + fun migrate(app: App) { + if (dataVersion < DATA_VERSION) + ConfigMigration(app, this) + } + fun getFor(profileId: Int): ProfileConfig { + return profileConfigs[profileId] ?: ProfileConfig(db, profileId, db.configDao().getAllNow(profileId)).also { + profileConfigs[profileId] = it + } + } + fun forProfile() = getFor(App.profileId) + + fun setProfile(profileId: Int) { + } + + override fun set(key: String, value: String?) { + values[key] = value + launch { + db.configDao().add(ConfigEntry(-1, key, value)) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigGrades.kt new file mode 100644 index 00000000..267ec322 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigGrades.kt @@ -0,0 +1,16 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-11-26. + */ + +package pl.szczodrzynski.edziennik.config + +import pl.szczodrzynski.edziennik.config.utils.get +import pl.szczodrzynski.edziennik.config.utils.set +import pl.szczodrzynski.edziennik.utils.managers.GradesManager + +class ConfigGrades(private val config: Config) { + private var mOrderBy: Int? = null + var orderBy: Int + get() { mOrderBy = mOrderBy ?: config.values.get("gradesOrderBy", 0); return mOrderBy ?: GradesManager.ORDER_BY_DATE_DESC } + set(value) { config.set("gradesOrderBy", value); mOrderBy = value } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigSync.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigSync.kt new file mode 100644 index 00000000..387e5cf7 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigSync.kt @@ -0,0 +1,142 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-11-26. + */ + +package pl.szczodrzynski.edziennik.config + +import com.google.gson.Gson +import com.google.gson.reflect.TypeToken +import pl.szczodrzynski.edziennik.BuildConfig +import pl.szczodrzynski.edziennik.config.utils.get +import pl.szczodrzynski.edziennik.config.utils.getIntList +import pl.szczodrzynski.edziennik.config.utils.set +import pl.szczodrzynski.edziennik.config.utils.setMap +import pl.szczodrzynski.edziennik.data.api.szkolny.response.RegisterAvailabilityStatus +import pl.szczodrzynski.edziennik.utils.models.Time + +class ConfigSync(private val config: Config) { + private val gson = Gson() + + private var mDontShowAppManagerDialog: Boolean? = null + var dontShowAppManagerDialog: Boolean + get() { mDontShowAppManagerDialog = mDontShowAppManagerDialog ?: config.values.get("dontShowAppManagerDialog", false); return mDontShowAppManagerDialog ?: false } + set(value) { config.set("dontShowAppManagerDialog", value); mDontShowAppManagerDialog = value } + + private var mSyncEnabled: Boolean? = null + var enabled: Boolean + get() { mSyncEnabled = mSyncEnabled ?: config.values.get("syncEnabled", true); return mSyncEnabled ?: true } + set(value) { config.set("syncEnabled", value); mSyncEnabled = value } + + private var mWebPushEnabled: Boolean? = null + var webPushEnabled: Boolean + get() { mWebPushEnabled = mWebPushEnabled ?: config.values.get("webPushEnabled", true); return mWebPushEnabled ?: true } + set(value) { config.set("webPushEnabled", value); mWebPushEnabled = value } + + private var mSyncOnlyWifi: Boolean? = null + var onlyWifi: Boolean + get() { mSyncOnlyWifi = mSyncOnlyWifi ?: config.values.get("syncOnlyWifi", false); return mSyncOnlyWifi ?: notifyAboutUpdates } + set(value) { config.set("syncOnlyWifi", value); mSyncOnlyWifi = value } + + private var mSyncInterval: Int? = null + var interval: Int + get() { mSyncInterval = mSyncInterval ?: config.values.get("syncInterval", 60*60); return mSyncInterval ?: 60*60 } + set(value) { config.set("syncInterval", value); mSyncInterval = value } + + private var mNotifyAboutUpdates: Boolean? = null + var notifyAboutUpdates: Boolean + get() { mNotifyAboutUpdates = mNotifyAboutUpdates ?: config.values.get("notifyAboutUpdates", true); return mNotifyAboutUpdates ?: true } + set(value) { config.set("notifyAboutUpdates", value); mNotifyAboutUpdates = value } + + private var mLastAppSync: Long? = null + var lastAppSync: Long + get() { mLastAppSync = mLastAppSync ?: config.values.get("lastAppSync", 0L); return mLastAppSync ?: 0L } + set(value) { config.set("lastAppSync", value); mLastAppSync = value } + + /* ____ _ _ _ + / __ \ (_) | | | | + | | | |_ _ _ ___| |_ | |__ ___ _ _ _ __ ___ + | | | | | | | |/ _ \ __| | '_ \ / _ \| | | | '__/ __| + | |__| | |_| | | __/ |_ | | | | (_) | |_| | | \__ \ + \___\_\\__,_|_|\___|\__| |_| |_|\___/ \__,_|_| |__*/ + private var mQuietHoursEnabled: Boolean? = null + var quietHoursEnabled: Boolean + get() { mQuietHoursEnabled = mQuietHoursEnabled ?: config.values.get("quietHoursEnabled", false); return mQuietHoursEnabled ?: false } + set(value) { config.set("quietHoursEnabled", value); mQuietHoursEnabled = value } + + private var mQuietHoursStart: Time? = null + var quietHoursStart: Time? + get() { mQuietHoursStart = mQuietHoursStart ?: config.values.get("quietHoursStart", null as Time?); return mQuietHoursStart } + set(value) { config.set("quietHoursStart", value); mQuietHoursStart = value } + + private var mQuietHoursEnd: Time? = null + var quietHoursEnd: Time? + get() { mQuietHoursEnd = mQuietHoursEnd ?: config.values.get("quietHoursEnd", null as Time?); return mQuietHoursEnd } + set(value) { config.set("quietHoursEnd", value); mQuietHoursEnd = value } + + private var mQuietDuringLessons: Boolean? = null + var quietDuringLessons: Boolean + get() { mQuietDuringLessons = mQuietDuringLessons ?: config.values.get("quietDuringLessons", false); return mQuietDuringLessons ?: false } + set(value) { config.set("quietDuringLessons", value); mQuietDuringLessons = value } + + /* ______ _____ __ __ _______ _ + | ____/ ____| \/ | |__ __| | | + | |__ | | | \ / | | | ___ | | _____ _ __ ___ + | __|| | | |\/| | | |/ _ \| |/ / _ \ '_ \/ __| + | | | |____| | | | | | (_) | < __/ | | \__ \ + |_| \_____|_| |_| |_|\___/|_|\_\___|_| |_|__*/ + private var mTokenApp: String? = null + var tokenApp: String? + get() { mTokenApp = mTokenApp ?: config.values.get("tokenApp", null as String?); return mTokenApp } + set(value) { config.set("tokenApp", value); mTokenApp = value } + private var mTokenMobidziennik: String? = null + var tokenMobidziennik: String? + get() { mTokenMobidziennik = mTokenMobidziennik ?: config.values.get("tokenMobidziennik", null as String?); return mTokenMobidziennik } + set(value) { config.set("tokenMobidziennik", value); mTokenMobidziennik = value } + private var mTokenLibrus: String? = null + var tokenLibrus: String? + get() { mTokenLibrus = mTokenLibrus ?: config.values.get("tokenLibrus", null as String?); return mTokenLibrus } + set(value) { config.set("tokenLibrus", value); mTokenLibrus = value } + private var mTokenVulcan: String? = null + var tokenVulcan: String? + get() { mTokenVulcan = mTokenVulcan ?: config.values.get("tokenVulcan", null as String?); return mTokenVulcan } + set(value) { config.set("tokenVulcan", value); mTokenVulcan = value } + private var mTokenVulcanHebe: String? = null + var tokenVulcanHebe: String? + get() { mTokenVulcanHebe = mTokenVulcanHebe ?: config.values.get("tokenVulcanHebe", null as String?); return mTokenVulcanHebe } + set(value) { config.set("tokenVulcanHebe", value); mTokenVulcanHebe = value } + + private var mTokenMobidziennikList: List? = null + var tokenMobidziennikList: List + get() { mTokenMobidziennikList = mTokenMobidziennikList ?: config.values.getIntList("tokenMobidziennikList", listOf()); return mTokenMobidziennikList ?: listOf() } + set(value) { config.set("tokenMobidziennikList", value); mTokenMobidziennikList = value } + private var mTokenLibrusList: List? = null + var tokenLibrusList: List + get() { mTokenLibrusList = mTokenLibrusList ?: config.values.getIntList("tokenLibrusList", listOf()); return mTokenLibrusList ?: listOf() } + set(value) { config.set("tokenLibrusList", value); mTokenLibrusList = value } + private var mTokenVulcanList: List? = null + var tokenVulcanList: List + get() { mTokenVulcanList = mTokenVulcanList ?: config.values.getIntList("tokenVulcanList", listOf()); return mTokenVulcanList ?: listOf() } + set(value) { config.set("tokenVulcanList", value); mTokenVulcanList = value } + private var mTokenVulcanHebeList: List? = null + var tokenVulcanHebeList: List + get() { mTokenVulcanHebeList = mTokenVulcanHebeList ?: config.values.getIntList("tokenVulcanHebeList", listOf()); return mTokenVulcanHebeList ?: listOf() } + set(value) { config.set("tokenVulcanHebeList", value); mTokenVulcanHebeList = value } + + private var mRegisterAvailability: Map? = null + var registerAvailability: Map + get() { + val flavor = config.values.get("registerAvailabilityFlavor", null as String?) + if (BuildConfig.FLAVOR != flavor) + return mapOf() + + mRegisterAvailability = mRegisterAvailability ?: config.values.get("registerAvailability", null as String?)?.let { it -> + gson.fromJson(it, object: TypeToken>(){}.type) + } + return mRegisterAvailability ?: mapOf() + } + set(value) { + config.setMap("registerAvailability", value) + config.set("registerAvailabilityFlavor", BuildConfig.FLAVOR) + mRegisterAvailability = value + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigTimetable.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigTimetable.kt new file mode 100644 index 00000000..2418f1d3 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigTimetable.kt @@ -0,0 +1,26 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-11-26. + */ + +package pl.szczodrzynski.edziennik.config + +import pl.szczodrzynski.edziennik.config.utils.get +import pl.szczodrzynski.edziennik.config.utils.set +import pl.szczodrzynski.edziennik.utils.models.Time + +class ConfigTimetable(private val config: Config) { + private var mBellSyncMultiplier: Int? = null + var bellSyncMultiplier: Int + get() { mBellSyncMultiplier = mBellSyncMultiplier ?: config.values.get("bellSyncMultiplier", 0); return mBellSyncMultiplier ?: 0 } + set(value) { config.set("bellSyncMultiplier", value); mBellSyncMultiplier = value } + + private var mBellSyncDiff: Time? = null + var bellSyncDiff: Time? + get() { mBellSyncDiff = mBellSyncDiff ?: config.values.get("bellSyncDiff", null as Time?); return mBellSyncDiff } + set(value) { config.set("bellSyncDiff", value); mBellSyncDiff = value } + + private var mCountInSeconds: Boolean? = null + var countInSeconds: Boolean + get() { mCountInSeconds = mCountInSeconds ?: config.values.get("countInSeconds", false); return mCountInSeconds ?: false } + set(value) { config.set("countInSeconds", value); mCountInSeconds = value } +} \ No newline at end of file diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigUI.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigUI.kt new file mode 100644 index 00000000..f36652a1 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigUI.kt @@ -0,0 +1,61 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-11-26. + */ + +package pl.szczodrzynski.edziennik.config + +import pl.szczodrzynski.edziennik.config.utils.get +import pl.szczodrzynski.edziennik.config.utils.getIntList +import pl.szczodrzynski.edziennik.config.utils.set + +class ConfigUI(private val config: Config) { + private var mTheme: Int? = null + var theme: Int + get() { mTheme = mTheme ?: config.values.get("theme", 1); return mTheme ?: 1 } + set(value) { config.set("theme", value); mTheme = value } + + private var mLanguage: String? = null + var language: String? + get() { mLanguage = mLanguage ?: config.values.get("language", null as String?); return mLanguage } + set(value) { config.set("language", value); mLanguage = value } + + private var mHeaderBackground: String? = null + var headerBackground: String? + get() { mHeaderBackground = mHeaderBackground ?: config.values.get("headerBg", null as String?); return mHeaderBackground } + set(value) { config.set("headerBg", value); mHeaderBackground = value } + + private var mAppBackground: String? = null + var appBackground: String? + get() { mAppBackground = mAppBackground ?: config.values.get("appBg", null as String?); return mAppBackground } + set(value) { config.set("appBg", value); mAppBackground = value } + + private var mMiniMenuVisible: Boolean? = null + var miniMenuVisible: Boolean + get() { mMiniMenuVisible = mMiniMenuVisible ?: config.values.get("miniMenuVisible", false); return mMiniMenuVisible ?: false } + set(value) { config.set("miniMenuVisible", value); mMiniMenuVisible = value } + + private var mMiniMenuButtons: List? = null + var miniMenuButtons: List + get() { mMiniMenuButtons = mMiniMenuButtons ?: config.values.getIntList("miniMenuButtons", listOf()); return mMiniMenuButtons ?: listOf() } + set(value) { config.set("miniMenuButtons", value); mMiniMenuButtons = value } + + private var mOpenDrawerOnBackPressed: Boolean? = null + var openDrawerOnBackPressed: Boolean + get() { mOpenDrawerOnBackPressed = mOpenDrawerOnBackPressed ?: config.values.get("openDrawerOnBackPressed", false); return mOpenDrawerOnBackPressed ?: false } + set(value) { config.set("openDrawerOnBackPressed", value); mOpenDrawerOnBackPressed = value } + + private var mSnowfall: Boolean? = null + var snowfall: Boolean + get() { mSnowfall = mSnowfall ?: config.values.get("snowfall", false); return mSnowfall ?: false } + set(value) { config.set("snowfall", value); mSnowfall = value } + + private var mEggfall: Boolean? = null + var eggfall: Boolean + get() { mEggfall = mEggfall ?: config.values.get("eggfall", false); return mEggfall ?: false } + set(value) { config.set("eggfall", value); mEggfall = value } + + private var mBottomSheetOpened: Boolean? = null + var bottomSheetOpened: Boolean + get() { mBottomSheetOpened = mBottomSheetOpened ?: config.values.get("bottomSheetOpened", false); return mBottomSheetOpened ?: false } + set(value) { config.set("bottomSheetOpened", value); mBottomSheetOpened = value } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfig.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfig.kt new file mode 100644 index 00000000..6482634c --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfig.kt @@ -0,0 +1,60 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-11-27. + */ + +package pl.szczodrzynski.edziennik.config + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import pl.szczodrzynski.edziennik.config.db.ConfigEntry +import pl.szczodrzynski.edziennik.config.utils.ProfileConfigMigration +import pl.szczodrzynski.edziennik.config.utils.get +import pl.szczodrzynski.edziennik.config.utils.set +import pl.szczodrzynski.edziennik.config.utils.toHashMap +import pl.szczodrzynski.edziennik.data.db.AppDb +import kotlin.coroutines.CoroutineContext + +class ProfileConfig(val db: AppDb, val profileId: Int, rawEntries: List) : CoroutineScope, AbstractConfig { + companion object { + const val DATA_VERSION = 3 + } + + private val job = Job() + override val coroutineContext: CoroutineContext + get() = job + Dispatchers.Default + + val values: HashMap = hashMapOf() + + val grades by lazy { ProfileConfigGrades(this) } + val ui by lazy { ProfileConfigUI(this) } + val sync by lazy { ProfileConfigSync(this) } + val attendance by lazy { ProfileConfigAttendance(this) } + /* + val timetable by lazy { ConfigTimetable(this) } + val grades by lazy { ConfigGrades(this) }*/ + + private var mDataVersion: Int? = null + var dataVersion: Int + get() { mDataVersion = mDataVersion ?: values.get("dataVersion", 0); return mDataVersion ?: 0 } + set(value) { set("dataVersion", value); mDataVersion = value } + + private var mHash: String? = null + var hash: String + get() { mHash = mHash ?: values.get("hash", ""); return mHash ?: "" } + set(value) { set("hash", value); mHash = value } + + init { + rawEntries.toHashMap(profileId, values) + if (dataVersion < DATA_VERSION) + ProfileConfigMigration(this) + } + + override fun set(key: String, value: String?) { + values[key] = value + launch { + db.configDao().add(ConfigEntry(profileId, key, value)) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfigAttendance.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfigAttendance.kt new file mode 100644 index 00000000..326f5b16 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfigAttendance.kt @@ -0,0 +1,30 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-29. + */ + +package pl.szczodrzynski.edziennik.config + +import pl.szczodrzynski.edziennik.config.utils.get +import pl.szczodrzynski.edziennik.config.utils.set + +class ProfileConfigAttendance(private val config: ProfileConfig) { + private var mAttendancePageSelection: Int? = null + var attendancePageSelection: Int + get() { mAttendancePageSelection = mAttendancePageSelection ?: config.values.get("attendancePageSelection", 1); return mAttendancePageSelection ?: 1 } + set(value) { config.set("attendancePageSelection", value); mAttendancePageSelection = value } + + private var mUseSymbols: Boolean? = null + var useSymbols: Boolean + get() { mUseSymbols = mUseSymbols ?: config.values.get("useSymbols", false); return mUseSymbols ?: false } + set(value) { config.set("useSymbols", value); mUseSymbols = value } + + private var mGroupConsecutiveDays: Boolean? = null + var groupConsecutiveDays: Boolean + get() { mGroupConsecutiveDays = mGroupConsecutiveDays ?: config.values.get("groupConsecutiveDays", true); return mGroupConsecutiveDays ?: true } + set(value) { config.set("groupConsecutiveDays", value); mGroupConsecutiveDays = value } + + private var mShowPresenceInMonth: Boolean? = null + var showPresenceInMonth: Boolean + get() { mShowPresenceInMonth = mShowPresenceInMonth ?: config.values.get("showPresenceInMonth", false); return mShowPresenceInMonth ?: false } + set(value) { config.set("showPresenceInMonth", value); mShowPresenceInMonth = value } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfigGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfigGrades.kt new file mode 100644 index 00000000..6434aac7 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfigGrades.kt @@ -0,0 +1,57 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-11-27. + */ + +package pl.szczodrzynski.edziennik.config + +import pl.szczodrzynski.edziennik.config.utils.get +import pl.szczodrzynski.edziennik.config.utils.getFloat +import pl.szczodrzynski.edziennik.config.utils.set +import pl.szczodrzynski.edziennik.utils.managers.GradesManager.Companion.COLOR_MODE_WEIGHTED +import pl.szczodrzynski.edziennik.utils.managers.GradesManager.Companion.YEAR_ALL_GRADES + +class ProfileConfigGrades(private val config: ProfileConfig) { + private var mColorMode: Int? = null + var colorMode: Int + get() { mColorMode = mColorMode ?: config.values.get("gradesColorMode", COLOR_MODE_WEIGHTED); return mColorMode ?: COLOR_MODE_WEIGHTED } + set(value) { config.set("gradesColorMode", value); mColorMode = value } + + private var mYearAverageMode: Int? = null + var yearAverageMode: Int + get() { mYearAverageMode = mYearAverageMode ?: config.values.get("yearAverageMode", YEAR_ALL_GRADES); return mYearAverageMode ?: YEAR_ALL_GRADES } + set(value) { config.set("yearAverageMode", value); mYearAverageMode = value } + + private var mHideImproved: Boolean? = null + var hideImproved: Boolean + get() { mHideImproved = mHideImproved ?: config.values.get("hideImproved", false); return mHideImproved ?: false } + set(value) { config.set("hideImproved", value); mHideImproved = value } + + private var mAverageWithoutWeight: Boolean? = null + var averageWithoutWeight: Boolean + get() { mAverageWithoutWeight = mAverageWithoutWeight ?: config.values.get("averageWithoutWeight", true); return mAverageWithoutWeight ?: true } + set(value) { config.set("averageWithoutWeight", value); mAverageWithoutWeight = value } + + private var mPlusValue: Float? = null + var plusValue: Float? + get() { mPlusValue = mPlusValue ?: config.values.getFloat("plusValue"); return mPlusValue } + set(value) { config.set("plusValue", value); mPlusValue = value } + private var mMinusValue: Float? = null + var minusValue: Float? + get() { mMinusValue = mMinusValue ?: config.values.getFloat("minusValue"); return mMinusValue } + set(value) { config.set("minusValue", value); mMinusValue = value } + + private var mDontCountEnabled: Boolean? = null + var dontCountEnabled: Boolean + get() { mDontCountEnabled = mDontCountEnabled ?: config.values.get("dontCountEnabled", false); return mDontCountEnabled ?: false } + set(value) { config.set("dontCountEnabled", value); mDontCountEnabled = value } + + private var mDontCountGrades: List? = null + var dontCountGrades: List + get() { mDontCountGrades = mDontCountGrades ?: config.values.get("dontCountGrades", listOf()); return mDontCountGrades ?: listOf() } + set(value) { config.set("dontCountGrades", value); mDontCountGrades = value } + + private var mHideSticksFromOld: Boolean? = null + var hideSticksFromOld: Boolean + get() { mHideSticksFromOld = mHideSticksFromOld ?: config.values.get("hideSticksFromOld", false); return mHideSticksFromOld ?: false } + set(value) { config.set("hideSticksFromOld", value); mHideSticksFromOld = value } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfigSync.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfigSync.kt new file mode 100644 index 00000000..2012bc4b --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfigSync.kt @@ -0,0 +1,15 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-2-21. + */ + +package pl.szczodrzynski.edziennik.config + +import pl.szczodrzynski.edziennik.config.utils.getIntList +import pl.szczodrzynski.edziennik.config.utils.set + +class ProfileConfigSync(private val config: ProfileConfig) { + private var mNotificationFilter: List? = null + var notificationFilter: List + get() { mNotificationFilter = mNotificationFilter ?: config.values.getIntList("notificationFilter", listOf()); return mNotificationFilter ?: listOf() } + set(value) { config.set("notificationFilter", value); mNotificationFilter = value } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfigUI.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfigUI.kt new file mode 100644 index 00000000..187cb6bd --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfigUI.kt @@ -0,0 +1,72 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-1-19. + */ + +package pl.szczodrzynski.edziennik.config + +import pl.szczodrzynski.edziennik.config.utils.get +import pl.szczodrzynski.edziennik.config.utils.set +import pl.szczodrzynski.edziennik.data.db.entity.Profile.Companion.AGENDA_DEFAULT +import pl.szczodrzynski.edziennik.ui.home.HomeCardModel + +class ProfileConfigUI(private val config: ProfileConfig) { + private var mAgendaViewType: Int? = null + var agendaViewType: Int + get() { mAgendaViewType = mAgendaViewType ?: config.values.get("agendaViewType", 0); return mAgendaViewType ?: AGENDA_DEFAULT } + set(value) { config.set("agendaViewType", value); mAgendaViewType = value } + + private var mAgendaCompactMode: Boolean? = null + var agendaCompactMode: Boolean + get() { mAgendaCompactMode = mAgendaCompactMode ?: config.values.get("agendaCompactMode", false); return mAgendaCompactMode ?: false } + set(value) { config.set("agendaCompactMode", value); mAgendaCompactMode = value } + + private var mAgendaGroupByType: Boolean? = null + var agendaGroupByType: Boolean + get() { mAgendaGroupByType = mAgendaGroupByType ?: config.values.get("agendaGroupByType", false); return mAgendaGroupByType ?: false } + set(value) { config.set("agendaGroupByType", value); mAgendaGroupByType = value } + + private var mAgendaLessonChanges: Boolean? = null + var agendaLessonChanges: Boolean + get() { mAgendaLessonChanges = mAgendaLessonChanges ?: config.values.get("agendaLessonChanges", true); return mAgendaLessonChanges ?: true } + set(value) { config.set("agendaLessonChanges", value); mAgendaLessonChanges = value } + + private var mAgendaTeacherAbsence: Boolean? = null + var agendaTeacherAbsence: Boolean + get() { mAgendaTeacherAbsence = mAgendaTeacherAbsence ?: config.values.get("agendaTeacherAbsence", true); return mAgendaTeacherAbsence ?: true } + set(value) { config.set("agendaTeacherAbsence", value); mAgendaTeacherAbsence = value } + + private var mAgendaElearningMark: Boolean? = null + var agendaElearningMark: Boolean + get() { mAgendaElearningMark = mAgendaElearningMark ?: config.values.get("agendaElearningMark", false); return mAgendaElearningMark ?: false } + set(value) { config.set("agendaElearningMark", value); mAgendaElearningMark = value } + + private var mAgendaElearningGroup: Boolean? = null + var agendaElearningGroup: Boolean + get() { mAgendaElearningGroup = mAgendaElearningGroup ?: config.values.get("agendaElearningGroup", true); return mAgendaElearningGroup ?: true } + set(value) { config.set("agendaElearningGroup", value); mAgendaElearningGroup = value } + + private var mHomeCards: List? = null + var homeCards: List + get() { mHomeCards = mHomeCards ?: config.values.get("homeCards", listOf(), HomeCardModel::class.java); return mHomeCards ?: listOf() } + set(value) { config.set("homeCards", value); mHomeCards = value } + + private var mMessagesGreetingOnCompose: Boolean? = null + var messagesGreetingOnCompose: Boolean + get() { mMessagesGreetingOnCompose = mMessagesGreetingOnCompose ?: config.values.get("messagesGreetingOnCompose", true); return mMessagesGreetingOnCompose ?: true } + set(value) { config.set("messagesGreetingOnCompose", value); mMessagesGreetingOnCompose = value } + + private var mMessagesGreetingOnReply: Boolean? = null + var messagesGreetingOnReply: Boolean + get() { mMessagesGreetingOnReply = mMessagesGreetingOnReply ?: config.values.get("messagesGreetingOnReply", true); return mMessagesGreetingOnReply ?: true } + set(value) { config.set("messagesGreetingOnReply", value); mMessagesGreetingOnReply = value } + + private var mMessagesGreetingOnForward: Boolean? = null + var messagesGreetingOnForward: Boolean + get() { mMessagesGreetingOnForward = mMessagesGreetingOnForward ?: config.values.get("messagesGreetingOnForward", false); return mMessagesGreetingOnForward ?: false } + set(value) { config.set("messagesGreetingOnForward", value); mMessagesGreetingOnForward = value } + + private var mMessagesGreetingText: String? = null + var messagesGreetingText: String? + get() { mMessagesGreetingText = mMessagesGreetingText ?: config.values["messagesGreetingText"]; return mMessagesGreetingText } + set(value) { config.set("messagesGreetingText", value); mMessagesGreetingText = value } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/db/ConfigDao.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/db/ConfigDao.kt new file mode 100644 index 00000000..f55df857 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/db/ConfigDao.kt @@ -0,0 +1,28 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-11-27. + */ + +package pl.szczodrzynski.edziennik.config.db + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query + +@Dao +interface ConfigDao { + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun add(entry: ConfigEntry) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun addAll(list: List) + + @Query("SELECT * FROM config WHERE profileId = -1") + fun getAllNow(): List + + @Query("SELECT * FROM config WHERE profileId = :profileId") + fun getAllNow(profileId: Int): List + + @Query("DELETE FROM config WHERE profileId = :profileId") + fun clear(profileId: Int) +} \ No newline at end of file diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/db/ConfigEntry.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/db/ConfigEntry.kt new file mode 100644 index 00000000..6da441fe --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/db/ConfigEntry.kt @@ -0,0 +1,14 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-11-26. + */ + +package pl.szczodrzynski.edziennik.config.db + +import androidx.room.Entity + +@Entity(tableName = "config", primaryKeys = ["profileId", "key"]) +data class ConfigEntry( + val profileId: Int = -1, + val key: String, + val value: String? +) \ No newline at end of file diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/AppConfigMigrationV3.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/AppConfigMigrationV3.kt new file mode 100644 index 00000000..78a1d8a6 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/AppConfigMigrationV3.kt @@ -0,0 +1,96 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-1-19. + */ + +package pl.szczodrzynski.edziennik.config.utils + +import android.content.SharedPreferences +import com.google.gson.Gson +import com.google.gson.reflect.TypeToken +import pl.szczodrzynski.edziennik.BuildConfig +import pl.szczodrzynski.edziennik.MainActivity +import pl.szczodrzynski.edziennik.config.Config +import pl.szczodrzynski.edziennik.data.api.LOGIN_TYPE_LIBRUS +import pl.szczodrzynski.edziennik.data.api.LOGIN_TYPE_MOBIDZIENNIK +import pl.szczodrzynski.edziennik.data.api.LOGIN_TYPE_VULCAN +import pl.szczodrzynski.edziennik.utils.models.Time +import kotlin.math.abs + +class AppConfigMigrationV3(p: SharedPreferences, config: Config) { + init { config.apply { + val s = "app.appConfig" + if (dataVersion < 1) { + ui.theme = p.getString("$s.appTheme", null)?.toIntOrNull() ?: 1 + sync.enabled = p.getString("$s.registerSyncEnabled", null)?.toBoolean() ?: true + sync.interval = p.getString("$s.registerSyncInterval", null)?.toIntOrNull() ?: 3600 + val oldButtons = p.getString("$s.miniDrawerButtonIds", null)?.let { str -> + str.replace("[\\[\\]]*".toRegex(), "") + .split(",\\s?".toRegex()) + .mapNotNull { it.toIntOrNull() } + } + ui.miniMenuButtons = oldButtons ?: listOf( + MainActivity.DRAWER_ITEM_HOME, + MainActivity.DRAWER_ITEM_TIMETABLE, + MainActivity.DRAWER_ITEM_AGENDA, + MainActivity.DRAWER_ITEM_GRADES, + MainActivity.DRAWER_ITEM_MESSAGES, + MainActivity.DRAWER_ITEM_HOMEWORK, + MainActivity.DRAWER_ITEM_SETTINGS + ) + dataVersion = 1 + } + if (dataVersion < 2) { + devModePassword = p.getString("$s.devModePassword", null).fix() + sync.tokenApp = p.getString("$s.fcmToken", null).fix() + timetable.bellSyncMultiplier = p.getString("$s.bellSyncMultiplier", null)?.toIntOrNull() ?: 0 + appRateSnackbarTime = p.getString("$s.appRateSnackbarTime", null)?.toLongOrNull() ?: 0 + timetable.countInSeconds = p.getString("$s.countInSeconds", null)?.toBoolean() ?: false + ui.headerBackground = p.getString("$s.headerBackground", null).fix() + ui.appBackground = p.getString("$s.appBackground", null).fix() + ui.language = p.getString("$s.language", null).fix() + appVersion = p.getString("$s.lastAppVersion", null)?.toIntOrNull() ?: BuildConfig.VERSION_CODE + appInstalledTime = p.getString("$s.appInstalledTime", null)?.toLongOrNull() ?: 0 + grades.orderBy = p.getString("$s.gradesOrderBy", null)?.toIntOrNull() ?: 0 + sync.quietDuringLessons = p.getString("$s.quietDuringLessons", null)?.toBoolean() ?: false + ui.miniMenuVisible = p.getString("$s.miniDrawerVisible", null)?.toBoolean() ?: false + loginFinished = p.getString("$s.loginFinished", null)?.toBoolean() ?: false + sync.onlyWifi = p.getString("$s.registerSyncOnlyWifi", null)?.toBoolean() ?: false + sync.notifyAboutUpdates = p.getString("$s.notifyAboutUpdates", null)?.toBoolean() ?: true + timetable.bellSyncDiff = p.getString("$s.bellSyncDiff", null)?.let { Gson().fromJson(it, Time::class.java) } + + val startMillis = p.getString("$s.quietHoursStart", null)?.toLongOrNull() ?: 0 + val endMillis = p.getString("$s.quietHoursEnd", null)?.toLongOrNull() ?: 0 + if (startMillis > 0) { + try { + sync.quietHoursStart = Time.fromMillis(abs(startMillis)) + sync.quietHoursEnd = Time.fromMillis(abs(endMillis)) + sync.quietHoursEnabled = true + } + catch (_: Exception) {} + } + else { + sync.quietHoursEnabled = false + sync.quietHoursStart = null + sync.quietHoursEnd = null + } + + sync.tokenMobidziennikList = listOf() + sync.tokenVulcanList = listOf() + sync.tokenLibrusList = listOf() + val tokens = p.getString("$s.fcmTokens", null)?.let { Gson().fromJson>>>(it, object: TypeToken>>>(){}.type) } + tokens?.forEach { + val token = it.value.first + when (it.key) { + LOGIN_TYPE_MOBIDZIENNIK -> sync.tokenMobidziennik = token + LOGIN_TYPE_VULCAN -> sync.tokenVulcan = token + LOGIN_TYPE_LIBRUS -> sync.tokenLibrus = token + } + } + dataVersion = 2 + } + }} + + private fun String?.fix(): String? { + return this?.replace("\"", "")?.let { if (it == "null") null else it } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ConfigExtensions.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ConfigExtensions.kt new file mode 100644 index 00000000..94bb87e6 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ConfigExtensions.kt @@ -0,0 +1,113 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-11-27. + */ + +package pl.szczodrzynski.edziennik.config.utils + +import com.google.gson.* +import com.google.gson.reflect.TypeToken +import pl.szczodrzynski.edziennik.config.AbstractConfig +import pl.szczodrzynski.edziennik.config.db.ConfigEntry +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time + +private val gson = Gson() + +fun AbstractConfig.set(key: String, value: Int) { + set(key, value.toString()) +} +fun AbstractConfig.set(key: String, value: Boolean) { + set(key, value.toString()) +} +fun AbstractConfig.set(key: String, value: Long) { + set(key, value.toString()) +} +fun AbstractConfig.set(key: String, value: Float) { + set(key, value.toString()) +} +fun AbstractConfig.set(key: String, value: Date?) { + set(key, value?.stringY_m_d) +} +fun AbstractConfig.set(key: String, value: Time?) { + set(key, value?.stringValue) +} +fun AbstractConfig.set(key: String, value: JsonElement?) { + set(key, value?.toString()) +} +fun AbstractConfig.set(key: String, value: List?) { + set(key, value?.let { gson.toJson(it) }) +} +fun AbstractConfig.set(key: String, value: Any?) { + set(key, value?.let { gson.toJson(it) }) +} +fun AbstractConfig.setStringList(key: String, value: List?) { + set(key, value?.let { gson.toJson(it) }) +} +fun AbstractConfig.setIntList(key: String, value: List?) { + set(key, value?.let { gson.toJson(it) }) +} +fun AbstractConfig.setLongList(key: String, value: List?) { + set(key, value?.let { gson.toJson(it) }) +} +fun AbstractConfig.setMap(key: String, value: Map?) { + set(key, value?.let { gson.toJson(it) }) +} + +fun HashMap.get(key: String, default: String?): String? { + return this[key] ?: default +} +fun HashMap.get(key: String, default: Boolean): Boolean { + return this[key]?.toBoolean() ?: default +} +fun HashMap.getBooleanOrNull(key: String): Boolean? { + return this[key]?.toBooleanStrictOrNull() +} +fun HashMap.get(key: String, default: Int): Int { + return this[key]?.toIntOrNull() ?: default +} +fun HashMap.get(key: String, default: Long): Long { + return this[key]?.toLongOrNull() ?: default +} +fun HashMap.get(key: String, default: Float): Float { + return this[key]?.toFloatOrNull() ?: default +} +fun HashMap.get(key: String, default: Date?): Date? { + return this[key]?.let { Date.fromY_m_d(it) } ?: default +} +fun HashMap.get(key: String, default: Time?): Time? { + return this[key]?.let { Time.fromHms(it) } ?: default +} +fun HashMap.get(key: String, default: JsonObject?): JsonObject? { + return this[key]?.let { JsonParser().parse(it)?.asJsonObject } ?: default +} +fun HashMap.get(key: String, default: JsonArray?): JsonArray? { + return this[key]?.let { JsonParser().parse(it)?.asJsonArray } ?: default +} +inline fun HashMap.get(key: String, default: T?): T? { + return this[key]?.let { Gson().fromJson(it, T::class.java) } ?: default +} +/* !!! cannot use mutable list here - modifying it will not update the DB */ +fun HashMap.get(key: String, default: List?, classOfT: Class): List? { + return this[key]?.let { ConfigGsonUtils().deserializeList(gson, it, classOfT) } ?: default +} +fun HashMap.getStringList(key: String, default: List?): List? { + return this[key]?.let { gson.fromJson>(it, object: TypeToken>(){}.type) } ?: default +} +fun HashMap.getIntList(key: String, default: List?): List? { + return this[key]?.let { gson.fromJson>(it, object: TypeToken>(){}.type) } ?: default +} +fun HashMap.getLongList(key: String, default: List?): List? { + return this[key]?.let { gson.fromJson>(it, object: TypeToken>(){}.type) } ?: default +} + +fun HashMap.getFloat(key: String): Float? { + return this[key]?.toFloatOrNull() +} + +fun List.toHashMap(profileId: Int, map: HashMap) { + map.clear() + forEach { + if (it.profileId == profileId) + map[it.key] = it.value + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ConfigGsonUtils.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ConfigGsonUtils.kt new file mode 100644 index 00000000..0b0a634e --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ConfigGsonUtils.kt @@ -0,0 +1,45 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-12-2. + */ +package pl.szczodrzynski.edziennik.config.utils + +import com.google.gson.Gson +import com.google.gson.JsonParser +import pl.szczodrzynski.edziennik.ext.getInt +import pl.szczodrzynski.edziennik.ui.home.HomeCardModel +import pl.szczodrzynski.edziennik.utils.models.Time + +class ConfigGsonUtils { + @Suppress("UNCHECKED_CAST") + fun deserializeList(gson: Gson, str: String?, classOfT: Class): List { + val json = JsonParser.parseString(str) + val list: MutableList = mutableListOf() + if (!json.isJsonArray) + return list + + json.asJsonArray.forEach { e -> + when (classOfT) { + String::class.java -> { + list += e.asString as T + } + HomeCardModel::class.java -> { + val o = e.asJsonObject + list += HomeCardModel( + o.getInt("profileId", 0), + o.getInt("cardId", 0) + ) as T + } + Time::class.java -> { + val o = e.asJsonObject + list += Time( + o.getInt("hour", 0), + o.getInt("minute", 0), + o.getInt("second", 0) + ) as T + } + } + } + + return list + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ConfigMigration.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ConfigMigration.kt new file mode 100644 index 00000000..dcb4ab94 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ConfigMigration.kt @@ -0,0 +1,110 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-11-27. + */ + +package pl.szczodrzynski.edziennik.config.utils + +import android.content.Context +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.BuildConfig +import pl.szczodrzynski.edziennik.MainActivity +import pl.szczodrzynski.edziennik.config.Config +import pl.szczodrzynski.edziennik.ext.HOUR +import pl.szczodrzynski.edziennik.utils.managers.GradesManager.Companion.ORDER_BY_DATE_DESC +import pl.szczodrzynski.edziennik.utils.models.Time +import kotlin.math.abs + +class ConfigMigration(app: App, config: Config) { + init { config.apply { + + val p = app.getSharedPreferences("pl.szczodrzynski.edziennik_profiles", Context.MODE_PRIVATE) + if (p.contains("app.appConfig.appTheme")) { + // migrate appConfig from app version 3.x and lower. + // Updates dataVersion to level 2. + AppConfigMigrationV3(p, config) + } + + if (dataVersion < 2) { + appVersion = BuildConfig.VERSION_CODE + loginFinished = false + ui.language = null + ui.theme = 1 + ui.appBackground = null + ui.headerBackground = null + ui.miniMenuVisible = false + ui.miniMenuButtons = listOf( + MainActivity.DRAWER_ITEM_HOME, + MainActivity.DRAWER_ITEM_TIMETABLE, + MainActivity.DRAWER_ITEM_AGENDA, + MainActivity.DRAWER_ITEM_GRADES, + MainActivity.DRAWER_ITEM_MESSAGES, + MainActivity.DRAWER_ITEM_HOMEWORK, + MainActivity.DRAWER_ITEM_SETTINGS + ) + sync.enabled = true + sync.interval = 1* HOUR.toInt() + sync.notifyAboutUpdates = true + sync.onlyWifi = false + sync.quietHoursEnabled = false + sync.quietHoursStart = null + sync.quietHoursEnd = null + sync.quietDuringLessons = false + sync.tokenApp = null + sync.tokenMobidziennik = null + sync.tokenMobidziennikList = listOf() + sync.tokenLibrus = null + sync.tokenLibrusList = listOf() + sync.tokenVulcan = null + sync.tokenVulcanList = listOf() + timetable.bellSyncMultiplier = 0 + timetable.bellSyncDiff = null + timetable.countInSeconds = false + grades.orderBy = ORDER_BY_DATE_DESC + + dataVersion = 2 + } + + if (dataVersion < 3) { + update = null + privacyPolicyAccepted = false + devMode = null + devModePassword = null + appInstalledTime = 0L + appRateSnackbarTime = 0L + + dataVersion = 3 + } + + if (dataVersion < 10) { + ui.openDrawerOnBackPressed = false + ui.snowfall = false + ui.bottomSheetOpened = false + sync.dontShowAppManagerDialog = false + sync.webPushEnabled = true + sync.lastAppSync = 0L + + + dataVersion = 10 + } + + if (dataVersion < 11) { + val startMillis = config.values.get("quietHoursStart", 0L) + val endMillis = config.values.get("quietHoursEnd", 0L) + if (startMillis > 0) { + try { + sync.quietHoursStart = Time.fromMillis(abs(startMillis)) + sync.quietHoursEnd = Time.fromMillis(abs(endMillis)) + sync.quietHoursEnabled = true + } + catch (_: Exception) {} + } + else { + sync.quietHoursEnabled = false + sync.quietHoursStart = null + sync.quietHoursEnd = null + } + + dataVersion = 11 + } + }} +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ProfileConfigMigration.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ProfileConfigMigration.kt new file mode 100644 index 00000000..57177899 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ProfileConfigMigration.kt @@ -0,0 +1,49 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-12-1. + */ + +package pl.szczodrzynski.edziennik.config.utils + +import pl.szczodrzynski.edziennik.config.ProfileConfig +import pl.szczodrzynski.edziennik.data.db.entity.Notification +import pl.szczodrzynski.edziennik.data.db.entity.Profile.Companion.AGENDA_DEFAULT +import pl.szczodrzynski.edziennik.ui.home.HomeCard +import pl.szczodrzynski.edziennik.ui.home.HomeCardModel +import pl.szczodrzynski.edziennik.utils.managers.GradesManager.Companion.COLOR_MODE_WEIGHTED +import pl.szczodrzynski.edziennik.utils.managers.GradesManager.Companion.YEAR_ALL_GRADES + +class ProfileConfigMigration(config: ProfileConfig) { + init { config.apply { + + if (dataVersion < 1) { + grades.colorMode = COLOR_MODE_WEIGHTED + grades.yearAverageMode = YEAR_ALL_GRADES + grades.hideImproved = false + grades.averageWithoutWeight = true + grades.plusValue = null + grades.minusValue = null + grades.dontCountEnabled = false + grades.dontCountGrades = listOf() + ui.agendaViewType = AGENDA_DEFAULT + // no migration for ui.homeCards + + dataVersion = 1 + } + + if (dataVersion < 2) { + sync.notificationFilter = sync.notificationFilter + Notification.TYPE_TEACHER_ABSENCE + + dataVersion = 2 + } + + if (dataVersion < 3) { + if (ui.homeCards.isNotEmpty()) { + ui.homeCards = ui.homeCards.toMutableList().also { + it.add(HomeCardModel(config.profileId, HomeCard.CARD_NOTES)) + } + } + + dataVersion = 3 + } + }} +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/ApiService.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/ApiService.kt new file mode 100644 index 00000000..f68e8840 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/ApiService.kt @@ -0,0 +1,327 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-28. + */ + +package pl.szczodrzynski.edziennik.data.api + +import android.app.Service +import android.content.Context +import android.content.Intent +import android.os.IBinder +import org.greenrobot.eventbus.EventBus +import org.greenrobot.eventbus.Subscribe +import org.greenrobot.eventbus.ThreadMode +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.edziennik.EdziennikTask +import pl.szczodrzynski.edziennik.data.api.events.* +import pl.szczodrzynski.edziennik.data.api.events.requests.ServiceCloseRequest +import pl.szczodrzynski.edziennik.data.api.events.requests.TaskCancelRequest +import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikCallback +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.api.task.ErrorReportTask +import pl.szczodrzynski.edziennik.data.api.task.IApiTask +import pl.szczodrzynski.edziennik.data.api.task.SzkolnyTask +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.toApiError +import pl.szczodrzynski.edziennik.utils.Utils.d +import kotlin.math.min +import kotlin.math.roundToInt + +class ApiService : Service() { + companion object { + const val TAG = "ApiService" + const val NOTIFICATION_API_CHANNEL_ID = "pl.szczodrzynski.edziennik.SYNC" + fun start(context: Context) { + context.startService(Intent(context, ApiService::class.java)) + } + fun startAndRequest(context: Context, request: Any) { + context.startService(Intent(context, ApiService::class.java)) + EventBus.getDefault().postSticky(request) + } + + var lastEventTime = System.currentTimeMillis() + var taskCancelTries = 0 + } + + private val app by lazy { applicationContext as App } + + private val syncingProfiles = mutableListOf() + + private var szkolnyTaskFinished = false + private val allTaskRequestList = mutableListOf() + private val taskQueue = mutableListOf() + private val errorList = mutableListOf() + + private var serviceClosed = false + set(value) { field = value; notification.serviceClosed = value } + private var taskCancelled = false + private var taskIsRunning = false + private var taskRunning: IApiTask? = null // for debug purposes + private var taskRunningId = -1 + private var taskStartTime = 0L + private var taskMaximumId = 0 + + private var taskProfileId = -1 + private var taskProgress = -1f + private var taskProgressText: String? = null + + private val notification by lazy { EdziennikNotification(app) } + + /* ______ _ _ _ _ _____ _ _ _ _ + | ____| | | (_) (_) | / ____| | | | | | | + | |__ __| |_____ ___ _ __ _ __ _| | __ | | __ _| | | |__ __ _ ___| | __ + | __| / _` |_ / |/ _ \ '_ \| '_ \| | |/ / | | / _` | | | '_ \ / _` |/ __| |/ / + | |___| (_| |/ /| | __/ | | | | | | | < | |___| (_| | | | |_) | (_| | (__| < + |______\__,_/___|_|\___|_| |_|_| |_|_|_|\_\ \_____\__,_|_|_|_.__/ \__,_|\___|_|\*/ + private val taskCallback = object : EdziennikCallback { + override fun onCompleted() { + lastEventTime = System.currentTimeMillis() + d(TAG, "Task $taskRunningId (profile $taskProfileId) finished in ${System.currentTimeMillis()-taskStartTime}") + EventBus.getDefault().postSticky(ApiTaskFinishedEvent(taskProfileId)) + clearTask() + + notification.setIdle().post() + runTask() + } + + override fun onError(apiError: ApiError) { + lastEventTime = System.currentTimeMillis() + d(TAG, "Task $taskRunningId threw an error - $apiError") + apiError.profileId = taskProfileId + + if (app.userActionManager.requiresUserAction(apiError)) { + app.userActionManager.sendToUser(apiError) + } + else { + EventBus.getDefault().postSticky(ApiTaskErrorEvent(apiError)) + errorList.add(apiError) + apiError.throwable?.printStackTrace() + } + + if (apiError.isCritical) { + taskRunning?.cancel() + notification.setCriticalError().post() + clearTask() + runTask() + } + else { + notification.addError().post() + } + } + + override fun onProgress(step: Float) { + lastEventTime = System.currentTimeMillis() + if (step <= 0) + return + if (taskProgress < 0) + taskProgress = 0f + taskProgress += step + taskProgress = min(100f, taskProgress) + d(TAG, "Task $taskRunningId progress: ${taskProgress.roundToInt()}%") + EventBus.getDefault().post(ApiTaskProgressEvent(taskProfileId, taskProgress, taskProgressText)) + notification.setProgress(taskProgress).post() + } + + override fun onStartProgress(stringRes: Int) { + lastEventTime = System.currentTimeMillis() + taskProgressText = getString(stringRes) + d(TAG, "Task $taskRunningId progress: $taskProgressText") + EventBus.getDefault().post(ApiTaskProgressEvent(taskProfileId, taskProgress, taskProgressText)) + notification.setProgressText(taskProgressText).post() + } + } + + /* _______ _ _ _ + |__ __| | | | | (_) + | | __ _ ___| | __ _____ _____ ___ _ _| |_ _ ___ _ __ + | |/ _` / __| |/ / / _ \ \/ / _ \/ __| | | | __| |/ _ \| '_ \ + | | (_| \__ \ < | __/> < __/ (__| |_| | |_| | (_) | | | | + |_|\__,_|___/_|\_\ \___/_/\_\___|\___|\__,_|\__|_|\___/|_| |*/ + private fun runTask() { + checkIfTaskFrozen() + if (taskIsRunning) + return + if (taskCancelled || serviceClosed || (taskQueue.isEmpty() && szkolnyTaskFinished)) { + allCompleted() + return + } + + lastEventTime = System.currentTimeMillis() + + val task = if (taskQueue.isNotEmpty()) { + taskQueue.removeAt(0) + } else { + szkolnyTaskFinished = true + SzkolnyTask(app, syncingProfiles) + } + + task.taskId = ++taskMaximumId + task.prepare(app) + taskIsRunning = true + taskRunningId = task.taskId + taskRunning = task + taskProfileId = task.profileId + taskProgress = -1f + taskProgressText = task.taskName + + d(TAG, "Executing task $taskRunningId - ${task::class.java.name}") + + // update the notification + notification.setCurrentTask(taskRunningId, taskProgressText).post() + + // post an event + EventBus.getDefault().post(ApiTaskStartedEvent(taskProfileId, task.profile)) + + task.profile?.let { syncingProfiles.add(it) } + + taskStartTime = System.currentTimeMillis() + try { + when (task) { + is EdziennikTask -> task.run(app, taskCallback) + is ErrorReportTask -> task.run(app, taskCallback, notification, errorList) + is SzkolnyTask -> task.run(taskCallback) + } + } catch (e: Exception) { + taskCallback.onError(e.toApiError(TAG)) + } + } + + /** + * Check if a task is inactive for more than 30 seconds. + * If the user tries to cancel a task with no success at least three times, + * consider it frozen as well. + * + * This usually means it is broken and won't become active again. + * This method cancels the task and removes any pointers to it. + */ + private fun checkIfTaskFrozen(): Boolean { + if (System.currentTimeMillis() - lastEventTime > 30*1000 + || taskCancelTries >= 3) { + val time = System.currentTimeMillis() - lastEventTime + d(TAG, "!!! Task $taskRunningId froze for $time ms. $taskRunning") + clearTask() + return true + } + return false + } + + /** + * Stops the service if the current task is frozen/broken. + */ + private fun stopIfTaskFrozen() { + if (checkIfTaskFrozen()) { + allCompleted() + } + } + + /** + * Remove any task descriptors or pointers from the service. + */ + private fun clearTask() { + taskIsRunning = false + taskRunningId = -1 + taskRunning = null + taskProfileId = -1 + taskProgress = -1f + taskProgressText = null + taskCancelled = false + taskCancelTries = 0 + } + + private fun allCompleted() { + serviceClosed = true + EventBus.getDefault().postSticky(ApiTaskAllFinishedEvent()) + stopSelf() + } + + /* ______ _ ____ + | ____| | | | _ \ + | |____ _____ _ __ | |_| |_) |_ _ ___ + | __\ \ / / _ \ '_ \| __| _ <| | | / __| + | |___\ V / __/ | | | |_| |_) | |_| \__ \ + |______\_/ \___|_| |_|\__|____/ \__,_|__*/ + @Subscribe(sticky = true, threadMode = ThreadMode.ASYNC) + fun onApiTask(task: IApiTask) { + EventBus.getDefault().removeStickyEvent(task) + d(TAG, task.toString()) + + if (task is EdziennikTask) { + // fix for duplicated tasks, thank you EventBus + if (task.request in allTaskRequestList) + return + allTaskRequestList += task.request + } + + if (task is EdziennikTask) { + when (task.request) { + is EdziennikTask.SyncRequest -> app.db.profileDao().idsForSyncNow.forEach { + taskQueue += EdziennikTask.syncProfile(it) + } + is EdziennikTask.SyncProfileListRequest -> task.request.profileList.forEach { + taskQueue += EdziennikTask.syncProfile(it) + } + else -> { + taskQueue += task + } + } + } + else { + taskQueue += task + } + d(TAG, "EventBus received an IApiTask: $task") + d(TAG, "Current queue:") + taskQueue.forEach { + d(TAG, " - $it") + } + runTask() + } + + @Subscribe(sticky = true, threadMode = ThreadMode.ASYNC) + fun onTaskCancelRequest(request: TaskCancelRequest) { + EventBus.getDefault().removeStickyEvent(request) + d(TAG, request.toString()) + + taskCancelTries++ + taskCancelled = true + taskRunning?.cancel() + stopIfTaskFrozen() + } + @Subscribe(sticky = true, threadMode = ThreadMode.ASYNC) + fun onServiceCloseRequest(request: ServiceCloseRequest) { + EventBus.getDefault().removeStickyEvent(request) + d(TAG, request.toString()) + + serviceClosed = true + taskCancelled = true + taskRunning?.cancel() + allCompleted() + } + + /* _____ _ _ _ + / ____| (_) (_) | | + | (___ ___ _ ____ ___ ___ ___ _____ _____ _ __ _ __ _ __| | ___ ___ + \___ \ / _ \ '__\ \ / / |/ __/ _ \ / _ \ \ / / _ \ '__| '__| |/ _` |/ _ \/ __| + ____) | __/ | \ V /| | (_| __/ | (_) \ V / __/ | | | | | (_| | __/\__ \ + |_____/ \___|_| \_/ |_|\___\___| \___/ \_/ \___|_| |_| |_|\__,_|\___||__*/ + override fun onCreate() { + d(TAG, "Service created") + EventBus.getDefault().register(this) + notification.setIdle().setCloseAction() + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + d(TAG, "Foreground service onStartCommand") + startForeground(app.notificationChannelsManager.sync.id, notification.notification) + return START_NOT_STICKY + } + + override fun onDestroy() { + d(TAG, "Service destroyed") + serviceClosed = true + EventBus.getDefault().unregister(this) + } + + override fun onBind(intent: Intent?): IBinder? { + return null + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/AppError.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/AppError.java deleted file mode 100644 index ea72e969..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/AppError.java +++ /dev/null @@ -1,321 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api; - -import android.content.Context; -import android.os.AsyncTask; -import android.os.Build; -import android.util.Log; - -import com.google.gson.JsonObject; - -import java.io.InterruptedIOException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; - -import javax.net.ssl.SSLException; - -import im.wangchao.mhttp.Request; -import im.wangchao.mhttp.Response; -import pl.szczodrzynski.edziennik.R; - - -public class AppError { - public static final int CODE_OTHER = 0; - public static final int CODE_OK = 1; - public static final int CODE_NO_INTERNET = 10; - public static final int CODE_SSL_ERROR = 13; - public static final int CODE_ARCHIVED = 5; - public static final int CODE_MAINTENANCE = 6; - public static final int CODE_LOGIN_ERROR = 7; - public static final int CODE_ACCOUNT_MISMATCH = 8; - public static final int CODE_APP_SERVER_ERROR = 9; - public static final int CODE_MULTIACCOUNT_SETUP = 12; - public static final int CODE_TIMEOUT = 11; - public static final int CODE_PROFILE_NOT_FOUND = 14; - public static final int CODE_ATTACHMENT_NOT_AVAILABLE = 28; - // user's fault - public static final int CODE_INVALID_LOGIN = 2; - public static final int CODE_INVALID_SERVER_ADDRESS = 21; - public static final int CODE_INVALID_SCHOOL_NAME = 22; - public static final int CODE_INVALID_DEVICE = 23; - public static final int CODE_OLD_PASSWORD = 4; - public static final int CODE_INVALID_TOKEN = 24; - public static final int CODE_EXPIRED_TOKEN = 27; - public static final int CODE_INVALID_SYMBOL = 25; - public static final int CODE_INVALID_PIN = 26; - public static final int CODE_LIBRUS_NOT_ACTIVATED = 29; - public static final int CODE_SYNERGIA_NOT_ACTIVATED = 32; - public static final int CODE_LIBRUS_DISCONNECTED = 31; - public static final int CODE_PROFILE_ARCHIVED = 30; - - public static final int CODE_INTERNAL_MISSING_DATA = 100; - // internal errors - not for user's information. - // these error codes are processed in API main classes - public static final int CODE_INTERNAL_LIBRUS_ACCOUNT_410 = 120; - public static final int CODE_INTERNAL_LIBRUS_ACCOUNT_410_ = 120; - - public String TAG; - public int line; - public int errorCode; - public String errorText; - public Response response; - public Request request; - public Throwable throwable; - public String apiResponse; - - public AppError(String TAG, int line, int errorCode, String errorText, Response response, Request request, Throwable throwable, String apiResponse) { - this.TAG = TAG; - this.line = line; - this.errorCode = errorCode; - this.errorText = errorText; - this.response = response; - this.request = request; - this.throwable = throwable; - this.apiResponse = apiResponse; - } - - public AppError(String TAG, int line, int errorCode) { - this(TAG, line, errorCode, null, null, null, null, null); - } - public AppError(String TAG, int line, int errorCode, Response response, Throwable throwable) { - this(TAG, line, errorCode, null, response, response == null ? null : response.request(), throwable, null); - } - public AppError(String TAG, int line, int errorCode, Response response) { - this(TAG, line, errorCode, null, response, response == null ? null : response.request(), null, null); - } - public AppError(String TAG, int line, int errorCode, Throwable throwable, String apiResponse) { - this(TAG, line, errorCode, null, null, null, throwable, apiResponse); - } - public AppError(String TAG, int line, int errorCode, Throwable throwable, JsonObject apiResponse) { - this(TAG, line, errorCode, null, null, null, throwable, apiResponse.toString()); - } - public AppError(String TAG, int line, int errorCode, String errorText, Response response, JsonObject apiResponse) { - this(TAG, line, errorCode, errorText, response, response == null ? null : response.request(), null, apiResponse.toString()); - } - public AppError(String TAG, int line, int errorCode, String errorText, Response response, String apiResponse) { - this(TAG, line, errorCode, errorText, response, response == null ? null : response.request(), null, apiResponse); - } - public AppError(String TAG, int line, int errorCode, String errorText, String apiResponse) { - this(TAG, line, errorCode, errorText, null, null, null, apiResponse); - } - public AppError(String TAG, int line, int errorCode, String errorText, JsonObject apiResponse) { - this(TAG, line, errorCode, errorText, null, null, null, apiResponse.toString()); - } - public AppError(String TAG, int line, int errorCode, String errorText) { - this(TAG, line, errorCode, errorText, null, null, null, null); - } - public AppError(String TAG, int line, int errorCode, JsonObject apiResponse) { - this(TAG, line, errorCode, null, null, null, null, apiResponse.toString()); - } - public AppError(String TAG, int line, int errorCode, Response response, Throwable throwable, JsonObject apiResponse) { - this(TAG, line, errorCode, null, response, response == null ? null : response.request(), throwable, apiResponse.toString()); - } - public AppError(String TAG, int line, int errorCode, Response response, Throwable throwable, String apiResponse) { - this(TAG, line, errorCode, null, response, response == null ? null : response.request(), throwable, apiResponse); - } - public AppError(String TAG, int line, int errorCode, Response response, String apiResponse) { - this(TAG, line, errorCode, null, response, response == null ? null : response.request(), null, apiResponse); - } - public AppError(String TAG, int line, int errorCode, Response response, JsonObject apiResponse) { - this(TAG, line, errorCode, null, response, response == null ? null : response.request(), null, apiResponse.toString()); - } - - public String getDetails(Context context) { - StringBuilder sb = new StringBuilder(); - sb.append(stringErrorCode(context, errorCode, errorText)).append("\n"); - sb.append("(").append(stringErrorType(errorCode)).append("#").append(errorCode).append(")\n"); - sb.append("at ").append(TAG).append(":").append(line).append("\n"); - sb.append("\n"); - if (throwable == null) - sb.append("Throwable is null"); - else - sb.append(Log.getStackTraceString(throwable)); - sb.append("\n"); - sb.append(Build.MANUFACTURER).append(" ").append(Build.BRAND).append(" ").append(Build.MODEL).append(" ").append(Build.DEVICE).append("\n"); - - return sb.toString(); - } - - public interface GetApiResponseCallback { - void onSuccess(String apiResponse); - } - /** - * - * @param context a Context - * @param apiResponseCallback a callback executed on a worker thread - */ - public void getApiResponse(Context context, GetApiResponseCallback apiResponseCallback) { - StringBuilder sb = new StringBuilder(); - sb.append("Request:\n"); - if (request != null) { - sb.append(request.method()).append(" ").append(request.url().toString()).append("\n"); - sb.append(request.headers().toString()).append("\n"); - sb.append("\n"); - sb.append(request.bodyToString()).append("\n\n"); - } - else - sb.append("null\n\n"); - - if (apiResponse == null && response != null) - apiResponse = response.parserErrorBody; - - sb.append("Response:\n"); - if (response != null) { - sb.append(response.code()).append(" ").append(response.message()).append("\n"); - sb.append(response.headers().toString()).append("\n"); - sb.append("\n"); - if (apiResponse == null) { - if (Thread.currentThread().getName().equals("main")) { - AsyncTask.execute(() -> { - if (response.raw().body() != null) { - try { - sb.append(response.raw().body().string()); - } catch (Exception e) { - sb.append("Exception while getting response body:\n").append(Log.getStackTraceString(e)); - } - } - else { - sb.append("null"); - } - apiResponseCallback.onSuccess(sb.toString()); - }); - } - else { - if (response.raw().body() != null) { - try { - sb.append(response.raw().body().string()); - } catch (Exception e) { - sb.append("Exception while getting response body:\n").append(Log.getStackTraceString(e)); - } - } - else { - sb.append("null"); - } - apiResponseCallback.onSuccess(sb.toString()); - } - return; - } - } - else - sb.append("null\n\n"); - - sb.append("API Response:\n"); - if (apiResponse != null) { - sb.append(apiResponse).append("\n\n"); - } - else { - sb.append("null\n\n"); - } - - apiResponseCallback.onSuccess(sb.toString()); - } - - public AppError changeIfCodeOther() { - if (errorCode != CODE_OTHER && errorCode != CODE_MAINTENANCE) - return this; - if (throwable instanceof UnknownHostException) - errorCode = CODE_NO_INTERNET; - else if (throwable instanceof SSLException) - errorCode = CODE_SSL_ERROR; - else if (throwable instanceof SocketTimeoutException) - errorCode = CODE_TIMEOUT; - else if (throwable instanceof InterruptedIOException) - errorCode = CODE_NO_INTERNET; - else if (response != null && - (response.code() == 424 - || response.code() == 400 - || response.code() == 401 - || response.code() == 500 - || response.code() == 503 - || response.code() == 404)) - errorCode = CODE_MAINTENANCE; - return this; - } - - public String asReadableString(Context context) { - return stringErrorCode(context, errorCode, errorText) + (errorCode == CODE_MAINTENANCE && errorText != null && !errorText.isEmpty() ? " ("+errorText+")" : ""); - } - - public static String stringErrorCode(Context context, int errorCode, String errorText) - { - switch (errorCode) { - case CODE_OK: - return context.getString(R.string.sync_error_ok); - case CODE_INVALID_LOGIN: - return context.getString(R.string.sync_error_invalid_login); - case CODE_LOGIN_ERROR: - return context.getString(R.string.sync_error_login_error); - case CODE_INVALID_DEVICE: - return context.getString(R.string.sync_error_invalid_device); - case CODE_OLD_PASSWORD: - return context.getString(R.string.sync_error_old_password); - case CODE_ARCHIVED: - return context.getString(R.string.sync_error_archived); - case CODE_MAINTENANCE: - return context.getString(R.string.sync_error_maintenance); - case CODE_NO_INTERNET: - return context.getString(R.string.sync_error_no_internet); - case CODE_ACCOUNT_MISMATCH: - return context.getString(R.string.sync_error_account_mismatch); - case CODE_APP_SERVER_ERROR: - return context.getString(R.string.sync_error_app_server); - case CODE_TIMEOUT: - return context.getString(R.string.sync_error_timeout); - case CODE_SSL_ERROR: - return context.getString(R.string.sync_error_ssl); - case CODE_INVALID_SERVER_ADDRESS: - return context.getString(R.string.sync_error_invalid_server_address); - case CODE_INVALID_SCHOOL_NAME: - return context.getString(R.string.sync_error_invalid_school_name); - case CODE_PROFILE_NOT_FOUND: - return context.getString(R.string.sync_error_profile_not_found); - case CODE_INVALID_TOKEN: - return context.getString(R.string.sync_error_invalid_token); - case CODE_ATTACHMENT_NOT_AVAILABLE: - return context.getString(R.string.sync_error_attachment_not_available); - case CODE_LIBRUS_NOT_ACTIVATED: - return context.getString(R.string.sync_error_librus_not_activated); - case CODE_PROFILE_ARCHIVED: - return context.getString(R.string.sync_error_profile_archived); - case CODE_LIBRUS_DISCONNECTED: - return context.getString(R.string.sync_error_librus_disconnected); - case CODE_SYNERGIA_NOT_ACTIVATED: - return context.getString(R.string.sync_error_synergia_not_activated); - default: - case CODE_MULTIACCOUNT_SETUP: - case CODE_OTHER: - return errorText != null ? errorText : context.getString(R.string.sync_error_unknown); - } - } - public static String stringErrorType(int errorCode) - { - switch (errorCode) { - default: - case CODE_OTHER: return "CODE_OTHER"; - case CODE_OK: return "CODE_OK"; - case CODE_NO_INTERNET: return "CODE_NO_INTERNET"; - case CODE_SSL_ERROR: return "CODE_SSL_ERROR"; - case CODE_ARCHIVED: return "CODE_ARCHIVED"; - case CODE_MAINTENANCE: return "CODE_MAINTENANCE"; - case CODE_LOGIN_ERROR: return "CODE_LOGIN_ERROR"; - case CODE_ACCOUNT_MISMATCH: return "CODE_ACCOUNT_MISMATCH"; - case CODE_APP_SERVER_ERROR: return "CODE_APP_SERVER_ERROR"; - case CODE_MULTIACCOUNT_SETUP: return "CODE_MULTIACCOUNT_SETUP"; - case CODE_TIMEOUT: return "CODE_TIMEOUT"; - case CODE_PROFILE_NOT_FOUND: return "CODE_PROFILE_NOT_FOUND"; - case CODE_INVALID_LOGIN: return "CODE_INVALID_LOGIN"; - case CODE_INVALID_SERVER_ADDRESS: return "CODE_INVALID_SERVER_ADDRESS"; - case CODE_INVALID_SCHOOL_NAME: return "CODE_INVALID_SCHOOL_NAME"; - case CODE_INVALID_DEVICE: return "CODE_INVALID_DEVICE"; - case CODE_OLD_PASSWORD: return "CODE_OLD_PASSWORD"; - case CODE_INVALID_TOKEN: return "CODE_INVALID_TOKEN"; - case CODE_EXPIRED_TOKEN: return "CODE_EXPIRED_TOKEN"; - case CODE_INVALID_SYMBOL: return "CODE_INVALID_SYMBOL"; - case CODE_INVALID_PIN: return "CODE_INVALID_PIN"; - case CODE_ATTACHMENT_NOT_AVAILABLE: return "CODE_ATTACHMENT_NOT_AVAILABLE"; - case CODE_LIBRUS_NOT_ACTIVATED: return "CODE_LIBRUS_NOT_ACTIVATED"; - case CODE_PROFILE_ARCHIVED: return "CODE_PROFILE_ARCHIVED"; - case CODE_LIBRUS_DISCONNECTED: return "CODE_LIBRUS_DISCONNECTED"; - case CODE_SYNERGIA_NOT_ACTIVATED: return "CODE_SYNERGIA_NOT_ACTIVATED"; - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Constants.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Constants.kt new file mode 100644 index 00000000..1cb7587a --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Constants.kt @@ -0,0 +1,129 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-19. + */ + +package pl.szczodrzynski.edziennik.data.api + +import android.os.Build +import pl.szczodrzynski.edziennik.BuildConfig + +const val GET = 0 +const val POST = 1 + +val SYSTEM_USER_AGENT = System.getProperty("http.agent") ?: "Dalvik/2.1.0 Android" + +val SERVER_USER_AGENT = "Szkolny.eu/${BuildConfig.VERSION_NAME} $SYSTEM_USER_AGENT" + +const val FAKE_LIBRUS_API = "https://librus.szkolny.eu/api" +const val FAKE_LIBRUS_PORTAL = "https://librus.szkolny.eu" +const val FAKE_LIBRUS_AUTHORIZE = "https://librus.szkolny.eu/authorize.php" +const val FAKE_LIBRUS_LOGIN = "https://librus.szkolny.eu/login_action.php" +const val FAKE_LIBRUS_TOKEN = "https://librus.szkolny.eu/access_token.php" +const val FAKE_LIBRUS_ACCOUNT = "/synergia_accounts_fresh.php?login=" +const val FAKE_LIBRUS_ACCOUNTS = "/synergia_accounts.php" + +val LIBRUS_USER_AGENT = "${SYSTEM_USER_AGENT}LibrusMobileApp" +const val SYNERGIA_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Gecko/20100101 Firefox/62.0" +const val LIBRUS_CLIENT_ID = "VaItV6oRutdo8fnjJwysnTjVlvaswf52ZqmXsJGP" +const val LIBRUS_REDIRECT_URL = "app://librus" +const val LIBRUS_AUTHORIZE_URL = "https://portal.librus.pl/oauth2/authorize?client_id=$LIBRUS_CLIENT_ID&redirect_uri=$LIBRUS_REDIRECT_URL&response_type=code" +const val LIBRUS_LOGIN_URL = "https://portal.librus.pl/rodzina/login/action" +const val LIBRUS_TOKEN_URL = "https://portal.librus.pl/oauth2/access_token" + +const val LIBRUS_ACCOUNT_URL = "/v3/SynergiaAccounts/fresh/" // + login +const val LIBRUS_ACCOUNTS_URL = "/v3/SynergiaAccounts" + +/** https://api.librus.pl/2.0 */ +const val LIBRUS_API_URL = "https://api.librus.pl/2.0" +/** https://portal.librus.pl/api */ +const val LIBRUS_PORTAL_URL = "https://portal.librus.pl/api" +/** https://api.librus.pl/OAuth/Token */ +const val LIBRUS_API_TOKEN_URL = "https://api.librus.pl/OAuth/Token" +/** https://api.librus.pl/OAuth/TokenJST */ +const val LIBRUS_API_TOKEN_JST_URL = "https://api.librus.pl/OAuth/TokenJST" +const val LIBRUS_API_AUTHORIZATION = "Mjg6ODRmZGQzYTg3YjAzZDNlYTZmZmU3NzdiNThiMzMyYjE=" +const val LIBRUS_API_SECRET_JST = "18b7c1ee08216f636a1b1a2440e68398" +const val LIBRUS_API_CLIENT_ID_JST = "59" +//const val LIBRUS_API_CLIENT_ID_JST_REFRESH = "42" + +const val LIBRUS_JST_DEMO_CODE = "68656A21" +const val LIBRUS_JST_DEMO_PIN = "1290" + +const val LIBRUS_SYNERGIA_URL = "https://synergia.librus.pl" +/** https://synergia.librus.pl/loguj/token/TOKEN/przenies */ +const val LIBRUS_SYNERGIA_TOKEN_LOGIN_URL = "https://synergia.librus.pl/loguj/token/TOKEN/przenies" + +const val LIBRUS_MESSAGES_URL = "https://wiadomosci.librus.pl/module" +const val LIBRUS_SANDBOX_URL = "https://sandbox.librus.pl/index.php?action=" + +const val LIBRUS_SYNERGIA_HOMEWORK_ATTACHMENT_URL = "https://synergia.librus.pl/homework/downloadFile" +const val LIBRUS_SYNERGIA_MESSAGES_ATTACHMENT_URL = "https://synergia.librus.pl/wiadomosci/pobierz_zalacznik" + +const val IDZIENNIK_USER_AGENT = SYNERGIA_USER_AGENT +const val IDZIENNIK_WEB_URL = "https://iuczniowie.progman.pl/idziennik" +const val IDZIENNIK_WEB_LOGIN = "login.aspx" +const val IDZIENNIK_WEB_SETTINGS = "mod_panelRodzica/Ustawienia.aspx" +const val IDZIENNIK_WEB_HOME = "mod_panelRodzica/StronaGlowna.aspx" +const val IDZIENNIK_WEB_TIMETABLE = "mod_panelRodzica/plan/WS_Plan.asmx/pobierzPlanZajec" +const val IDZIENNIK_WEB_GRADES = "mod_panelRodzica/oceny/WS_ocenyUcznia.asmx/pobierzOcenyUcznia" +const val IDZIENNIK_WEB_MISSING_GRADES = "mod_panelRodzica/brak_ocen/WS_BrakOcenUcznia.asmx/pobierzBrakujaceOcenyUcznia" +const val IDZIENNIK_WEB_EXAMS = "mod_panelRodzica/sprawdziany/mod_sprawdzianyPanel.asmx/pobierzListe" +const val IDZIENNIK_WEB_HOMEWORK = "mod_panelRodzica/pracaDomowa/WS_pracaDomowa.asmx/pobierzPraceDomowe" +const val IDZIENNIK_WEB_NOTICES = "mod_panelRodzica/uwagi/WS_uwagiUcznia.asmx/pobierzUwagiUcznia" +const val IDZIENNIK_WEB_ATTENDANCE = "mod_panelRodzica/obecnosci/WS_obecnosciUcznia.asmx/pobierzObecnosciUcznia" +const val IDZIENNIK_WEB_ANNOUNCEMENTS = "mod_panelRodzica/tabOgl/WS_tablicaOgloszen.asmx/GetOgloszenia" +const val IDZIENNIK_WEB_MESSAGES_LIST = "mod_komunikator/WS_wiadomosci.asmx/PobierzListeWiadomosci" +const val IDZIENNIK_WEB_GET_MESSAGE = "mod_komunikator/WS_wiadomosci.asmx/PobierzWiadomosc" +const val IDZIENNIK_WEB_GET_RECIPIENT_LIST = "mod_komunikator/WS_wiadomosci.asmx/pobierzListeOdbiorcowPanelRodzic" +const val IDZIENNIK_WEB_SEND_MESSAGE = "mod_komunikator/WS_wiadomosci.asmx/WyslijWiadomosc" +const val IDZIENNIK_WEB_GET_ATTACHMENT = "mod_komunikator/Download.ashx" +const val IDZIENNIK_WEB_GET_HOMEWORK = "mod_panelRodzica/pracaDomowa/WS_pracaDomowa.asmx/pobierzJednaPraceDomowa" +const val IDZIENNIK_WEB_GET_HOMEWORK_ATTACHMENT = "mod_panelRodzica/pracaDomowa.aspx" + +val IDZIENNIK_API_USER_AGENT = SYSTEM_USER_AGENT +const val IDZIENNIK_API_URL = "https://iuczniowie.progman.pl/idziennik/api" +const val IDZIENNIK_API_CURRENT_REGISTER = "Uczniowie/\$STUDENT_ID/AktualnyDziennik" +const val IDZIENNIK_API_GRADES = "Uczniowie/\$STUDENT_ID/Oceny/" /* + semester */ +const val IDZIENNIK_API_MESSAGES_INBOX = "Wiadomosci/Odebrane" +const val IDZIENNIK_API_MESSAGES_SENT = "Wiadomosci/Wyslane" + + +val MOBIDZIENNIK_USER_AGENT = SYSTEM_USER_AGENT + +const val VULCAN_HEBE_USER_AGENT = "Dart/2.10 (dart:io)" +const val VULCAN_HEBE_APP_NAME = "DzienniczekPlus 2.0" +const val VULCAN_HEBE_APP_VERSION = "21.02.09 (G)" +private const val VULCAN_API_DEVICE_NAME_PREFIX = "Szkolny.eu " +private const val VULCAN_API_DEVICE_NAME_SUFFIX = " - nie usuwać" +val VULCAN_API_DEVICE_NAME by lazy { + val base = "$VULCAN_API_DEVICE_NAME_PREFIX${Build.MODEL}" + val baseMaxLength = 50 - VULCAN_API_DEVICE_NAME_SUFFIX.length + base.take(baseMaxLength) + VULCAN_API_DEVICE_NAME_SUFFIX +} + +const val VULCAN_WEB_ENDPOINT_LUCKY_NUMBER = "Start.mvc/GetKidsLuckyNumbers" +const val VULCAN_WEB_ENDPOINT_REGISTER_DEVICE = "RejestracjaUrzadzeniaToken.mvc/Get" +const val VULCAN_HEBE_ENDPOINT_REGISTER_NEW = "api/mobile/register/new" +const val VULCAN_HEBE_ENDPOINT_MAIN = "api/mobile/register/hebe" +const val VULCAN_HEBE_ENDPOINT_PUSH_ALL = "api/mobile/push/all" +const val VULCAN_HEBE_ENDPOINT_TIMETABLE = "api/mobile/schedule" +const val VULCAN_HEBE_ENDPOINT_TIMETABLE_CHANGES = "api/mobile/schedule/changes" +const val VULCAN_HEBE_ENDPOINT_ADDRESSBOOK = "api/mobile/addressbook" +const val VULCAN_HEBE_ENDPOINT_TEACHERS = "api/mobile/teacher" +const val VULCAN_HEBE_ENDPOINT_EXAMS = "api/mobile/exam" +const val VULCAN_HEBE_ENDPOINT_GRADES = "api/mobile/grade" +const val VULCAN_HEBE_ENDPOINT_GRADE_SUMMARY = "api/mobile/grade/summary" +const val VULCAN_HEBE_ENDPOINT_HOMEWORK = "api/mobile/homework" +const val VULCAN_HEBE_ENDPOINT_NOTICES = "api/mobile/note" +const val VULCAN_HEBE_ENDPOINT_ATTENDANCE = "api/mobile/lesson" +const val VULCAN_HEBE_ENDPOINT_MESSAGES = "api/mobile/message" +const val VULCAN_HEBE_ENDPOINT_MESSAGES_STATUS = "api/mobile/message/status" +const val VULCAN_HEBE_ENDPOINT_MESSAGES_SEND = "api/mobile/message" +const val VULCAN_HEBE_ENDPOINT_LUCKY_NUMBER = "api/mobile/school/lucky" + +const val EDUDZIENNIK_USER_AGENT = "Szkolny.eu/${BuildConfig.VERSION_NAME}" + +const val PODLASIE_API_VERSION = "1.0.62" +const val PODLASIE_API_URL = "https://cpdklaser.zeto.bialystok.pl/api" +const val PODLASIE_API_USER_ENDPOINT = "/pobierzDaneUcznia" +const val PODLASIE_API_LOGOUT_DEVICES_ENDPOINT = "/wyczyscUrzadzenia" diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Edziennik.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Edziennik.java deleted file mode 100644 index 99ab1a4b..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Edziennik.java +++ /dev/null @@ -1,1171 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api; - -import android.app.Activity; -import android.appwidget.AppWidgetManager; -import android.content.ClipData; -import android.content.ClipboardManager; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.os.AsyncTask; -import android.os.Build; -import android.os.Handler; -import android.os.Looper; -import android.text.Html; -import android.util.Base64; -import android.util.Log; -import android.webkit.CookieManager; -import android.webkit.CookieSyncManager; -import android.webkit.WebView; -import android.widget.Toast; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.StringRes; - -import com.afollestad.materialdialogs.DialogAction; -import com.afollestad.materialdialogs.MaterialDialog; -import com.danimahardhika.cafebar.CafeBar; -import com.google.android.gms.common.util.ArrayUtils; -import com.google.firebase.iid.FirebaseInstanceId; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.mikepenz.iconics.IconicsDrawable; -import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import pl.szczodrzynski.edziennik.App; -import pl.szczodrzynski.edziennik.BuildConfig; -import pl.szczodrzynski.edziennik.R; -import pl.szczodrzynski.edziennik.MainActivity; -import pl.szczodrzynski.edziennik.WidgetTimetable; -import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface; -import pl.szczodrzynski.edziennik.data.api.interfaces.SyncCallback; -import pl.szczodrzynski.edziennik.data.db.modules.announcements.AnnouncementFull; -import pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance; -import pl.szczodrzynski.edziennik.data.db.modules.attendance.AttendanceFull; -import pl.szczodrzynski.edziennik.data.db.modules.events.Event; -import pl.szczodrzynski.edziennik.data.db.modules.events.EventFull; -import pl.szczodrzynski.edziennik.data.db.modules.events.EventType; -import pl.szczodrzynski.edziennik.data.db.modules.grades.GradeFull; -import pl.szczodrzynski.edziennik.data.db.modules.lessons.LessonFull; -import pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore; -import pl.szczodrzynski.edziennik.data.db.modules.messages.Message; -import pl.szczodrzynski.edziennik.data.db.modules.messages.MessageFull; -import pl.szczodrzynski.edziennik.data.db.modules.metadata.Metadata; -import pl.szczodrzynski.edziennik.data.db.modules.notices.Notice; -import pl.szczodrzynski.edziennik.data.db.modules.notices.NoticeFull; -import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile; -import pl.szczodrzynski.edziennik.data.db.modules.profiles.ProfileFull; -import pl.szczodrzynski.edziennik.data.db.modules.teams.Team; -import pl.szczodrzynski.edziennik.utils.models.Date; -import pl.szczodrzynski.edziennik.utils.models.Notification; -import pl.szczodrzynski.edziennik.network.ServerRequest; -import pl.szczodrzynski.edziennik.sync.SyncJob; -import pl.szczodrzynski.edziennik.utils.Themes; -import pl.szczodrzynski.edziennik.widgets.luckynumber.WidgetLuckyNumber; -import pl.szczodrzynski.edziennik.widgets.notifications.WidgetNotifications; - -import static android.content.Context.CLIPBOARD_SERVICE; -import static com.mikepenz.iconics.utils.IconicsConvertersKt.colorInt; -import static com.mikepenz.iconics.utils.IconicsConvertersKt.sizeDp; -import static pl.szczodrzynski.edziennik.App.APP_URL; -import static pl.szczodrzynski.edziennik.MainActivity.DRAWER_ITEM_HOME; -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_OK; -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_OTHER; -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_PROFILE_ARCHIVED; -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_PROFILE_NOT_FOUND; -import static pl.szczodrzynski.edziennik.data.api.AppError.stringErrorCode; -import static pl.szczodrzynski.edziennik.data.api.AppError.stringErrorType; -import static pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface.FEATURE_AGENDA; -import static pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface.FEATURE_ALL; -import static pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface.FEATURE_ANNOUNCEMENTS; -import static pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface.FEATURE_ATTENDANCE; -import static pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface.FEATURE_GRADES; -import static pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface.FEATURE_HOMEWORK; -import static pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface.FEATURE_MESSAGES_INBOX; -import static pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface.FEATURE_MESSAGES_OUTBOX; -import static pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface.FEATURE_NOTICES; -import static pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface.FEATURE_TIMETABLE; -import static pl.szczodrzynski.edziennik.data.db.modules.events.Event.TYPE_HOMEWORK; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_SEMESTER1_FINAL; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_SEMESTER1_PROPOSED; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_SEMESTER2_FINAL; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_SEMESTER2_PROPOSED; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_YEAR_FINAL; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_YEAR_PROPOSED; -import static pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore.LOGIN_TYPE_IUCZNIOWIE; -import static pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore.LOGIN_TYPE_LIBRUS; -import static pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore.LOGIN_TYPE_MOBIDZIENNIK; -import static pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore.LOGIN_TYPE_VULCAN; -import static pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile.REGISTRATION_ENABLED; -import static pl.szczodrzynski.edziennik.sync.SyncService.PROFILE_MAX_PROGRESS; -import static pl.szczodrzynski.edziennik.utils.Utils.d; -import static pl.szczodrzynski.edziennik.utils.Utils.ns; - -public class Edziennik { - //public static final int CODE_NULL = 0; - private App app; - - private static final String TAG = "Edziennik"; - private static boolean registerEmpty; - public static int oldLuckyNumber; - - public static EdziennikInterface getApi(App app, int loginType) { - switch (loginType) { - default: - case LOGIN_TYPE_MOBIDZIENNIK: - return app.apiMobidziennik; - case LOGIN_TYPE_LIBRUS: - return app.apiLibrus; - case LOGIN_TYPE_IUCZNIOWIE: - return app.apiIuczniowie; - case LOGIN_TYPE_VULCAN: - return app.apiVulcan; - } - } - - public Edziennik(App app) { - this.app = app; - } - - @SuppressWarnings("deprecation") - public static void clearCookies(Context context, String url) { - //Log.d(TAG, "Cookies: " + yahooCookies); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { - //Log.d(TAG, "Using clearCookies code for API >=" + String.valueOf(Build.VERSION_CODES.LOLLIPOP_MR1)); - CookieManager.getInstance().removeAllCookies(null); - CookieManager.getInstance().flush(); - } else { - //Log.d(TAG, "Using clearCookies code for API <" + String.valueOf(Build.VERSION_CODES.LOLLIPOP_MR1)); - CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(context); - cookieSyncManager.startSync(); - CookieManager cookieManager = CookieManager.getInstance(); - cookieManager.removeAllCookie(); - cookieManager.removeSessionCookie(); - cookieSyncManager.stopSync(); - cookieSyncManager.sync(); - } - } - - public void initMessagesWebView(WebView webView, App app, boolean fullVersion, boolean clearCookies) { - if (!app.profile.getEmpty() && app.profile.getLoginStoreType() == LoginStore.LOGIN_TYPE_MOBIDZIENNIK) { - String url; - if (fullVersion) { - url = "https://" + app.profile.getLoginData("serverName", "") + ".mobidziennik.pl/mobile/wiadomosci"; - } else { - url = "https://" + app.profile.getLoginData("serverName", "") + ".mobidziennik.pl/api/"; - } - - String str1 = "login=" + app.profile.getLoginData("username", "") + "&haslo=" + app.profile.getLoginData("password", ""); - - if (!fullVersion) { - str1 += "&ip=" + app.deviceId + "&wersja=20&token=&webview_wiadomosci=1"; - } - - - if (-1L != -1L) { - str1 += "&id_wiadomosci=" + -1L; - } - - if (clearCookies) - clearCookies(app, "https://" + app.profile.getLoginData("serverName", "") + ".mobidziennik.pl"); - - //Toast.makeText(app, "URL "+url, Toast.LENGTH_SHORT).show(); - webView.postUrl(url, str1.getBytes()); - } else if (!app.profile.getEmpty() && app.profile.getLoginStoreType() == LoginStore.LOGIN_TYPE_IUCZNIOWIE) { - String url = "https://iuczniowie.progman.pl/idziennik/mod_panelRodzica/Komunikator.aspx"; - webView.loadUrl(url); - /* - if (app.profile.loginServerName.equals("") || app.profile.loginUsername.equals("") || app.profile.loginPassword.equals("")) { - webView.loadData("

    "+app.getString(R.string.api_error_code_invalid_login)+"

    ", "text/html", "UTF-8"); - return; - } - - if (app.appConfig.deviceId == null || app.appConfig.deviceId.equals("")) { - app.appConfig.deviceId = Settings.Secure.getString(app.getContentResolver(), Settings.Secure.ANDROID_ID); - app.appConfig.savePending = true; - } - - //Ion.getDefault(app.getContext()).getCookieMiddleware().getCookieStore().removeAll(); // TODO remove only cookies for this domain - String finalLoginServerName = app.profile.loginServerName; - String finalLoginUsername = app.profile.loginUsername; - String finalLoginPassword = app.profile.loginPassword; - Ion.with(app.getContext()) - .load("https://iuczniowie.progman.pl/idziennik/login.aspx") - .setTimeout(REQUEST_TIMEOUT) - .setHeader("User-Agent", Iuczniowie.userAgent) - //.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") - .asString() - .setCallback((e, result) -> { - if (e instanceof java.util.concurrent.TimeoutException) { - webView.loadData("

    "+app.getString(R.string.api_error_code_timeout)+"

    ", "text/html", "UTF-8"); - return; - } - app.profile.loggedIn = (result != null && result.equals("ok")); - if (result == null || result.equals("")) { // for safety - webView.loadData("

    "+app.getString(R.string.api_error_code_no_internet)+"

    ", "text/html", "UTF-8"); - return; - } - if (clearCookies) - clearCookies(app, "https://iuczniowie.progman.pl"); - - String post = ""; - try { - post += "ctl00$ContentPlaceHolder$nazwaPrzegladarki="+URLEncoder.encode(Iuczniowie.userAgent, "UTF-8"); - post += "ctl00$ContentPlaceHolder$NazwaSzkoly="+finalLoginServerName; - post += "ctl00$ContentPlaceHolder$UserName="+URLEncoder.encode(finalLoginUsername, "UTF-8"); - post += "ctl00$ContentPlaceHolder$Password="+URLEncoder.encode(finalLoginPassword, "UTF-8"); - post += "ctl00$ContentPlaceHolder$Logowanie=Zaloguj"; - } catch (UnsupportedEncodingException e1) { - e1.printStackTrace(); - } - - webView.getSettings().setUserAgentString(Iuczniowie.userAgent); - - });*/ - } else if (app.profile.getEmpty()) { - webView.loadData("

    " + app.getString(R.string.sync_error_invalid_login) + "

    ", "text/html", "UTF-8"); - } else { - webView.loadData("

    " + app.getString(R.string.settings_register_login_not_implemented_text) + "

    ", "text/html", "UTF-8"); - } - } - - - - /* _____ _______ _ - | __ \ /\ |__ __| | | - | |__) | __ ___ ___ ___ ___ ___ / \ ___ _ _ _ __ ___| | __ _ ___| | __ - | ___/ '__/ _ \ / __/ _ \/ __/ __| / /\ \ / __| | | | '_ \ / __| |/ _` / __| |/ / - | | | | | (_) | (_| __/\__ \__ \/ ____ \\__ \ |_| | | | | (__| | (_| \__ \ < - |_| |_| \___/ \___\___||___/___/_/ \_\___/\__, |_| |_|\___|_|\__,_|___/_|\_\ - __/ | - |__*/ - - /** - * A task for creating notifications and downloading shared events. - */ - private static class ProcessAsyncTask extends AsyncTask { - private App app; - private WeakReference activityContext; - private SyncCallback callback; - private Exception e = null; - private String apiResponse = null; - private int profileId; - private ProfileFull profile; - - public ProcessAsyncTask(App app, Context activityContext, SyncCallback callback, int profileId, ProfileFull profile) { - //d(TAG, "Thread/ProcessAsyncTask/constructor/"+Thread.currentThread().getName()); - this.app = app; - this.activityContext = new WeakReference<>(activityContext); - this.callback = callback; - this.profileId = profileId; - this.profile = profile; - } - - @Override - protected Integer doInBackground(Void... voids) { - Context activityContext = this.activityContext.get(); - //d(TAG, "Thread/ProcessAsyncTask/doInBackground/"+Thread.currentThread().getName()); - try { - - // UPDATE FCM TOKEN IF EMPTY - if (app.appConfig.fcmToken == null || app.appConfig.fcmToken.equals("")) { - FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(instanceIdResult -> { - app.appConfig.fcmToken = instanceIdResult.getToken(); - app.appConfig.savePending = true; - }); - } - - callback.onProgress(1); - if (profile.getSyncNotifications()) { - new Handler(activityContext.getMainLooper()).post(() -> { - callback.onActionStarted(R.string.sync_action_creating_notifications); - }); - - for (LessonFull change : app.db.lessonChangeDao().getNotNotifiedNow(profileId)) { - String text = app.getContext().getString(R.string.notification_lesson_change_format, change.changeTypeStr(app.getContext()), change.lessonDate == null ? "" : change.lessonDate.getFormattedString(), change.subjectLongName); - app.notifier.add(new Notification(app.getContext(), text) - .withProfileData(profile.getId(), profile.getName()) - .withType(Notification.TYPE_TIMETABLE_LESSON_CHANGE) - .withFragmentRedirect(MainActivity.DRAWER_ITEM_TIMETABLE) - .withLongExtra("timetableDate", change.lessonDate.getValue()) - .withAddedDate(change.addedDate) - ); - } - for (EventFull event : app.db.eventDao().getNotNotifiedNow(profileId)) { - String text; - if (event.type == TYPE_HOMEWORK) - text = app.getContext().getString(R.string.notification_homework_format, ns(app.getString(R.string.notification_event_no_subject), event.subjectLongName), event.eventDate.getFormattedString()); - else - text = app.getContext().getString(R.string.notification_event_format, event.typeName, event.eventDate.getFormattedString(), ns(app.getString(R.string.notification_event_no_subject), event.subjectLongName)); - app.notifier.add(new Notification(app.getContext(), text) - .withProfileData(profile.getId(), profile.getName()) - .withType(event.type == TYPE_HOMEWORK ? Notification.TYPE_NEW_HOMEWORK : Notification.TYPE_NEW_EVENT) - .withFragmentRedirect(event.type == TYPE_HOMEWORK ? MainActivity.DRAWER_ITEM_HOMEWORK : MainActivity.DRAWER_ITEM_AGENDA) - .withLongExtra("eventId", event.id) - .withLongExtra("eventDate", event.eventDate.getValue()) - .withAddedDate(event.addedDate) - ); - // student's rights abuse - disabled, because this was useless - /*if (!event.addedManually && event.type == RegisterEvent.TYPE_EXAM && event.eventDate.combineWith(event.startTime) - event.addedDate < 7 * 24 * 60 * 60 * 1000) { - text = app.getContext().getString(R.string.notification_abuse_format, event.typeString(app, app.profile), event.subjectLongName, event.eventDate.getFormattedString()); - app.notifier.add(new Notification(app.getContext(), text) - .withProfileData(profile.id, profile.name) - .withType(Notification.TYPE_GENERAL) - .withFragmentRedirect(MainActivity.DRAWER_ITEM_NOTIFICATIONS) - ); - }*/ - } - - Date today = Date.getToday(); - int todayValue = today.getValue(); - profile.setCurrentSemester(profile.dateToSemester(today)); - - for (GradeFull grade : app.db.gradeDao().getNotNotifiedNow(profileId)) { - String gradeName = grade.name; - if (grade.type == TYPE_SEMESTER1_PROPOSED - || grade.type == TYPE_SEMESTER2_PROPOSED) { - gradeName = (app.getString(R.string.grade_semester_proposed_format_2, grade.name)); - } else if (grade.type == TYPE_SEMESTER1_FINAL - || grade.type == TYPE_SEMESTER2_FINAL) { - gradeName = (app.getString(R.string.grade_semester_final_format_2, grade.name)); - } else if (grade.type == TYPE_YEAR_PROPOSED) { - gradeName = (app.getString(R.string.grade_year_proposed_format_2, grade.name)); - } else if (grade.type == TYPE_YEAR_FINAL) { - gradeName = (app.getString(R.string.grade_year_final_format_2, grade.name)); - } - String text = app.getContext().getString(R.string.notification_grade_format, gradeName, grade.subjectLongName); - app.notifier.add(new Notification(app.getContext(), text) - .withProfileData(profile.getId(), profile.getName()) - .withType(Notification.TYPE_NEW_GRADE) - .withFragmentRedirect(MainActivity.DRAWER_ITEM_GRADES) - .withLongExtra("gradesSubjectId", grade.subjectId) - .withAddedDate(grade.addedDate) - ); - } - for (NoticeFull notice : app.db.noticeDao().getNotNotifiedNow(profileId)) { - String noticeTypeStr = (notice.type == Notice.TYPE_POSITIVE ? app.getString(R.string.notification_notice_praise) : (notice.type == Notice.TYPE_NEGATIVE ? app.getString(R.string.notification_notice_warning) : app.getString(R.string.notification_notice_new))); - String text = app.getContext().getString(R.string.notification_notice_format, noticeTypeStr, notice.teacherFullName, Date.fromMillis(notice.addedDate).getFormattedString()); - app.notifier.add(new Notification(app.getContext(), text) - .withProfileData(profile.getId(), profile.getName()) - .withType(Notification.TYPE_NEW_NOTICE) - .withFragmentRedirect(MainActivity.DRAWER_ITEM_BEHAVIOUR) - .withLongExtra("noticeId", notice.id) - .withAddedDate(notice.addedDate) - ); - } - for (AttendanceFull attendance : app.db.attendanceDao().getNotNotifiedNow(profileId)) { - String attendanceTypeStr = app.getString(R.string.notification_type_attendance); - switch (attendance.type) { - case Attendance.TYPE_ABSENT: - attendanceTypeStr = app.getString(R.string.notification_absence); - break; - case Attendance.TYPE_ABSENT_EXCUSED: - attendanceTypeStr = app.getString(R.string.notification_absence_excused); - break; - case Attendance.TYPE_BELATED: - attendanceTypeStr = app.getString(R.string.notification_belated); - break; - case Attendance.TYPE_BELATED_EXCUSED: - attendanceTypeStr = app.getString(R.string.notification_belated_excused); - break; - case Attendance.TYPE_RELEASED: - attendanceTypeStr = app.getString(R.string.notification_release); - break; - } - String text = app.getContext().getString(R.string.notification_attendance_format, attendanceTypeStr, attendance.subjectLongName, attendance.lessonDate.getFormattedString()); - app.notifier.add(new Notification(app.getContext(), text) - .withProfileData(profile.getId(), profile.getName()) - .withType(Notification.TYPE_NEW_ATTENDANCE) - .withFragmentRedirect(MainActivity.DRAWER_ITEM_ATTENDANCE) - .withLongExtra("attendanceId", attendance.id) - .withAddedDate(attendance.addedDate) - ); - } - for (AnnouncementFull announcement : app.db.announcementDao().getNotNotifiedNow(profileId)) { - String text = app.getContext().getString(R.string.notification_announcement_format, announcement.subject); - app.notifier.add(new Notification(app.getContext(), text) - .withProfileData(profile.getId(), profile.getName()) - .withType(Notification.TYPE_NEW_ANNOUNCEMENT) - .withFragmentRedirect(MainActivity.DRAWER_ITEM_ANNOUNCEMENTS) - .withLongExtra("announcementId", announcement.id) - .withAddedDate(announcement.addedDate) - ); - } - for (MessageFull message : app.db.messageDao().getReceivedNotNotifiedNow(profileId)) { - String text = app.getContext().getString(R.string.notification_message_format, message.senderFullName, message.subject); - app.notifier.add(new Notification(app.getContext(), text) - .withProfileData(profile.getId(), profile.getName()) - .withType(Notification.TYPE_NEW_MESSAGE) - .withFragmentRedirect(MainActivity.DRAWER_ITEM_MESSAGES) - .withLongExtra("messageType", Message.TYPE_RECEIVED) - .withLongExtra("messageId", message.id) - .withAddedDate(message.addedDate) - ); - } - - if (profile.getLuckyNumber() != oldLuckyNumber - && profile.getLuckyNumber() != -1 - && profile.getLuckyNumberDate() != null - && profile.getLuckyNumberDate().getValue() >= todayValue) { - String text; - if (profile.getLuckyNumberDate().getValue() == todayValue) { // LN for today - text = app.getString((profile.getStudentNumber() != -1 && profile.getStudentNumber() == profile.getLuckyNumber() ? R.string.notification_lucky_number_yours_format : R.string.notification_lucky_number_format), profile.getLuckyNumber()); - } else if (profile.getLuckyNumberDate().getValue() == todayValue + 1) { // LN for tomorrow - text = app.getString((profile.getStudentNumber() != -1 && profile.getStudentNumber() == profile.getLuckyNumber() ? R.string.notification_lucky_number_yours_tomorrow_format : R.string.notification_lucky_number_tomorrow_format), profile.getLuckyNumber()); - } else { // LN for later - text = app.getString((profile.getStudentNumber() != -1 && profile.getStudentNumber() == profile.getLuckyNumber() ? R.string.notification_lucky_number_yours_later_format : R.string.notification_lucky_number_later_format), profile.getLuckyNumberDate().getFormattedString(), profile.getLuckyNumber()); - } - app.notifier.add(new Notification(app.getContext(), text) - .withProfileData(profile.getId(), profile.getName()) - .withType(Notification.TYPE_LUCKY_NUMBER) - .withFragmentRedirect(MainActivity.DRAWER_ITEM_HOME) - ); - oldLuckyNumber = profile.getLuckyNumber(); - } - } - - - app.db.metadataDao().setAllNotified(profileId, true); - callback.onProgress(1); - - // SEND WEB PUSH, if registration allowed - // otherwise, UNREGISTER THE USER - if (profile.getRegistration() == REGISTRATION_ENABLED) { - new Handler(activityContext.getMainLooper()).post(() -> { - callback.onActionStarted(R.string.sync_action_syncing_shared_events); - }); - //if (profile.registrationUsername == null || profile.registrationUsername.equals("")) { - //} - ServerRequest syncRequest = new ServerRequest(app, app.requestScheme + APP_URL + "main.php?sync", "Edziennik/REG", profile); - - if (registerEmpty) { - syncRequest.setBodyParameter("first_run", "true"); - } - - // ALSO SEND NEW DATA TO BROWSER *excluding* all Shared Events !!! - // because they will be sent by the server, as soon as it's shared, by FCM - - if (app.appConfig.webPushEnabled) { - int position = 0; - for (Notification notification : app.appConfig.notifications) { - //Log.d(TAG, notification.text); - if (!notification.notified) { - if (notification.type != Notification.TYPE_NEW_SHARED_EVENT - && notification.type != Notification.TYPE_SERVER_MESSAGE - && notification.type != Notification.TYPE_NEW_SHARED_HOMEWORK) // these are automatically sent to the browser by the server - { - //Log.d(TAG, "Adding notify[" + position + "]"); - syncRequest.setBodyParameter("notify[" + position + "][type]", Integer.toString(notification.type)); - syncRequest.setBodyParameter("notify[" + position + "][title]", notification.title); - syncRequest.setBodyParameter("notify[" + position + "][text]", notification.text); - position++; - } - } - } - } - - callback.onProgress(1); - - if (app.appConfig.webPushEnabled || profile.getEnableSharedEvents()) { - JsonObject result = syncRequest.runSync(); - callback.onProgress(1); - //Log.d(TAG, "Executed request"); - if (result == null) { - return AppError.CODE_APP_SERVER_ERROR; - } - apiResponse = result.toString(); - if (!result.get("success").getAsString().equals("true")) { - return AppError.CODE_APP_SERVER_ERROR; - } - // HERE PROCESS ALL THE RECEIVED EVENTS - // add them to the profile and create appropriate notifications - for (JsonElement jEventEl : result.getAsJsonArray("events")) { - JsonObject jEvent = jEventEl.getAsJsonObject(); - String teamCode = jEvent.get("team").getAsString(); - //d(TAG, "An event is there! "+jEvent.toString()); - // get the target Team from teamCode - Team team = app.db.teamDao().getByCodeNow(profile.getId(), teamCode); - if (team != null) { - //d(TAG, "The target team is "+team.name+", ID "+team.id); - // create the event from Json. Add the missing teamId and !!profileId!! - Event event = app.gson.fromJson(jEvent.toString(), Event.class); - // proguard. disable for Event.class - if (event.eventDate == null) { - apiResponse += "\n\nEventDate == null\n" + jEvent.toString(); - throw new Exception("null eventDate"); - } - event.profileId = profile.getId(); - event.teamId = team.id; - event.addedManually = true; - //d(TAG, "Created the event! "+event); - - if (event.sharedBy != null && event.sharedBy.equals(profile.getUsernameId())) { - //d(TAG, "Shared by self! Changing name"); - event.sharedBy = "self"; - event.sharedByName = profile.getStudentNameLong(); - } - - EventType type = app.db.eventTypeDao().getByIdNow(profileId, event.type); - - //d(TAG, "Finishing adding event "+event); - app.db.eventDao().add(event); - Metadata metadata = new Metadata(profile.getId(), event.type == TYPE_HOMEWORK ? Metadata.TYPE_HOMEWORK : Metadata.TYPE_EVENT, event.id, registerEmpty, true, jEvent.get("addedDate").getAsLong()); - long metadataId = app.db.metadataDao().add(metadata); - if (metadataId != -1 && !registerEmpty) { - app.notifier.add(new Notification(app.getContext(), app.getString(R.string.notification_shared_event_format, event.sharedByName, type != null ? type.name : "wydarzenie", event.eventDate == null ? "nieznana data" : event.eventDate.getFormattedString(), event.topic)) - .withProfileData(profile.getId(), profile.getName()) - .withType(event.type == TYPE_HOMEWORK ? Notification.TYPE_NEW_SHARED_HOMEWORK : Notification.TYPE_NEW_SHARED_EVENT) - .withFragmentRedirect(event.type == TYPE_HOMEWORK ? MainActivity.DRAWER_ITEM_HOMEWORK : MainActivity.DRAWER_ITEM_AGENDA) - .withLongExtra("eventDate", event.eventDate.getValue()) - ); - } - } - } - callback.onProgress(5); - return CODE_OK; - } else { - callback.onProgress(6); - return CODE_OK; - } - } else { - // the user does not want to be registered - callback.onProgress(7); - return CODE_OK; - } - } catch (Exception e) { - e.printStackTrace(); - this.e = e; - return null; - } - //return null; - } - - @Override - protected void onPostExecute(Integer errorCode) { - //d(TAG, "Thread/ProcessAsyncTask/onPostExecute/"+Thread.currentThread().getName()); - Context activityContext = this.activityContext.get(); - app.profileSaveFull(profile); - if (app.profile != null && profile.getId() == app.profile.getId()) { - app.profile = profile; - } - if (errorCode == null) { - // this means an Exception was thrown - callback.onError(activityContext, new AppError(TAG, 513, CODE_OTHER, e, apiResponse)); - return; - } - //Log.d(TAG, "Finishing"); - - - callback.onProgress(1); - - if (errorCode == CODE_OK) - callback.onSuccess(activityContext, profile); - else { - try { - // oh that's useless - throw new RuntimeException(stringErrorCode(app, errorCode, "")); - } catch (Exception e) { - callback.onError(activityContext, new AppError(TAG, 528, errorCode, e, (String) null)); - } - } - super.onPostExecute(errorCode); - } - } - - public void notifyAndReload() { - app.notifier.postAll(null); - app.saveConfig(); - SyncJob.schedule(app); - Intent i = new Intent(Intent.ACTION_MAIN) - .putExtra("reloadProfileId", -1); - app.sendBroadcast(i); - - Intent intent = new Intent(app.getContext(), WidgetTimetable.class); - intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); - int[] ids = AppWidgetManager.getInstance(app).getAppWidgetIds(new ComponentName(app, WidgetTimetable.class)); - intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids); - app.sendBroadcast(intent); - - intent = new Intent(app.getContext(), WidgetNotifications.class); - intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); - ids = AppWidgetManager.getInstance(app).getAppWidgetIds(new ComponentName(app, WidgetNotifications.class)); - intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids); - app.sendBroadcast(intent); - - intent = new Intent(app.getContext(), WidgetLuckyNumber.class); - intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); - ids = AppWidgetManager.getInstance(app).getAppWidgetIds(new ComponentName(app, WidgetLuckyNumber.class)); - intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids); - app.sendBroadcast(intent); - } - - /* _____ - / ____| - | (___ _ _ _ __ ___ - \___ \| | | | '_ \ / __| - ____) | |_| | | | | (__ - |_____/ \__, |_| |_|\___| - __/ | - |__*/ - // DataCallbacks that are *not* in Edziennik.sync need to be executed on the main thread. - // EdziennikInterface.sync is executed on a worker thread - // in Edziennik.sync/newCallback methods are called on a worker thread - - // callback passed to Edziennik.sync is executed on the main thread - // thus, callback which is in guiSync is also on the main thread - - /** - * Sync all Edziennik data. - * Used in services, login form and {@code guiSync} - *

    - * May be ran on worker thread. - * {@link EdziennikInterface}.sync is ran always on worker thread. - * Every callback is ran on the UI thread. - * - * @param app - * @param activityContext - * @param callback - * @param profileId - */ - public void sync(@NonNull App app, @NonNull Context activityContext, @NonNull SyncCallback callback, int profileId) { - sync(app, activityContext, callback, profileId, (int[])null); - } - public void sync(@NonNull App app, @NonNull Context activityContext, @NonNull SyncCallback callback, int profileId, @Nullable int ... featureList) { - // empty: no unread notifications, all shared events (current+past) - // only if there is no data, and we are not logged in yet - SyncCallback newCallback = new SyncCallback() { - @Override - public void onLoginFirst(List profileList, LoginStore loginStore) { - new Handler(activityContext.getMainLooper()).post(() -> { - callback.onLoginFirst(profileList, loginStore); - }); - } - - @Override - public void onSuccess(Context activityContext, ProfileFull profileFull) { - new Handler(activityContext.getMainLooper()).post(() -> { - new ProcessAsyncTask(app, activityContext, callback, profileId, profileFull).execute(); - }); - } - - @Override - public void onError(Context activityContext, AppError error) { - new Handler(activityContext.getMainLooper()).post(() -> { - callback.onError(activityContext, error); - }); - } - - @Override - public void onProgress(int progressStep) { - new Handler(activityContext.getMainLooper()).post(() -> { - callback.onProgress(progressStep); - }); - } - - @Override - public void onActionStarted(int stringResId) { - new Handler(activityContext.getMainLooper()).post(() -> { - callback.onActionStarted(stringResId); - }); - } - }; - AsyncTask.execute(() -> { - ProfileFull profile = app.db.profileDao().getByIdNow(profileId); - if (profile != null) { - - if (profile.getArchived()) { - newCallback.onError(activityContext, new AppError(TAG, 678, CODE_PROFILE_ARCHIVED, profile.getName())); - return; - } - else if (profile.getDateYearEnd() != null && Date.getToday().getValue() >= profile.getDateYearEnd().getValue()) { - profile.setArchived(true); - app.notifier.add(new Notification(app.getContext(), app.getString(R.string.profile_auto_archiving_format, profile.getName(), profile.getDateYearEnd().getFormattedString())) - .withProfileData(profile.getId(), profile.getName()) - .withType(Notification.TYPE_AUTO_ARCHIVING) - .withFragmentRedirect(DRAWER_ITEM_HOME) - .withLongExtra("autoArchiving", 1L) - ); - app.notifier.postAll(null); - app.db.profileDao().add(profile); - if (App.profileId == profile.getId()) { - app.profile.setArchived(true); - } - newCallback.onSuccess(activityContext, profile); - return; - } - - registerEmpty = profile.getEmpty(); - oldLuckyNumber = profile.getLuckyNumber(); - getApi(app, profile.getLoginStoreType()).syncFeature(activityContext, newCallback, profile, featureList); - } else { - new Handler(activityContext.getMainLooper()).post(() -> callback.onError(activityContext, new AppError(TAG, 609, CODE_PROFILE_NOT_FOUND, (String) null))); - } - }); - } - - /* _____ _ _ _____ - / ____| | | |_ _| - | | __| | | | | | __ ___ __ __ _ _ __ _ __ ___ _ __ ___ - | | |_ | | | | | | \ \ /\ / / '__/ _` | '_ \| '_ \ / _ \ '__/ __| - | |__| | |__| |_| |_ \ V V /| | | (_| | |_) | |_) | __/ | \__ \ - \_____|\____/|_____| \_/\_/ |_| \__,_| .__/| .__/ \___|_| |___/ - | | | | - |_| |*/ - /** - * Sync all Edziennik data while showing a progress dialog. - * A wrapper for {@code sync} - * - * Does not switch between threads. - * All callbacks have to be executed on the UI thread. - * - * @param app an App singleton instance - * @param activity a parent activity - * @param profileId ID of the profile to sync - * @param dialogTitle a title of the dialog to show - * @param dialogText dialog's content - * @param successText a toast to show on success - */ - public void guiSync(@NonNull App app, @NonNull Activity activity, int profileId, @StringRes int dialogTitle, @StringRes int dialogText, @StringRes int successText) { - guiSync(app, activity, profileId, dialogTitle, dialogText, successText, (int[])null); - } - public void guiSync(@NonNull App app, @NonNull Activity activity, int profileId, @StringRes int dialogTitle, @StringRes int dialogText, @StringRes int successText, int ... featureList) { - MaterialDialog progressDialog = new MaterialDialog.Builder(activity) - .title(dialogTitle) - .content(dialogText) - .progress(false, PROFILE_MAX_PROGRESS, false) - .canceledOnTouchOutside(false) - .show(); - SyncCallback guiSyncCallback = new SyncCallback() { - @Override - public void onLoginFirst(List profileList, LoginStore loginStore) { - - } - - @Override - public void onSuccess(Context activityContext, ProfileFull profileFull) { - progressDialog.dismiss(); - Toast.makeText(activityContext, successText, Toast.LENGTH_SHORT).show(); - notifyAndReload(); - // profiles are saved automatically, during app.saveConfig in processFinish - /*if (activityContext instanceof MainActivity) { - //((MainActivity) activityContext).reloadCurrentFragment("GuiSync"); - ((MainActivity) activityContext).accountHeaderAddProfiles(); - }*/ - } - - @Override - public void onError(Context activityContext, AppError error) { - progressDialog.dismiss(); - guiShowErrorDialog((Activity) activityContext, error, R.string.sync_error_dialog_title); - } - - @Override - public void onProgress(int progressStep) { - progressDialog.incrementProgress(progressStep); - } - - @Override - public void onActionStarted(int stringResId) { - progressDialog.setContent(activity.getString(R.string.sync_action_format, activity.getString(stringResId))); - } - }; - app.apiEdziennik.sync(app, activity, guiSyncCallback, profileId, featureList); - } - /** - * Sync all Edziennik data in background. - * A callback is executed on main thread. - * A wrapper for {@code sync} - * - * @param app an App singleton instance - * @param activity a parent activity - * @param profileId ID of the profile to sync - * @param syncCallback a callback - * @param feature a feature to sync - */ - public void guiSyncSilent(@NonNull App app, @NonNull Activity activity, int profileId, SyncCallback syncCallback, int feature) { - SyncCallback guiSyncCallback = new SyncCallback() { - @Override - public void onLoginFirst(List profileList, LoginStore loginStore) { - - } - - @Override - public void onSuccess(Context activityContext, ProfileFull profileFull) { - notifyAndReload(); - syncCallback.onSuccess(activityContext, profileFull); - } - - @Override - public void onError(Context activityContext, AppError error) { - syncCallback.onError(activityContext, error); - } - - @Override - public void onProgress(int progressStep) { - syncCallback.onProgress(progressStep); - } - - @Override - public void onActionStarted(int stringResId) { - syncCallback.onActionStarted(stringResId); - } - }; - app.apiEdziennik.sync(app, activity, guiSyncCallback, profileId, feature == FEATURE_ALL ? null : new int[]{feature}); - } - - /** - * Show a dialog allowing the user to choose which features to sync. - * Handles everything including pre-selecting the features basing on the current fragment. - * - * Will execute {@code sync} after the selection is made. - * - * A normal progress dialog is shown during the sync. - * - * @param app an App singleton instance - * @param activity a parent activity - * @param profileId ID of the profile to sync - * @param dialogTitle a title of the dialog to show - * @param dialogText dialog's content - * @param successText a toast to show on success - * @param currentFeature a feature id representing the currently opened fragment or caller - */ - public void guiSyncFeature(@NonNull App app, - @NonNull Activity activity, - int profileId, - @StringRes int dialogTitle, - @StringRes int dialogText, - @StringRes int successText, - int currentFeature) { - - String[] items = new String[]{ - app.getString(R.string.menu_timetable), - app.getString(R.string.menu_agenda), - app.getString(R.string.menu_grades), - app.getString(R.string.menu_homework), - app.getString(R.string.menu_notices), - app.getString(R.string.menu_attendance), - app.getString(R.string.title_messages_inbox_single), - app.getString(R.string.title_messages_sent_single), - app.getString(R.string.menu_announcements) - }; - int[] itemsIds = new int[]{ - FEATURE_TIMETABLE, - FEATURE_AGENDA, - FEATURE_GRADES, - FEATURE_HOMEWORK, - FEATURE_NOTICES, - FEATURE_ATTENDANCE, - FEATURE_MESSAGES_INBOX, - FEATURE_MESSAGES_OUTBOX, - FEATURE_ANNOUNCEMENTS - }; - int[] selectedIndices; - if (currentFeature == FEATURE_ALL) { - selectedIndices = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8}; - } - else { - selectedIndices = new int[]{Arrays.binarySearch(itemsIds, currentFeature)}; - } - - MaterialDialog dialog = new MaterialDialog.Builder(activity) - .title(R.string.sync_feature_title) - .content(R.string.sync_feature_text) - .positiveText(R.string.ok) - .negativeText(R.string.cancel) - .neutralText(R.string.sync_feature_all) - .items(items) - .itemsIds(itemsIds) - .itemsCallbackMultiChoice(ArrayUtils.toWrapperArray(selectedIndices), (dialog1, which, text) -> { - dialog1.getActionButton(DialogAction.POSITIVE).setEnabled(which.length > 0); - return true; - }) - .alwaysCallMultiChoiceCallback() - .onPositive(((dialog1, which) -> { - List featureList = new ArrayList<>(); - for (int i: dialog1.getSelectedIndices()) { - featureList.add(itemsIds[i]); - } - guiSync(app, activity, profileId, dialogTitle, dialogText, successText, ArrayUtils.toPrimitiveArray(featureList)); - })) - .onNeutral(((dialog1, which) -> { - guiSync(app, activity, profileId, dialogTitle, dialogText, successText); - })) - .show(); - - - - } - - public void guiShowArchivedDialog(Activity activity, String profileName) { - new MaterialDialog.Builder(activity) - .title(R.string.profile_archived_dialog_title) - .content(activity.getString(R.string.profile_archived_dialog_text_format, profileName)) - .positiveText(R.string.ok) - .onPositive(((dialog, which) -> dialog.dismiss())) - .autoDismiss(false) - .show(); - } - - /* _____ _ _ _____ - / ____| | | |_ _| - | | __| | | | | | ___ _ __ _ __ ___ _ __ ___ - | | |_ | | | | | | / _ \ '__| '__/ _ \| '__/ __| - | |__| | |__| |_| |_ | __/ | | | | (_) | | \__ \ - \_____|\____/|_____| \___|_| |_| \___/|_| |__*/ - /** - * Used for reporting an exception somewhere in the code that is not part of Edziennik APIs. - * - * @param activity a parent activity - * @param errorLine the line of code where the error occurred - * @param e an Exception object - */ - public void guiReportException(Activity activity, int errorLine, Exception e) { - guiReportError(activity, new AppError(TAG, errorLine, CODE_OTHER, "Błąd wewnętrzny aplikacji ("+errorLine+")", null, null, e, null), null); - } - - public void guiShowErrorDialog(Activity activity, @NonNull AppError error, @StringRes int dialogTitle) { - if (error.errorCode == CODE_PROFILE_ARCHIVED) { - guiShowArchivedDialog(activity, error.errorText); - return; - } - error.changeIfCodeOther(); - new MaterialDialog.Builder(activity) - .title(dialogTitle) - .content(error.asReadableString(activity)) - .positiveText(R.string.ok) - .onPositive(((dialog, which) -> dialog.dismiss())) - .neutralText(R.string.sync_error_dialog_report_button) - .onNeutral(((dialog, which) -> { - guiReportError(activity, error, dialog); - })) - .autoDismiss(false) - .show(); - } - public void guiShowErrorSnackbar(MainActivity activity, @NonNull AppError error) { - if (error.errorCode == CODE_PROFILE_ARCHIVED) { - guiShowArchivedDialog(activity, error.errorText); - return; - } - - // TODO: 2019-08-28 - IconicsDrawable icon = new IconicsDrawable(activity) - .icon(CommunityMaterial.Icon.cmd_alert_circle); - sizeDp(icon, 20); - colorInt(icon, Themes.INSTANCE.getPrimaryTextColor(activity)); - - error.changeIfCodeOther(); - CafeBar.builder(activity) - .to(activity.findViewById(R.id.coordinator)) - .content(error.asReadableString(activity)) - .icon(icon) - .positiveText(R.string.more) - .positiveColor(0xff4caf50) - .negativeText(R.string.ok) - .negativeColor(0x66ffffff) - .onPositive((cafeBar -> guiReportError(activity, error, null))) - .onNegative((cafeBar -> cafeBar.dismiss())) - .autoDismiss(false) - .swipeToDismiss(true) - .floating(true) - .show(); - } - public void guiReportError(Activity activity, AppError error, @Nullable MaterialDialog parentDialogToDisableNeutral) { - String errorDetails = error.getDetails(activity); - String htmlErrorDetails = ""+errorDetails+""; - htmlErrorDetails = htmlErrorDetails.replaceAll(activity.getPackageName(), ""+activity.getPackageName()+""); - htmlErrorDetails = htmlErrorDetails.replaceAll("\n", "
    "); - - new MaterialDialog.Builder(activity) - .title(R.string.sync_report_dialog_title) - .content(Html.fromHtml(htmlErrorDetails)) - .typeface(null, "RobotoMono-Regular.ttf") - .negativeText(R.string.close) - .onNegative(((dialog1, which1) -> dialog1.dismiss())) - .neutralText(R.string.copy_to_clipboard) - .onNeutral((dialog1, which1) -> { - ClipboardManager clipboard = (ClipboardManager) activity.getSystemService(CLIPBOARD_SERVICE); - if (clipboard != null) { - ClipData clip = ClipData.newPlainText("Error report", errorDetails); - clipboard.setPrimaryClip(clip); - Toast.makeText(activity, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show(); - } - }) - .autoDismiss(false) - .positiveText(R.string.sync_report_dialog_button) - .checkBoxPromptRes(R.string.sync_report_dialog_include_api_response, true, null) - .onPositive(((dialog1, which1) -> AsyncTask.execute(() -> error.getApiResponse(activity, apiResponse -> { - new ServerRequest(app, app.requestScheme + APP_URL + "main.php?report", "Edziennik/Report") - .setBodyParameter("base64_encoded", Base64.encodeToString(errorDetails.getBytes(), Base64.DEFAULT)) - .setBodyParameter("api_response", dialog1.isPromptCheckBoxChecked() ? Base64.encodeToString(apiResponse.getBytes(), Base64.DEFAULT) : "VW5jaGVja2Vk"/*Unchecked*/) - .run((e, result) -> { - new Handler(activity.getMainLooper()).post(() -> { - if (result != null) - { - if (result.get("success").getAsBoolean()) { - Toast.makeText(activity, activity.getString(R.string.crash_report_sent), Toast.LENGTH_SHORT).show(); - dialog1.getActionButton(DialogAction.POSITIVE).setEnabled(false); - if (parentDialogToDisableNeutral != null) - parentDialogToDisableNeutral.getActionButton(DialogAction.NEUTRAL).setEnabled(false); - } - else { - Toast.makeText(activity, activity.getString(R.string.crash_report_cannot_send) + ": " + result.get("reason").getAsString(), Toast.LENGTH_LONG).show(); - } - } - else - { - Toast.makeText(activity, activity.getString(R.string.crash_report_cannot_send)+" brak internetu", Toast.LENGTH_LONG).show(); - } - }); - }); - })))) - .show(); - } - - /** - * A method that displays a dialog allowing the user to report an error that has occurred. - * - * @param activity a parent activity - * @param errorCode self-explanatory - * @param errorText additional error information, that replaces text based on {@code errorCode} if it's {@code CODE_OTHER} - * @param throwable a {@link Throwable} containing the error details - * @param apiResponse response of the Edziennik API - * @param parentDialogToDisableNeutral if not null, an instance of {@link MaterialDialog} in which the neutral button should be disabled after submitting an error report - */ - public void guiReportError(Activity activity, int errorCode, String errorText, Throwable throwable, String apiResponse, @Nullable MaterialDialog parentDialogToDisableNeutral) { - // build a string containing the stack trace and the device name + user's registration data - String contentPlain = "Application Internal Error "+stringErrorType(errorCode)+":\n"+stringErrorCode(activity, errorCode, "")+"\n"+errorText+"\n\n"; - contentPlain += Log.getStackTraceString(throwable); - String content = ""+contentPlain+""; - content = content.replaceAll(activity.getPackageName(), ""+activity.getPackageName()+""); - content = content.replaceAll("\n", "
    "); - - contentPlain += "\n"+Build.MANUFACTURER+"\n"+Build.BRAND+"\n"+Build.MODEL+"\n"+Build.DEVICE+"\n"; - if (app.profile != null && app.profile.getRegistration() == REGISTRATION_ENABLED) { - contentPlain += "U: "+app.profile.getUsernameId()+"\nS: "+ app.profile.getStudentNameLong() +"\nT: "+app.profile.loginStoreType()+"\n"; - } - contentPlain += BuildConfig.VERSION_NAME+" "+BuildConfig.BUILD_TYPE+"\nAndroid "+Build.VERSION.RELEASE; - - d(TAG, contentPlain); - d(TAG, apiResponse == null ? "API Response = null" : apiResponse); - - - // show a dialog containing the error details in HTML - String finalContentPlain = contentPlain; - new MaterialDialog.Builder(activity) - .title(R.string.sync_report_dialog_title) - .content(Html.fromHtml(content)) - .typeface(null, "RobotoMono-Regular.ttf") - .negativeText(R.string.close) - .onNegative(((dialog1, which1) -> dialog1.dismiss())) - .neutralText(R.string.copy_to_clipboard) - .onNeutral((dialog1, which1) -> { - ClipboardManager clipboard = (ClipboardManager) activity.getSystemService(CLIPBOARD_SERVICE); - if (clipboard != null) { - ClipData clip = ClipData.newPlainText("Error report", finalContentPlain); - clipboard.setPrimaryClip(clip); - Toast.makeText(activity, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show(); - } - }) - .autoDismiss(false) - .positiveText(R.string.sync_report_dialog_button) - .checkBoxPromptRes(R.string.sync_report_dialog_include_api_response, true, null) - .onPositive(((dialog1, which1) -> { - // send the error report - new ServerRequest(app, app.requestScheme + APP_URL + "main.php?report", "Edziennik/Report") - .setBodyParameter("base64_encoded", Base64.encodeToString(finalContentPlain.getBytes(), Base64.DEFAULT)) - .setBodyParameter("api_response", dialog1.isPromptCheckBoxChecked() ? apiResponse == null ? Base64.encodeToString("NULL XD".getBytes(), Base64.DEFAULT) : Base64.encodeToString(apiResponse.getBytes(), Base64.DEFAULT) : "VW5jaGVja2Vk"/*Unchecked*/) - .run((e, result) -> { - new Handler(Looper.getMainLooper()).post(() -> { - if (result != null) - { - if (result.get("success").getAsBoolean()) { - Toast.makeText(activity, activity.getString(R.string.crash_report_sent), Toast.LENGTH_SHORT).show(); - dialog1.getActionButton(DialogAction.POSITIVE).setEnabled(false); - if (parentDialogToDisableNeutral != null) - parentDialogToDisableNeutral.getActionButton(DialogAction.NEUTRAL).setEnabled(false); - } - else { - Toast.makeText(activity, activity.getString(R.string.crash_report_cannot_send) + ": " + result.get("reason").getAsString(), Toast.LENGTH_LONG).show(); - } - } - else - { - Toast.makeText(activity, activity.getString(R.string.crash_report_cannot_send)+" JsonObject equals null", Toast.LENGTH_LONG).show(); - } - }); - }); - })) - .show(); - } - - /* _____ __ _ _ _ - | __ \ / _(_) | | | - | |__) | __ ___ | |_ _| | ___ _ __ ___ _ __ ___ _____ ____ _| | - | ___/ '__/ _ \| _| | |/ _ \ | '__/ _ \ '_ ` _ \ / _ \ \ / / _` | | - | | | | | (_) | | | | | __/ | | | __/ | | | | | (_) \ V / (_| | | - |_| |_| \___/|_| |_|_|\___| |_| \___|_| |_| |_|\___/ \_/ \__,_|*/ - public void guiRemoveProfile(MainActivity activity, int profileId, String profileName) { - new MaterialDialog.Builder(activity) - .title(R.string.profile_menu_remove_confirm) - .content(activity.getString(R.string.profile_menu_remove_confirm_text_format, profileName, profileName)) - .positiveText(R.string.remove) - .negativeText(R.string.cancel) - .onPositive(((dialog, which) -> { - AsyncTask.execute(() -> { - removeProfile(profileId); - activity.runOnUiThread(() -> { - //activity.drawer.loadItem(DRAWER_ITEM_HOME, null, "ProfileRemoving"); - //activity.recreate(DRAWER_ITEM_HOME); - activity.reloadTarget(); - Toast.makeText(activity, "Profil został usunięty.", Toast.LENGTH_LONG).show(); - }); - }); - })) - .show(); - } - public void removeProfile(int profileId) { - Profile profileObject = app.db.profileDao().getByIdNow(profileId); - if (profileObject == null) - return; - app.db.announcementDao().clear(profileId); - app.db.attendanceDao().clear(profileId); - app.db.eventDao().clear(profileId); - app.db.eventTypeDao().clear(profileId); - app.db.gradeDao().clear(profileId); - app.db.gradeCategoryDao().clear(profileId); - app.db.lessonDao().clear(profileId); - app.db.lessonChangeDao().clear(profileId); - app.db.luckyNumberDao().clear(profileId); - app.db.noticeDao().clear(profileId); - app.db.subjectDao().clear(profileId); - app.db.teacherDao().clear(profileId); - app.db.teamDao().clear(profileId); - app.db.messageRecipientDao().clear(profileId); - app.db.messageDao().clear(profileId); - - int loginStoreId = profileObject.getLoginStoreId(); - List profilesUsingLoginStore = app.db.profileDao().getIdsByLoginStoreIdNow(loginStoreId); - if (profilesUsingLoginStore.size() == 1) { - app.db.loginStoreDao().remove(loginStoreId); - } - app.db.profileDao().remove(profileId); - app.db.metadataDao().deleteAll(profileId); - - List toRemove = new ArrayList<>(); - for (Notification notification: app.appConfig.notifications) { - if (notification.profileId == profileId) { - toRemove.add(notification); - } - } - app.appConfig.notifications.removeAll(toRemove); - - app.profile = null; - App.profileId = -1; - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/EdziennikNotification.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/EdziennikNotification.kt new file mode 100644 index 00000000..0b413356 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/EdziennikNotification.kt @@ -0,0 +1,143 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-1. + */ + +package pl.szczodrzynski.edziennik.data.api + +import android.app.Notification +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationCompat.PRIORITY_MIN +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.ext.Bundle +import pl.szczodrzynski.edziennik.receivers.SzkolnyReceiver +import kotlin.math.roundToInt + + +class EdziennikNotification(val app: App) { + private val notificationManager by lazy { app.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager } + + private val notificationBuilder: NotificationCompat.Builder by lazy { + NotificationCompat.Builder(app, ApiService.NOTIFICATION_API_CHANNEL_ID) + .setSmallIcon(R.drawable.ic_notification) + .setPriority(PRIORITY_MIN) + .setOngoing(true) + .setLocalOnly(true) + } + + val notification: Notification + get() = notificationBuilder.build() + + private var errorCount = 0 + private var criticalErrorCount = 0 + var serviceClosed = false + + private fun cancelPendingIntent(taskId: Int): PendingIntent { + val intent = SzkolnyReceiver.getIntent(app, Bundle( + "task" to "TaskCancelRequest", + "taskId" to taskId + )) + return PendingIntent.getBroadcast(app, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) as PendingIntent + } + private val closePendingIntent: PendingIntent + get() { + val intent = SzkolnyReceiver.getIntent(app, Bundle( + "task" to "ServiceCloseRequest" + )) + return PendingIntent.getBroadcast(app, 0, intent, 0) as PendingIntent + } + + private fun errorCountText(): String? { + var result = "" + if (criticalErrorCount > 0) { + result += app.resources.getQuantityString(R.plurals.critical_errors_format, criticalErrorCount, criticalErrorCount) + } + if (criticalErrorCount > 0 && errorCount > 0) { + result += ", " + } + if (errorCount > 0) { + result += app.resources.getQuantityString(R.plurals.normal_errors_format, errorCount, errorCount) + } + return if (result.isEmpty()) null else result + } + + fun setIdle(): EdziennikNotification { + notificationBuilder.setContentTitle(app.getString(R.string.edziennik_notification_api_title)) + notificationBuilder.setProgress(0, 0, false) + notificationBuilder.apply { + val str = app.getString(R.string.edziennik_notification_api_text) + setStyle(NotificationCompat.BigTextStyle().bigText(str)) + setContentText(str) + } + setCloseAction() + return this + } + + fun addError(): EdziennikNotification { + errorCount++ + return this + } + fun setCriticalError(): EdziennikNotification { + criticalErrorCount++ + notificationBuilder.setContentTitle(app.getString(R.string.edziennik_notification_api_error_title)) + notificationBuilder.setProgress(0, 0, false) + notificationBuilder.apply { + val str = errorCountText() + setStyle(NotificationCompat.BigTextStyle().bigText(str)) + setContentText(str) + } + setCloseAction() + return this + } + + fun setProgress(progress: Float): EdziennikNotification { + notificationBuilder.setProgress(100, progress.roundToInt(), progress < 0f) + return this + } + fun setProgressText(progressText: String?): EdziennikNotification { + notificationBuilder.setContentTitle(progressText) + return this + } + + fun setCurrentTask(taskId: Int, progressText: String?): EdziennikNotification { + notificationBuilder.setProgress(100, 0, true) + notificationBuilder.setContentTitle(progressText) + notificationBuilder.apply { + val str = errorCountText() + setStyle(NotificationCompat.BigTextStyle().bigText(str)) + setContentText(str) + } + setCancelAction(taskId) + return this + } + + fun setCloseAction(): EdziennikNotification { + notificationBuilder.mActions.clear() + notificationBuilder.addAction( + NotificationCompat.Action( + R.drawable.ic_notification, + app.getString(R.string.edziennik_notification_api_close), + closePendingIntent + )) + return this + } + private fun setCancelAction(taskId: Int) { + notificationBuilder.mActions.clear() + notificationBuilder.addAction( + NotificationCompat.Action( + R.drawable.ic_notification, + app.getString(R.string.edziennik_notification_api_cancel), + cancelPendingIntent(taskId) + )) + } + + fun post() { + if (serviceClosed) + return + notificationManager.notify(app.notificationChannelsManager.sync.id, notification) + } + +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/EndpointChooser.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/EndpointChooser.kt new file mode 100644 index 00000000..7f882123 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/EndpointChooser.kt @@ -0,0 +1,117 @@ +package pl.szczodrzynski.edziennik.data.api + +import pl.szczodrzynski.edziennik.data.api.models.Data +import pl.szczodrzynski.edziennik.data.api.models.Feature +import pl.szczodrzynski.edziennik.data.api.models.LoginMethod +import pl.szczodrzynski.edziennik.data.db.entity.EndpointTimer +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_NEVER + +fun Data.prepare(loginMethods: List, features: List, featureIds: List, viewId: Int?, onlyEndpoints: List?) { + val data = this + + val possibleLoginMethods = data.loginMethods.toMutableList() + + for (loginMethod in loginMethods) { + if (loginMethod.isPossible(profile, loginStore)) + possibleLoginMethods += loginMethod.loginMethodId + } + + //var highestLoginMethod = 0 + var endpointList = mutableListOf() + val requiredLoginMethods = mutableListOf() + + data.targetEndpointIds.clear() + data.targetLoginMethodIds.clear() + + // get all endpoints for every feature, only if possible to login and possible/necessary to sync + for (featureId in featureIds) { + features.filter { + it.featureId == featureId // feature ID matches + && possibleLoginMethods.containsAll(it.requiredLoginMethods) // is possible to login + && it.shouldSync?.invoke(data) ?: true // is necessary/possible to sync + }.let { + endpointList.addAll(it) + } + } + + val timestamp = System.currentTimeMillis() + + endpointList = endpointList + // sort the endpoint list by feature ID and priority + .sortedWith(compareBy(Feature::featureId, Feature::priority)) + // select only the most important endpoint for each feature + .distinctBy { it.featureId } + .toMutableList() + // add all endpoint IDs and required login methods, filtering using timers + .onEach { feature -> + feature.endpointIds.forEach { endpoint -> + if (onlyEndpoints?.contains(endpoint.first) == false) + return@forEach + (data.endpointTimers + .singleOrNull { it.endpointId == endpoint.first } ?: EndpointTimer(data.profile?.id + ?: -1, endpoint.first)) + .let { timer -> + if ( + onlyEndpoints?.contains(endpoint.first) == true || + timer.nextSync == SYNC_ALWAYS || + viewId != null && timer.viewId == viewId || + timer.nextSync != SYNC_NEVER && timer.nextSync < timestamp + ) { + data.targetEndpointIds[endpoint.first] = timer.lastSync + requiredLoginMethods.add(endpoint.second) + } + } + } + } + + // check every login method for any dependencies + for (loginMethodId in requiredLoginMethods) { + var requiredLoginMethod: Int? = loginMethodId + while (requiredLoginMethod != LOGIN_METHOD_NOT_NEEDED) { + loginMethods.singleOrNull { it.loginMethodId == requiredLoginMethod }?.let { loginMethod -> + if (requiredLoginMethod != null) + data.targetLoginMethodIds.add(requiredLoginMethod!!) + requiredLoginMethod = loginMethod.requiredLoginMethod(data.profile, data.loginStore) + } + } + } + + // sort and distinct every login method and endpoint + data.targetLoginMethodIds = data.targetLoginMethodIds.toHashSet().toMutableList() + data.targetLoginMethodIds.sort() + + //data.targetEndpointIds = data.targetEndpointIds.toHashSet().toMutableList() + //data.targetEndpointIds.sort() + + progressCount = targetLoginMethodIds.size + targetEndpointIds.size + progressStep = if (progressCount <= 0) 0f else 100f / progressCount.toFloat() +} + +fun Data.prepareFor(loginMethods: List, loginMethodId: Int) { + val possibleLoginMethods = this.loginMethods.toMutableList() + + loginMethods.forEach { + if (it.isPossible(profile, loginStore)) + possibleLoginMethods += it.loginMethodId + } + + targetLoginMethodIds.clear() + + // check the login method for any dependencies + var requiredLoginMethod: Int? = loginMethodId + while (requiredLoginMethod != LOGIN_METHOD_NOT_NEEDED) { + loginMethods.singleOrNull { it.loginMethodId == requiredLoginMethod }?.let { + if (requiredLoginMethod != null) + targetLoginMethodIds.add(requiredLoginMethod!!) + requiredLoginMethod = it.requiredLoginMethod(profile, loginStore) + } + } + + // sort and distinct every login method + targetLoginMethodIds = targetLoginMethodIds.toHashSet().toMutableList() + targetLoginMethodIds.sort() + + progressCount = 0 + progressStep = 0f +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Errors.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Errors.kt new file mode 100644 index 00000000..eefc1d31 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Errors.kt @@ -0,0 +1,235 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-21. + */ + +package pl.szczodrzynski.edziennik.data.api + +/*const val CODE_OTHER = 0 +const val CODE_OK = 1 +const val CODE_NO_INTERNET = 10 +const val CODE_SSL_ERROR = 13 +const val CODE_ARCHIVED = 5 +const val CODE_MAINTENANCE = 6 +const val CODE_LOGIN_ERROR = 7 +const val CODE_ACCOUNT_MISMATCH = 8 +const val CODE_APP_SERVER_ERROR = 9 +const val CODE_MULTIACCOUNT_SETUP = 12 +const val CODE_TIMEOUT = 11 +const val CODE_PROFILE_NOT_FOUND = 14 +const val CODE_ATTACHMENT_NOT_AVAILABLE = 28 +const val CODE_INVALID_LOGIN = 2 +const val CODE_INVALID_SERVER_ADDRESS = 21 +const val CODE_INVALID_SCHOOL_NAME = 22 +const val CODE_INVALID_DEVICE = 23 +const val CODE_OLD_PASSWORD = 4 +const val CODE_INVALID_TOKEN = 24 +const val CODE_EXPIRED_TOKEN = 27 +const val CODE_INVALID_SYMBOL = 25 +const val CODE_INVALID_PIN = 26 +const val CODE_LIBRUS_NOT_ACTIVATED = 29 +const val CODE_SYNERGIA_NOT_ACTIVATED = 32 +const val CODE_LIBRUS_DISCONNECTED = 31 +const val CODE_PROFILE_ARCHIVED = 30*/ + +const val ERROR_APP_CRASH = 1 +const val ERROR_EXCEPTION = 2 +const val ERROR_API_EXCEPTION = 3 +const val ERROR_MESSAGE_NOT_SENT = 10 + +const val ERROR_REQUEST_FAILURE = 50 +const val ERROR_REQUEST_HTTP_400 = 51 +const val ERROR_REQUEST_HTTP_401 = 52 +const val ERROR_REQUEST_HTTP_403 = 53 +const val ERROR_REQUEST_HTTP_404 = 54 +const val ERROR_REQUEST_HTTP_405 = 55 +const val ERROR_REQUEST_HTTP_410 = 56 +const val ERROR_REQUEST_HTTP_424 = 57 +const val ERROR_REQUEST_HTTP_500 = 58 +const val ERROR_REQUEST_HTTP_503 = 59 +const val ERROR_REQUEST_FAILURE_HOSTNAME_NOT_FOUND = 60 +const val ERROR_REQUEST_FAILURE_TIMEOUT = 61 +const val ERROR_REQUEST_FAILURE_NO_INTERNET = 62 +const val ERROR_REQUEST_FAILURE_SSL_ERROR = 63 +const val ERROR_RESPONSE_EMPTY = 100 +const val ERROR_LOGIN_DATA_MISSING = 101 +const val ERROR_PROFILE_MISSING = 105 +const val ERROR_PROFILE_ARCHIVED = 106 +const val ERROR_INVALID_LOGIN_MODE = 110 +const val ERROR_LOGIN_METHOD_NOT_SATISFIED = 111 +const val ERROR_NOT_IMPLEMENTED = 112 +const val ERROR_FILE_DOWNLOAD = 113 + +const val ERROR_NO_STUDENTS_IN_ACCOUNT = 115 + +const val ERROR_CAPTCHA_NEEDED = 3000 +const val ERROR_CAPTCHA_LIBRUS_PORTAL = 3001 + +const val ERROR_API_PDO_ERROR = 5000 +const val ERROR_API_INVALID_CLIENT = 5001 +const val ERROR_API_INVALID_ARGUMENT = 5002 +const val ERROR_API_INVALID_SIGNATURE = 5003 +const val ERROR_API_MISSING_SCOPES = 5004 +const val ERROR_API_RESOURCE_NOT_FOUND = 5005 +const val ERROR_API_INTERNAL_SERVER_ERROR = 5006 +const val ERROR_API_PHP_E_ERROR = 5007 +const val ERROR_API_PHP_E_WARNING = 5008 +const val ERROR_API_PHP_E_PARSE = 5009 +const val ERROR_API_PHP_E_NOTICE = 5010 +const val ERROR_API_PHP_E_OTHER = 5011 +const val ERROR_API_MAINTENANCE = 5012 +const val ERROR_API_MISSING_ARGUMENT = 5013 +const val ERROR_API_PAYLOAD_EMPTY = 5014 +const val ERROR_API_INVALID_ACTION = 5015 +const val ERROR_API_UPDATE_NOT_FOUND = 5016 +const val ERROR_API_INVALID_DEVICEID_USERCODE = 5017 +const val ERROR_API_INVALID_PAIRTOKEN = 5018 +const val ERROR_API_INVALID_BROWSERID = 5019 +const val ERROR_API_INVALID_DEVICEID = 5020 +const val ERROR_API_INVALID_DEVICEID_BROWSERID = 5021 +const val ERROR_API_HELP_CATEGORY_NOT_FOUND = 5022 + +const val CODE_INTERNAL_LIBRUS_ACCOUNT_410 = 120 +const val CODE_INTERNAL_LIBRUS_SYNERGIA_EXPIRED = 121 +const val ERROR_LOGIN_LIBRUS_API_CAPTCHA_NEEDED = 124 +const val ERROR_LOGIN_LIBRUS_API_CONNECTION_PROBLEMS = 125 +const val ERROR_LOGIN_LIBRUS_API_INVALID_CLIENT = 126 +const val ERROR_LOGIN_LIBRUS_API_REG_ACCEPT_NEEDED = 127 +const val ERROR_LOGIN_LIBRUS_API_CHANGE_PASSWORD_ERROR = 128 +const val ERROR_LOGIN_LIBRUS_API_PASSWORD_CHANGE_REQUIRED = 129 +const val ERROR_LOGIN_LIBRUS_API_INVALID_LOGIN = 130 +const val ERROR_LOGIN_LIBRUS_API_OTHER = 131 +const val ERROR_LOGIN_LIBRUS_PORTAL_CSRF_MISSING = 132 +const val ERROR_LOGIN_LIBRUS_PORTAL_NOT_ACTIVATED = 133 +const val ERROR_LOGIN_LIBRUS_PORTAL_ACTION_ERROR = 134 +const val ERROR_LOGIN_LIBRUS_PORTAL_SYNERGIA_TOKEN_MISSING = 139 +const val ERROR_LIBRUS_API_TOKEN_EXPIRED = 140 +const val ERROR_LIBRUS_API_INSUFFICIENT_SCOPES = 141 +const val ERROR_LIBRUS_API_OTHER = 142 +const val ERROR_LIBRUS_API_ACCESS_DENIED = 143 +const val ERROR_LIBRUS_API_RESOURCE_NOT_FOUND = 144 +const val ERROR_LIBRUS_API_DATA_NOT_FOUND = 145 +const val ERROR_LIBRUS_API_TIMETABLE_NOT_PUBLIC = 146 +const val ERROR_LIBRUS_API_RESOURCE_ACCESS_DENIED = 147 +const val ERROR_LIBRUS_API_INVALID_REQUEST_PARAMS = 148 +const val ERROR_LIBRUS_API_INCORRECT_ENDPOINT = 149 +const val ERROR_LIBRUS_API_LUCKY_NUMBER_NOT_ACTIVE = 150 +const val ERROR_LIBRUS_API_NOTES_NOT_ACTIVE = 151 +const val ERROR_LOGIN_LIBRUS_SYNERGIA_NO_TOKEN = 152 +const val ERROR_LOGIN_LIBRUS_SYNERGIA_TOKEN_INVALID = 153 +const val ERROR_LOGIN_LIBRUS_SYNERGIA_NO_SESSION_ID = 154 +const val ERROR_LIBRUS_MESSAGES_ACCESS_DENIED = 155 +const val ERROR_LIBRUS_SYNERGIA_ACCESS_DENIED = 156 +const val ERROR_LOGIN_LIBRUS_MESSAGES_NO_SESSION_ID = 157 +const val ERROR_LIBRUS_PORTAL_ACCESS_DENIED = 158 +const val ERROR_LIBRUS_PORTAL_API_DISABLED = 159 +const val ERROR_LIBRUS_PORTAL_SYNERGIA_DISCONNECTED = 160 +const val ERROR_LIBRUS_PORTAL_OTHER = 161 +const val ERROR_LIBRUS_PORTAL_SYNERGIA_NOT_FOUND = 162 +const val ERROR_LOGIN_LIBRUS_PORTAL_OTHER = 163 +const val ERROR_LOGIN_LIBRUS_PORTAL_CODE_EXPIRED = 164 +const val ERROR_LOGIN_LIBRUS_PORTAL_CODE_REVOKED = 165 +const val ERROR_LOGIN_LIBRUS_PORTAL_NO_CLIENT_ID = 166 +const val ERROR_LOGIN_LIBRUS_PORTAL_NO_CODE = 167 +const val ERROR_LOGIN_LIBRUS_PORTAL_NO_REFRESH = 168 +const val ERROR_LOGIN_LIBRUS_PORTAL_NO_REDIRECT = 169 +const val ERROR_LOGIN_LIBRUS_PORTAL_UNSUPPORTED_GRANT = 170 +const val ERROR_LOGIN_LIBRUS_PORTAL_INVALID_CLIENT_ID = 171 +const val ERROR_LOGIN_LIBRUS_PORTAL_REFRESH_INVALID = 172 +const val ERROR_LOGIN_LIBRUS_PORTAL_REFRESH_REVOKED = 173 +const val ERROR_LIBRUS_SYNERGIA_OTHER = 174 +const val ERROR_LIBRUS_SYNERGIA_MAINTENANCE = 175 +const val ERROR_LIBRUS_MESSAGES_MAINTENANCE = 176 +const val ERROR_LIBRUS_MESSAGES_ERROR = 177 +const val ERROR_LIBRUS_MESSAGES_OTHER = 178 +const val ERROR_LOGIN_LIBRUS_MESSAGES_INVALID_LOGIN = 179 +const val ERROR_LOGIN_LIBRUS_PORTAL_INVALID_LOGIN = 180 +const val ERROR_LIBRUS_API_MAINTENANCE = 181 +const val ERROR_LIBRUS_PORTAL_MAINTENANCE = 182 +const val ERROR_LIBRUS_API_NOTICEBOARD_PROBLEM = 183 +const val ERROR_LOGIN_LIBRUS_PORTAL_CSRF_EXPIRED = 184 +const val ERROR_LIBRUS_API_DEVICE_REGISTERED = 185 +const val ERROR_LIBRUS_MESSAGES_NOT_FOUND = 186 +const val ERROR_LOGIN_LIBRUS_API_INVALID_REQUEST = 187 +const val ERROR_LIBRUS_MESSAGES_ATTACHMENT_NOT_FOUND = 188 +const val ERROR_LOGIN_LIBRUS_MESSAGES_TIMEOUT = 189 + +const val ERROR_LOGIN_MOBIDZIENNIK_WEB_INVALID_LOGIN = 201 +const val ERROR_LOGIN_MOBIDZIENNIK_WEB_OLD_PASSWORD = 202 +const val ERROR_LOGIN_MOBIDZIENNIK_WEB_INVALID_DEVICE = 203 +const val ERROR_LOGIN_MOBIDZIENNIK_WEB_ARCHIVED = 204 +const val ERROR_LOGIN_MOBIDZIENNIK_WEB_MAINTENANCE = 205 +const val ERROR_LOGIN_MOBIDZIENNIK_WEB_INVALID_ADDRESS = 206 +const val ERROR_LOGIN_MOBIDZIENNIK_WEB_OTHER = 210 +const val ERROR_MOBIDZIENNIK_WEB_ACCESS_DENIED = 211 +const val ERROR_MOBIDZIENNIK_WEB_NO_SESSION_KEY = 212 +const val ERROR_MOBIDZIENNIK_WEB_NO_SESSION_VALUE = 216 +const val ERROR_MOBIDZIENNIK_WEB_NO_SERVER_ID = 213 +const val ERROR_MOBIDZIENNIK_WEB_INVALID_RESPONSE = 214 +const val ERROR_LOGIN_MOBIDZIENNIK_WEB_NO_SESSION_ID = 215 +const val ERROR_LOGIN_MOBIDZIENNIK_API2_INVALID_LOGIN = 216 +const val ERROR_LOGIN_MOBIDZIENNIK_API2_OTHER = 217 +const val ERROR_MOBIDZIENNIK_WEB_SERVER_PROBLEM = 218 + +const val ERROR_LOGIN_VULCAN_INVALID_SYMBOL = 301 +const val ERROR_LOGIN_VULCAN_INVALID_TOKEN = 302 +const val ERROR_LOGIN_VULCAN_INVALID_PIN_0_REMAINING = 310 +const val ERROR_LOGIN_VULCAN_INVALID_PIN_1_REMAINING = 311 +const val ERROR_LOGIN_VULCAN_INVALID_PIN_2_REMAINING = 312 +const val ERROR_LOGIN_VULCAN_EXPIRED_TOKEN = 321 +const val ERROR_LOGIN_VULCAN_NO_PUPILS = 331 +const val ERROR_VULCAN_ATTACHMENT_DOWNLOAD = 343 +const val ERROR_VULCAN_WEB_DATA_MISSING = 344 +const val ERROR_VULCAN_WEB_429 = 345 +const val ERROR_VULCAN_WEB_OTHER = 346 +const val ERROR_VULCAN_WEB_NO_CERTIFICATE = 347 +const val ERROR_VULCAN_WEB_NO_REGISTER = 348 +const val ERROR_VULCAN_WEB_CERTIFICATE_EXPIRED = 349 +const val ERROR_VULCAN_WEB_LOGGED_OUT = 350 +const val ERROR_VULCAN_WEB_CERTIFICATE_POST_FAILED = 351 +const val ERROR_VULCAN_WEB_GRADUATE_ACCOUNT = 352 +const val ERROR_VULCAN_WEB_NO_SCHOOLS = 353 +const val ERROR_VULCAN_HEBE_OTHER = 354 +const val ERROR_VULCAN_HEBE_SIGNATURE_ERROR = 360 +const val ERROR_VULCAN_HEBE_INVALID_PAYLOAD = 361 +const val ERROR_VULCAN_HEBE_FIREBASE_ERROR = 362 +const val ERROR_VULCAN_HEBE_CERTIFICATE_GONE = 363 +const val ERROR_VULCAN_HEBE_SERVER_ERROR = 364 +const val ERROR_VULCAN_HEBE_ENTITY_NOT_FOUND = 365 +const val ERROR_VULCAN_HEBE_MISSING_SENDER_ENTRY = 366 +const val ERROR_VULCAN_API_DEPRECATED = 390 + +const val ERROR_LOGIN_EDUDZIENNIK_WEB_INVALID_LOGIN = 501 +const val ERROR_LOGIN_EDUDZIENNIK_WEB_OTHER = 510 +const val ERROR_LOGIN_EDUDZIENNIK_WEB_NO_SESSION_ID = 511 +const val ERROR_EDUDZIENNIK_WEB_LIMITED_ACCESS = 521 +const val ERROR_EDUDZIENNIK_WEB_SESSION_EXPIRED = 522 +const val ERROR_EDUDZIENNIK_WEB_TEAM_MISSING = 530 + +const val ERROR_LOGIN_PODLASIE_API_INVALID_TOKEN = 601 +const val ERROR_LOGIN_PODLASIE_API_DEVICE_LIMIT = 602 +const val ERROR_PODLASIE_API_NO_TOKEN = 630 +const val ERROR_PODLASIE_API_OTHER = 631 +const val ERROR_PODLASIE_API_DATA_MISSING = 632 + +const val ERROR_TEMPLATE_WEB_OTHER = 801 + +const val EXCEPTION_API_TASK = 900 +const val EXCEPTION_LOGIN_LIBRUS_API_TOKEN = 901 +const val EXCEPTION_LOGIN_LIBRUS_PORTAL_TOKEN = 902 +const val EXCEPTION_LIBRUS_PORTAL_SYNERGIA_TOKEN = 903 +const val EXCEPTION_LIBRUS_API_REQUEST = 904 +const val EXCEPTION_LIBRUS_SYNERGIA_REQUEST = 905 +const val EXCEPTION_MOBIDZIENNIK_WEB_REQUEST = 906 +const val EXCEPTION_MOBIDZIENNIK_WEB_FILE_REQUEST = 908 +const val EXCEPTION_LIBRUS_MESSAGES_FILE_REQUEST = 909 +const val EXCEPTION_NOTIFY = 910 +const val EXCEPTION_LIBRUS_MESSAGES_REQUEST = 911 +const val EXCEPTION_EDUDZIENNIK_WEB_REQUEST = 920 +const val EXCEPTION_EDUDZIENNIK_FILE_REQUEST = 921 +const val ERROR_ONEDRIVE_DOWNLOAD = 930 +const val EXCEPTION_VULCAN_WEB_LOGIN = 931 +const val EXCEPTION_VULCAN_WEB_REQUEST = 932 +const val EXCEPTION_PODLASIE_API_REQUEST = 940 +const val EXCEPTION_VULCAN_HEBE_REQUEST = 950 + +const val LOGIN_NO_ARGUMENTS = 1201 diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Features.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Features.kt new file mode 100644 index 00000000..e38b37b5 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Features.kt @@ -0,0 +1,86 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-29. + */ + +package pl.szczodrzynski.edziennik.data.api + +import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_AGENDA +import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_ANNOUNCEMENTS +import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_ATTENDANCE +import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_BEHAVIOUR +import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_GRADES +import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_HOME +import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_HOMEWORK +import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_MESSAGES +import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_TIMETABLE +import pl.szczodrzynski.edziennik.data.db.entity.Message.Companion.TYPE_RECEIVED +import pl.szczodrzynski.edziennik.data.db.entity.Message.Companion.TYPE_SENT + +internal const val FEATURE_TIMETABLE = 1 +internal const val FEATURE_AGENDA = 2 +internal const val FEATURE_GRADES = 3 +internal const val FEATURE_HOMEWORK = 4 +internal const val FEATURE_BEHAVIOUR = 5 +internal const val FEATURE_ATTENDANCE = 6 +internal const val FEATURE_MESSAGES_INBOX = 7 +internal const val FEATURE_MESSAGES_SENT = 8 +internal const val FEATURE_ANNOUNCEMENTS = 9 + +internal const val FEATURE_ALWAYS_NEEDED = 100 +internal const val FEATURE_STUDENT_INFO = 101 +internal const val FEATURE_STUDENT_NUMBER = 109 +internal const val FEATURE_SCHOOL_INFO = 102 +internal const val FEATURE_CLASS_INFO = 103 +internal const val FEATURE_TEAM_INFO = 104 +internal const val FEATURE_LUCKY_NUMBER = 105 +internal const val FEATURE_TEACHERS = 106 +internal const val FEATURE_SUBJECTS = 107 +internal const val FEATURE_CLASSROOMS = 108 +internal const val FEATURE_PUSH_CONFIG = 120 + +object Features { + private fun getAllNecessary(): List = listOf( + FEATURE_ALWAYS_NEEDED, + FEATURE_PUSH_CONFIG, + FEATURE_STUDENT_INFO, + FEATURE_STUDENT_NUMBER, + FEATURE_SCHOOL_INFO, + FEATURE_CLASS_INFO, + FEATURE_TEAM_INFO, + FEATURE_LUCKY_NUMBER, + FEATURE_TEACHERS, + FEATURE_SUBJECTS, + FEATURE_CLASSROOMS) + + private fun getAllFeatures(): List = listOf( + FEATURE_TIMETABLE, + FEATURE_AGENDA, + FEATURE_GRADES, + FEATURE_HOMEWORK, + FEATURE_BEHAVIOUR, + FEATURE_ATTENDANCE, + FEATURE_MESSAGES_INBOX, + FEATURE_MESSAGES_SENT, + FEATURE_ANNOUNCEMENTS) + + fun getAllIds(): List = getAllFeatures() + getAllNecessary() + + fun getIdsByView(targetId: Int, targetType: Int): List { + return (when (targetId) { + DRAWER_ITEM_HOME -> getAllFeatures() + DRAWER_ITEM_TIMETABLE -> listOf(FEATURE_TIMETABLE) + DRAWER_ITEM_AGENDA -> listOf(FEATURE_AGENDA) + DRAWER_ITEM_GRADES -> listOf(FEATURE_GRADES) + DRAWER_ITEM_MESSAGES -> when (targetType) { + TYPE_RECEIVED -> listOf(FEATURE_MESSAGES_INBOX) + TYPE_SENT -> listOf(FEATURE_MESSAGES_SENT) + else -> listOf(FEATURE_MESSAGES_INBOX, FEATURE_MESSAGES_SENT) + } + DRAWER_ITEM_HOMEWORK -> listOf(FEATURE_HOMEWORK) + DRAWER_ITEM_BEHAVIOUR -> listOf(FEATURE_BEHAVIOUR) + DRAWER_ITEM_ATTENDANCE -> listOf(FEATURE_ATTENDANCE) + DRAWER_ITEM_ANNOUNCEMENTS -> listOf(FEATURE_ANNOUNCEMENTS) + else -> getAllFeatures() + } + getAllNecessary()).sorted() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Iuczniowie.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Iuczniowie.java deleted file mode 100644 index 33c69671..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Iuczniowie.java +++ /dev/null @@ -1,1710 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api; - -import android.content.Context; -import android.graphics.Color; -import android.os.AsyncTask; -import android.os.Handler; -import android.util.Log; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.core.util.Pair; - -import com.crashlytics.android.Crashlytics; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonNull; -import com.google.gson.JsonObject; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import im.wangchao.mhttp.Request; -import im.wangchao.mhttp.Response; -import im.wangchao.mhttp.body.MediaTypeUtils; -import im.wangchao.mhttp.callback.JsonArrayCallbackHandler; -import im.wangchao.mhttp.callback.JsonCallbackHandler; -import im.wangchao.mhttp.callback.TextCallbackHandler; -import okhttp3.Cookie; -import okhttp3.HttpUrl; -import pl.szczodrzynski.edziennik.App; -import pl.szczodrzynski.edziennik.BuildConfig; -import pl.szczodrzynski.edziennik.R; -import pl.szczodrzynski.edziennik.data.api.interfaces.AttachmentGetCallback; -import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface; -import pl.szczodrzynski.edziennik.data.api.interfaces.LoginCallback; -import pl.szczodrzynski.edziennik.data.api.interfaces.MessageGetCallback; -import pl.szczodrzynski.edziennik.data.api.interfaces.RecipientListGetCallback; -import pl.szczodrzynski.edziennik.data.api.interfaces.SyncCallback; -import pl.szczodrzynski.edziennik.data.db.modules.announcements.Announcement; -import pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance; -import pl.szczodrzynski.edziennik.data.db.modules.events.Event; -import pl.szczodrzynski.edziennik.data.db.modules.grades.Grade; -import pl.szczodrzynski.edziennik.data.db.modules.lessons.Lesson; -import pl.szczodrzynski.edziennik.data.db.modules.lessons.LessonChange; -import pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore; -import pl.szczodrzynski.edziennik.data.db.modules.luckynumber.LuckyNumber; -import pl.szczodrzynski.edziennik.data.db.modules.messages.Message; -import pl.szczodrzynski.edziennik.data.db.modules.messages.MessageFull; -import pl.szczodrzynski.edziennik.data.db.modules.messages.MessageRecipient; -import pl.szczodrzynski.edziennik.data.db.modules.messages.MessageRecipientFull; -import pl.szczodrzynski.edziennik.data.db.modules.metadata.Metadata; -import pl.szczodrzynski.edziennik.data.db.modules.notices.Notice; -import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile; -import pl.szczodrzynski.edziennik.data.db.modules.profiles.ProfileFull; -import pl.szczodrzynski.edziennik.data.db.modules.subjects.Subject; -import pl.szczodrzynski.edziennik.data.db.modules.teachers.Teacher; -import pl.szczodrzynski.edziennik.data.db.modules.teams.Team; -import pl.szczodrzynski.edziennik.ui.modules.messages.MessagesComposeInfo; -import pl.szczodrzynski.edziennik.utils.models.Date; -import pl.szczodrzynski.edziennik.utils.models.Endpoint; -import pl.szczodrzynski.edziennik.utils.models.Time; -import pl.szczodrzynski.edziennik.utils.models.Week; - -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_INVALID_LOGIN; -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_INVALID_SCHOOL_NAME; -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_MAINTENANCE; -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_OTHER; -import static pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance.TYPE_ABSENT; -import static pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance.TYPE_ABSENT_EXCUSED; -import static pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance.TYPE_BELATED; -import static pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance.TYPE_PRESENT; -import static pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance.TYPE_RELEASED; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_SEMESTER1_FINAL; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_SEMESTER1_PROPOSED; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_YEAR_FINAL; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_YEAR_PROPOSED; -import static pl.szczodrzynski.edziennik.data.db.modules.lessons.LessonChange.TYPE_CANCELLED; -import static pl.szczodrzynski.edziennik.data.db.modules.lessons.LessonChange.TYPE_CHANGE; -import static pl.szczodrzynski.edziennik.data.db.modules.messages.Message.TYPE_DELETED; -import static pl.szczodrzynski.edziennik.data.db.modules.messages.Message.TYPE_RECEIVED; -import static pl.szczodrzynski.edziennik.data.db.modules.messages.Message.TYPE_SENT; -import static pl.szczodrzynski.edziennik.data.db.modules.notices.Notice.TYPE_NEGATIVE; -import static pl.szczodrzynski.edziennik.data.db.modules.notices.Notice.TYPE_NEUTRAL; -import static pl.szczodrzynski.edziennik.data.db.modules.notices.Notice.TYPE_POSITIVE; -import static pl.szczodrzynski.edziennik.utils.Utils.crc16; -import static pl.szczodrzynski.edziennik.utils.Utils.crc32; -import static pl.szczodrzynski.edziennik.utils.Utils.d; -import static pl.szczodrzynski.edziennik.utils.Utils.getWordGradeValue; - -public class Iuczniowie implements EdziennikInterface { - public Iuczniowie(App app) { - this.app = app; - } - - private static final String TAG = "api.Iuczniowie"; - private static String IDZIENNIK_URL = "https://iuczniowie.progman.pl/idziennik"; - private static final String userAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36"; - - private App app; - private Context activityContext = null; - private SyncCallback callback = null; - private int profileId = -1; - private Profile profile = null; - private LoginStore loginStore = null; - private boolean fullSync = true; - private Date today = Date.getToday(); - private List targetEndpoints = new ArrayList<>(); - - // PROGRESS - private static final int PROGRESS_LOGIN = 10; - private int PROGRESS_COUNT = 1; - private int PROGRESS_STEP = (90/PROGRESS_COUNT); - - private int onlyFeature = FEATURE_ALL; - - private List teamList; - private List teacherList; - private List subjectList; - private List lessonList; - private List lessonChangeList; - private List gradeList; - private List eventList; - private List noticeList; - private List attendanceList; - private List announcementList; - private List messageList; - private List messageRecipientList; - private List messageRecipientIgnoreList; - private List metadataList; - private List messageMetadataList; - - private static boolean fakeLogin = false; - private String lastLogin = ""; - private long lastLoginTime = -1; - private String lastResponse = null; - private String loginSchoolName = null; - private String loginUsername = null; - private String loginPassword = null; - private String loginBearerToken = null; - private int loginRegisterId = -1; - private int loginSchoolYearId = -1; - private String loginStudentId = null; - private int teamClassId = -1; - - private boolean prepare(@NonNull Context activityContext, @NonNull SyncCallback callback, int profileId, @Nullable Profile profile, @NonNull LoginStore loginStore) { - this.activityContext = activityContext; - this.callback = callback; - this.profileId = profileId; - // here we must have a login store: either with a correct ID or -1 - // there may be no profile and that's when onLoginFirst happens - this.profile = profile; - this.loginStore = loginStore; - this.fullSync = profile == null || profile.getEmpty() || profile.shouldFullSync(activityContext); - this.today = Date.getToday(); - - this.loginSchoolName = loginStore.getLoginData("schoolName", ""); - this.loginUsername = loginStore.getLoginData("username", ""); - this.loginPassword = loginStore.getLoginData("password", ""); - if (loginSchoolName.equals("") || loginUsername.equals("") || loginPassword.equals("")) { - finishWithError(new AppError(TAG, 162, CODE_INVALID_LOGIN, "Login field is empty")); - return false; - } - fakeLogin = BuildConfig.DEBUG && loginUsername.startsWith("FAKE"); - IDZIENNIK_URL = fakeLogin ? "http://szkolny.eu/idziennik" : "https://iuczniowie.progman.pl/idziennik"; - - teamList = profileId == -1 ? new ArrayList<>() : app.db.teamDao().getAllNow(profileId); - teacherList = profileId == -1 ? new ArrayList<>() : app.db.teacherDao().getAllNow(profileId); - subjectList = profileId == -1 ? new ArrayList<>() : app.db.subjectDao().getAllNow(profileId); - lessonList = new ArrayList<>(); - lessonChangeList = new ArrayList<>(); - gradeList = new ArrayList<>(); - eventList = new ArrayList<>(); - noticeList = new ArrayList<>(); - attendanceList = new ArrayList<>(); - announcementList = new ArrayList<>(); - messageList = new ArrayList<>(); - messageRecipientList = new ArrayList<>(); - messageRecipientIgnoreList = new ArrayList<>(); - metadataList = new ArrayList<>(); - messageMetadataList = new ArrayList<>(); - - return true; - } - - @Override - public void sync(@NonNull Context activityContext, @NonNull SyncCallback callback, int profileId, @Nullable Profile profile, @NonNull LoginStore loginStore) { - if (!prepare(activityContext, callback, profileId, profile, loginStore)) - return; - - login(() -> { - targetEndpoints = new ArrayList<>(); - targetEndpoints.add("LuckyNumberAndSemesterDates"); - targetEndpoints.add("Timetable"); - targetEndpoints.add("Grades"); - targetEndpoints.add("PropositionGrades"); - targetEndpoints.add("Exams"); - targetEndpoints.add("Notices"); - targetEndpoints.add("Announcements"); - targetEndpoints.add("Attendance"); - targetEndpoints.add("MessagesInbox"); - targetEndpoints.add("MessagesOutbox"); - targetEndpoints.add("Finish"); - PROGRESS_COUNT = targetEndpoints.size()-1; - PROGRESS_STEP = (90/PROGRESS_COUNT); - begin(); - }); - } - @Override - public void syncFeature(@NonNull Context activityContext, @NonNull SyncCallback callback, @NonNull ProfileFull profile, int ... featureList) { - if (featureList == null) { - sync(activityContext, callback, profile.getId(), profile, LoginStore.fromProfileFull(profile)); - return; - } - if (!prepare(activityContext, callback, profile.getId(), profile, LoginStore.fromProfileFull(profile))) - return; - - login(() -> { - targetEndpoints = new ArrayList<>(); - if (featureList.length == 1) - onlyFeature = featureList[0]; - targetEndpoints.add("LuckyNumberAndSemesterDates"); - for (int feature: featureList) { - switch (feature) { - case FEATURE_TIMETABLE: - targetEndpoints.add("Timetable"); - break; - case FEATURE_AGENDA: - targetEndpoints.add("Exams"); - break; - case FEATURE_GRADES: - targetEndpoints.add("Grades"); - targetEndpoints.add("PropositionGrades"); - break; - case FEATURE_HOMEWORK: - targetEndpoints.add("Homework"); - break; - case FEATURE_NOTICES: - targetEndpoints.add("Notices"); - break; - case FEATURE_ATTENDANCE: - targetEndpoints.add("Attendance"); - break; - case FEATURE_MESSAGES_INBOX: - targetEndpoints.add("MessagesInbox"); - break; - case FEATURE_MESSAGES_OUTBOX: - targetEndpoints.add("MessagesOutbox"); - break; - case FEATURE_ANNOUNCEMENTS: - targetEndpoints.add("Announcements"); - break; - } - } - targetEndpoints.add("Finish"); - PROGRESS_COUNT = targetEndpoints.size()-1; - PROGRESS_STEP = (90/PROGRESS_COUNT); - begin(); - }); - } - - private void begin() { - List cookieList = app.cookieJar.loadForRequest(HttpUrl.get(IDZIENNIK_URL)); - for (Cookie cookie: cookieList) { - if (cookie.name().equalsIgnoreCase("Bearer")) { - loginBearerToken = cookie.value(); - } - } - loginStudentId = profile.getStudentData("studentId", null); - loginSchoolYearId = profile.getStudentData("schoolYearId", -1); - loginRegisterId = profile.getStudentData("registerId", -1); - - if (loginRegisterId == -1) { - finishWithError(new AppError(TAG, 212, CODE_OTHER, app.getString(R.string.error_register_id_not_found), "loginRegisterId == -1")); - return; - } - if (loginSchoolYearId == -1) { - finishWithError(new AppError(TAG, 216, CODE_OTHER, app.getString(R.string.error_school_year_not_found), "loginSchoolYearId == -1")); - return; - } - if (loginStudentId == null) { - if (lastResponse == null) { - lastLoginTime = -1; - lastLogin = ""; - finishWithError(new AppError(TAG, 223, CODE_OTHER, app.getString(R.string.error_student_id_not_found), "loginStudentId == null && lastResponse == null")); - return; - } - Matcher selectMatcher = Pattern.compile("", Pattern.DOTALL).matcher(lastResponse); - if (!selectMatcher.find()) { - finishWithError(new AppError(TAG, 228, CODE_OTHER, app.getString(R.string.error_register_id_not_found), lastResponse)); - return; - } - Matcher idMatcher = Pattern.compile(".*?", Pattern.DOTALL).matcher(selectMatcher.group(0)); - while (idMatcher.find()) { - loginStudentId = idMatcher.group(1); - profile.putStudentData("studentId", loginStudentId); - } - } - - this.attendanceMonth = today.month; - this.attendanceYear = today.year; - this.attendancePrevMonthChecked = false; - this.examsMonth = today.month; - this.examsYear = today.year; - this.examsMonthsChecked = 0; - this.examsNextMonthChecked = false; - - callback.onProgress(PROGRESS_LOGIN); - - r("get", null); - } - - private void r(String type, String endpoint) { - // endpoint == null when beginning - if (endpoint == null) - endpoint = targetEndpoints.get(0); - int index = -1; - for (String request: targetEndpoints) { - index++; - if (request.equals(endpoint)) { - break; - } - } - if (type.equals("finish")) { - // called when finishing the action - callback.onProgress(PROGRESS_STEP); - index++; - } - d(TAG, "Called r("+type+", "+endpoint+"). Getting "+targetEndpoints.get(index)); - switch (targetEndpoints.get(index)) { - case "LuckyNumberAndSemesterDates": - getLuckyNumberAndSemesterDates(); - break; - case "Timetable": - getTimetable(); - break; - case "Grades": - getGrades(); - break; - case "PropositionGrades": - getPropositionGrades(); - break; - case "Exams": - getExams(); - break; - case "Notices": - getNotices(); - break; - case "Announcements": - getAnnouncements(); - break; - case "Attendance": - getAttendance(); - break; - case "MessagesInbox": - getMessagesInbox(); - break; - case "MessagesOutbox": - getMessagesOutbox(); - break; - case "Finish": - finish(); - break; - } - } - private void saveData() { - if (teamList.size() > 0) { - //app.db.teamDao().clear(profileId); - app.db.teamDao().addAll(teamList); - } - if (teacherList.size() > 0) - app.db.teacherDao().addAll(teacherList); - if (subjectList.size() > 0) - app.db.subjectDao().addAll(subjectList); - if (lessonList.size() > 0) { - app.db.lessonDao().clear(profileId); - app.db.lessonDao().addAll(lessonList); - } - if (lessonChangeList.size() > 0) - app.db.lessonChangeDao().addAll(lessonChangeList); - if (gradeList.size() > 0) { - app.db.gradeDao().clear(profileId); - app.db.gradeDao().addAll(gradeList); - } - if (eventList.size() > 0) { - app.db.eventDao().removeFuture(profileId, today); - app.db.eventDao().addAll(eventList); - } - if (noticeList.size() > 0) { - app.db.noticeDao().clear(profileId); - app.db.noticeDao().addAll(noticeList); - } - if (attendanceList.size() > 0) - app.db.attendanceDao().addAll(attendanceList); - if (announcementList.size() > 0) - app.db.announcementDao().addAll(announcementList); - if (messageList.size() > 0) - app.db.messageDao().addAllIgnore(messageList); - if (messageRecipientList.size() > 0) - app.db.messageRecipientDao().addAll(messageRecipientList); - if (messageRecipientIgnoreList.size() > 0) - app.db.messageRecipientDao().addAllIgnore(messageRecipientIgnoreList); - if (metadataList.size() > 0) - app.db.metadataDao().addAllIgnore(metadataList); - if (messageMetadataList.size() > 0) - app.db.metadataDao().setSeen(messageMetadataList); - } - private void finish() { - try { - saveData(); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 363, CODE_OTHER, app.getString(R.string.sync_error_saving_data), null, null, e, null)); - } - if (fullSync) { - profile.setLastFullSync(System.currentTimeMillis()); - fullSync = false; - } - profile.setEmpty(false); - callback.onSuccess(activityContext, new ProfileFull(profile, loginStore)); - } - private void finishWithError(AppError error) { - try { - saveData(); - } - catch (Exception e) { - Crashlytics.logException(e); - } - callback.onError(activityContext, error); - } - - /* _ _ - | | (_) - | | ___ __ _ _ _ __ - | | / _ \ / _` | | '_ \ - | |___| (_) | (_| | | | | | - |______\___/ \__, |_|_| |_| - __/ | - |__*/ - private void login(@NonNull LoginCallback loginCallback) { - if (lastLogin.equals(loginSchoolName +":"+ loginUsername) - && System.currentTimeMillis() - lastLoginTime < 5 * 60 * 1000 - && profile != null) { // less than 5 minutes, use the already logged in account - loginCallback.onSuccess(); - return; - } - app.cookieJar.clearForDomain("iuczniowie.progman.pl"); - callback.onActionStarted(R.string.sync_action_logging_in); - Request.builder() - .url(IDZIENNIK_URL +"/login.aspx") - .userAgent(userAgent) - .callback(new TextCallbackHandler() { - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 389, CODE_OTHER, response, throwable)); - } - - @Override - public void onSuccess(String data1, Response response1) { - if (data1 == null || data1.equals("")) { // for safety - finishWithError(new AppError(TAG, 395, CODE_MAINTENANCE, response1)); - return; - } - //Log.d(TAG, "r:"+data); - Request.Builder builder = Request.builder() - .url(IDZIENNIK_URL +"/login.aspx") - .userAgent(userAgent) - //.withClient(app.httpLazy) - .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/png,*/*;q=0.8") - .addHeader("Cache-Control", "max-age=0") - .addHeader("Origin", "https://iuczniowie.progman.pl") - .addHeader("Referer", "https://iuczniowie.progman.pl/idziennik/login.aspx") - .addHeader("Upgrade-Insecure-Requests", "1") - .contentType(MediaTypeUtils.APPLICATION_FORM) - .addParameter("ctl00$ContentPlaceHolder$nazwaPrzegladarki", userAgent) - .addParameter("ctl00$ContentPlaceHolder$NazwaSzkoly", loginSchoolName) - .addParameter("ctl00$ContentPlaceHolder$UserName", loginUsername) - .addParameter("ctl00$ContentPlaceHolder$Password", loginPassword) - .addParameter("ctl00$ContentPlaceHolder$captcha", "") - .addParameter("ctl00$ContentPlaceHolder$Logowanie", "Zaloguj") - .post(); - - // extract hidden form fields __VIEWSTATE __VIEWSTATEGENERATOR __EVENTVALIDATION - //Pattern pattern = Pattern.compile("<.+?name=\"__VIEWSTATE\".+?value=\"([A-z0-9+/=]+)\".+?name=\"__VIEWSTATEGENERATOR\".+?value=\"([A-z0-9+/=]+)\".+?name=\"__EVENTVALIDATION\".+?value=\"([A-z0-9+/=]+)\".+?>", Pattern.DOTALL); - //Pattern pattern = Pattern.compile("]* name=[\"']([^'\"]*)|)(?=[^>]* value=[\"']([^'\"]*)|)", Pattern.DOTALL); - Pattern pattern = Pattern.compile("", Pattern.DOTALL); - Matcher matcher = pattern.matcher(data1); - while (matcher.find()) { - //Log.d(TAG, "Match: "+matcher.group(1)+"="+matcher.group(2)); - builder.addParameter(matcher.group(1), matcher.group(2)); - } - - builder.callback(new TextCallbackHandler() { - @Override - public void onSuccess(String data2, Response response2) { - callback.onProgress(PROGRESS_LOGIN); - Pattern errorPattern = Pattern.compile("id=\"spanErrorMessage\">(.*?)", Pattern.DOTALL).matcher(data2); - if (!selectMatcher.find()) { - finishWithError(new AppError(TAG, 473, CODE_OTHER, app.getString(R.string.error_register_id_not_found), response2, data2)); - return; - } - Log.d(TAG, "g" + selectMatcher.group(0)); - Matcher idMatcher = Pattern.compile("(.+?)\\s(.+?)\\s*\\((.+?),\\s*(.+?)\\)", Pattern.DOTALL).matcher(selectMatcher.group(0)); - while (idMatcher.find()) { - if (loginRegisterId != Integer.parseInt(idMatcher.group(1))) - continue; - String teamClassName = idMatcher.group(4) + " " + idMatcher.group(5); - teamClassId = crc16(teamClassName.getBytes()); - app.db.teamDao().add(new Team( - profileId, - teamClassId, - teamClassName, - 1, - loginSchoolName+":"+teamClassName, - -1 - )); - } - loginCallback.onSuccess(); - return; - } - try { - Matcher yearMatcher = Pattern.compile("name=\"ctl00\\$dxComboRokSzkolny\".+?selected=\"selected\".*?value=\"([0-9]+)\"", Pattern.DOTALL).matcher(data2); - if (yearMatcher.find()) { - try { - loginSchoolYearId = Integer.parseInt(yearMatcher.group(1)); - } catch (Exception ex) { - finishWithError(new AppError(TAG, 501, CODE_OTHER, response2, ex, data2)); - return; - } - } else { - if (data2.contains("Hasło dostępu do systemu wygasło")) { - finishWithError(new AppError(TAG, 504, CODE_OTHER, app.getString(R.string.error_must_change_password), response2, data2)); - return; - } - finishWithError(new AppError(TAG, 507, CODE_OTHER, app.getString(R.string.error_school_year_not_found), response2, data2)); - return; - } - - List studentIds = new ArrayList<>(); - List registerIds = new ArrayList<>(); - List studentNamesLong = new ArrayList<>(); - List studentNamesShort = new ArrayList<>(); - List studentTeams = new ArrayList<>(); - - Matcher selectMatcher = Pattern.compile("", Pattern.DOTALL).matcher(data2); - if (!selectMatcher.find()) { - finishWithError(new AppError(TAG, 519, CODE_OTHER, app.getString(R.string.error_register_id_not_found), response2, data2)); - return; - } - Log.d(TAG, "g" + selectMatcher.group(0)); - Matcher idMatcher = Pattern.compile("(.+?)\\s(.+?)\\s*\\((.+?),\\s*(.+?)\\)", Pattern.DOTALL).matcher(selectMatcher.group(0)); - while (idMatcher.find()) { - registerIds.add(Integer.parseInt(idMatcher.group(1))); - String studentId = idMatcher.group(2); - String studentFirstName = idMatcher.group(3); - String studentLastName = idMatcher.group(4); - String teamClassName = idMatcher.group(5) + " " + idMatcher.group(6); - studentIds.add(studentId); - studentNamesLong.add(studentFirstName + " " + studentLastName); - studentNamesShort.add(studentFirstName + " " + studentLastName.charAt(0) + "."); - studentTeams.add(teamClassName); - } - Collections.reverse(studentIds); - Collections.reverse(registerIds); - Collections.reverse(studentNamesLong); - Collections.reverse(studentNamesShort); - Collections.reverse(studentTeams); - - List profileList = new ArrayList<>(); - for (int index = 0; index < registerIds.size(); index++) { - Profile newProfile = new Profile(); - newProfile.setStudentNameLong(studentNamesLong.get(index)); - newProfile.setStudentNameShort(studentNamesShort.get(index)); - newProfile.setName(newProfile.getStudentNameLong()); - newProfile.setSubname(loginUsername); - newProfile.setEmpty(true); - newProfile.setLoggedIn(true); - newProfile.putStudentData("studentId", studentIds.get(index)); - newProfile.putStudentData("registerId", registerIds.get(index)); - newProfile.putStudentData("schoolYearId", loginSchoolYearId); - profileList.add(newProfile); - } - - callback.onLoginFirst(profileList, loginStore); - } catch (Exception ex) { - finishWithError(new AppError(TAG, 557, CODE_OTHER, response2, ex, data2)); - } - } - - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 563, CODE_OTHER, response, throwable, data1)); - } - }).build().enqueue(); - } - }).build().enqueue(); - } - - /* _ _ _ _ _ _ _ - | | | | | | ___ | | | | | | - | |__| | ___| |_ __ ___ _ __ ___ ( _ ) ___ __ _| | | |__ __ _ ___| | _____ - | __ |/ _ \ | '_ \ / _ \ '__/ __| / _ \/\ / __/ _` | | | '_ \ / _` |/ __| |/ / __| - | | | | __/ | |_) | __/ | \__ \ | (_> < | (_| (_| | | | |_) | (_| | (__| <\__ \ - |_| |_|\___|_| .__/ \___|_| |___/ \___/\/ \___\__,_|_|_|_.__/ \__,_|\___|_|\_\___/ - | | - |*/ - private interface ApiRequestCallback { - void onSuccess(JsonObject result, Response response); - } - private void apiRequest(Request.Builder requestBuilder, ApiRequestCallback apiRequestCallback) { - requestBuilder.callback(new JsonCallbackHandler() { - @Override - public void onSuccess(JsonObject data, Response response) { - if (data == null) { - finishWithError(new AppError(TAG, 578, CODE_MAINTENANCE, response)); - return; - } - try { - apiRequestCallback.onSuccess(data, response); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 583, CODE_OTHER, response, e, data)); - } - } - - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 592, CODE_OTHER, response, throwable)); - } - }) - .build() - .enqueue(); - } - private interface ApiRequestArrayCallback { - void onSuccess(JsonArray result, Response response); - } - private void apiRequestArray(Request.Builder requestBuilder, ApiRequestArrayCallback apiRequestArrayCallback) { - requestBuilder.callback(new JsonArrayCallbackHandler() { - @Override - public void onSuccess(JsonArray data, Response response) { - if (data == null) { - finishWithError(new AppError(TAG, 603, CODE_MAINTENANCE, response)); - return; - } - try { - apiRequestArrayCallback.onSuccess(data, response); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 610, CODE_OTHER, response, e, data.toString())); - } - } - - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 616, CODE_OTHER, response, throwable)); - } - }) - .build() - .enqueue(); - } - - private Subject searchSubject(String name, long id, String shortName) { - Subject subject; - if (id == -1) - subject = Subject.getByName(subjectList, name); - else - subject = Subject.getById(subjectList, id); - - if (subject == null) { - subject = new Subject(profileId, (id == -1 ? crc16(name.getBytes()) : id), name, shortName); - subjectList.add(subject); - } - return subject; - } - - private Teacher searchTeacher(String firstName, String lastName) { - Teacher teacher = Teacher.getByFullName(teacherList, firstName+" "+lastName); - return validateTeacher(teacher, firstName, lastName); - } - private Teacher searchTeacher(char firstNameChar, String lastName) { - Teacher teacher = Teacher.getByShortName(teacherList, firstNameChar+"."+lastName); - return validateTeacher(teacher, String.valueOf(firstNameChar), lastName); - } - @NonNull - private Teacher validateTeacher(Teacher teacher, String firstName, String lastName) { - if (teacher == null) { - teacher = new Teacher(profileId, -1, firstName, lastName); - teacher.id = crc16(teacher.getShortName().getBytes()); - teacherList.add(teacher); - } - if (firstName.length() > 1) - teacher.name = firstName; - teacher.surname = lastName; - return teacher; - } - - private Teacher searchTeacherByLastFirst(String nameLastFirst) { - String[] nameParts = nameLastFirst.split(" ", Integer.MAX_VALUE); - if (nameParts.length == 1) - return searchTeacher(nameParts[0], ""); - return searchTeacher(nameParts[1], nameParts[0]); - } - private Teacher searchTeacherByFirstLast(String nameFirstLast) { - String[] nameParts = nameFirstLast.split(" ", Integer.MAX_VALUE); - if (nameParts.length == 1) - return searchTeacher(nameParts[0], ""); - return searchTeacher(nameParts[0], nameParts[1]); - } - private Teacher searchTeacherByFDotLast(String nameFDotLast) { - String[] nameParts = nameFDotLast.split("\\.", Integer.MAX_VALUE); - if (nameParts.length == 1) - return searchTeacher(nameParts[0], ""); - return searchTeacher(nameParts[0].charAt(0), nameParts[1]); - } - private Teacher searchTeacherByFDotSpaceLast(String nameFDotSpaceLast) { - String[] nameParts = nameFDotSpaceLast.split("\\. ", Integer.MAX_VALUE); - if (nameParts.length == 1) - return searchTeacher(nameParts[0], ""); - return searchTeacher(nameParts[0].charAt(0), nameParts[1]); - } - - /* _____ _ _____ _ - | __ \ | | | __ \ | | - | | | | __ _| |_ __ _ | |__) |___ __ _ _ _ ___ ___| |_ ___ - | | | |/ _` | __/ _` | | _ // _ \/ _` | | | |/ _ \/ __| __/ __| - | |__| | (_| | || (_| | | | \ \ __/ (_| | |_| | __/\__ \ |_\__ \ - |_____/ \__,_|\__\__,_| |_| \_\___|\__, |\__,_|\___||___/\__|___/ - | | - |*/ - private void getTimetable() { - callback.onActionStarted(R.string.sync_action_syncing_timetable); - Date weekStart = Week.getWeekStart(); - if (Date.getToday().getWeekDay() > 4) { - weekStart.stepForward(0, 0, 7); - } - apiRequest(Request.builder() - .url(IDZIENNIK_URL +"/mod_panelRodzica/plan/WS_Plan.asmx/pobierzPlanZajec") - .userAgent(userAgent) - .addParameter("idPozDziennika", loginRegisterId) - .addParameter("pidRokSzkolny", loginSchoolYearId) - .addParameter("data", weekStart.getStringY_m_d()+"T10:00:00.000Z") - .postJson(), (result, response) -> { - JsonObject data = result.getAsJsonObject("d"); - if (data == null) { - finishWithError(new AppError(TAG, 697, CODE_MAINTENANCE, response, result)); - return; - } - List> lessonHours = new ArrayList<>(); - for (JsonElement jLessonHourEl : data.getAsJsonArray("GodzinyLekcyjne")) { - JsonObject jLessonHour = jLessonHourEl.getAsJsonObject(); - // jLessonHour - lessonHours.add(new Pair<>(Time.fromH_m(jLessonHour.get("Poczatek").getAsString()), Time.fromH_m(jLessonHour.get("Koniec").getAsString()))); - } - - for (JsonElement jLessonEl : data.getAsJsonArray("Przedmioty")) { - JsonObject jLesson = jLessonEl.getAsJsonObject(); - // jLesson - Subject rSubject = searchSubject(jLesson.get("Nazwa").getAsString(), jLesson.get("Id").getAsInt(), jLesson.get("Skrot").getAsString()); - Teacher rTeacher = searchTeacherByFDotLast(jLesson.get("Nauczyciel").getAsString()); - - int weekDay = jLesson.get("DzienTygodnia").getAsInt() - 1; - Pair lessonHour = lessonHours.get(jLesson.get("Godzina").getAsInt()); - if (lessonHour == null || lessonHour.first == null || lessonHour.second == null) - continue; - Lesson lessonObject = new Lesson( - profileId, - weekDay, - lessonHour.first, - lessonHour.second - ); - lessonObject.subjectId = rSubject.id; - lessonObject.teacherId = rTeacher.id; - lessonObject.teamId = teamClassId; - lessonObject.classroomName = jLesson.get("NazwaSali").getAsString(); - - lessonList.add(lessonObject); - - int type = jLesson.get("TypZastepstwa").getAsInt(); - if (type != -1) { - // we have a lesson change to process - LessonChange lessonChangeObject = new LessonChange( - profileId, - weekStart.clone().stepForward(0, 0, weekDay), - lessonObject.startTime, - lessonObject.endTime - ); - - lessonChangeObject.teamId = lessonObject.teamId; - lessonChangeObject.teacherId = lessonObject.teacherId; - lessonChangeObject.subjectId = lessonObject.subjectId; - lessonChangeObject.classroomName = lessonObject.classroomName; - switch (type) { - case 0: - lessonChangeObject.type = TYPE_CANCELLED; - break; - case 1: - case 2: - case 3: - case 4: - case 5: - lessonChangeObject.type = TYPE_CHANGE; - String newTeacher = jLesson.get("NauZastepujacy").getAsString(); - String newSubject = jLesson.get("PrzedmiotZastepujacy").getAsString(); - if (!newTeacher.equals("")) { - lessonChangeObject.teacherId = searchTeacherByFDotLast(newTeacher).id; - } - if (!newSubject.equals("")) { - lessonChangeObject.subjectId = searchSubject(newSubject, -1, "").id; - } - break; - } - - lessonChangeList.add(lessonChangeObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_LESSON_CHANGE, lessonChangeObject.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - } - } - r("finish", "Timetable"); - }); - } - - private void getGrades() { - callback.onActionStarted(R.string.sync_action_syncing_grades); - apiRequest(Request.builder() - .url(IDZIENNIK_URL +"/mod_panelRodzica/oceny/WS_ocenyUcznia.asmx/pobierzOcenyUcznia") - .userAgent(userAgent) - .addParameter("idPozDziennika", loginRegisterId) - .postJson(), (result, response) -> { - JsonObject data = result.getAsJsonObject("d"); - if (data == null) { - finishWithError(new AppError(TAG, 782, CODE_MAINTENANCE, response, result)); - return; - } - JsonArray jSubjects = data.getAsJsonArray("Przedmioty"); - for (JsonElement jSubjectEl : jSubjects) { - JsonObject jSubject = jSubjectEl.getAsJsonObject(); - // jSubject - Subject rSubject = searchSubject(jSubject.get("Przedmiot").getAsString(), jSubject.get("IdPrzedmiotu").getAsInt(), jSubject.get("Przedmiot").getAsString()); - for (JsonElement jGradeEl : jSubject.getAsJsonArray("Oceny")) { - JsonObject jGrade = jGradeEl.getAsJsonObject(); - // jGrade - Teacher rTeacher = searchTeacherByLastFirst(jGrade.get("Wystawil").getAsString()); - - boolean countToTheAverage = jGrade.get("DoSredniej").getAsBoolean(); - float value = jGrade.get("WartoscDoSred").getAsFloat(); - - String gradeColor = jGrade.get("Kolor").getAsString(); - int colorInt = 0xff2196f3; - if (!gradeColor.isEmpty()) { - colorInt = Color.parseColor("#"+gradeColor); - } - - Grade gradeObject = new Grade( - profileId, - jGrade.get("idK").getAsLong(), - jGrade.get("Kategoria").getAsString(), - colorInt, - "", - jGrade.get("Ocena").getAsString(), - value, - value > 0 && countToTheAverage ? jGrade.get("Waga").getAsFloat() : 0, - jGrade.get("Semestr").getAsInt(), - rTeacher.id, - rSubject.id); - - switch (jGrade.get("Typ").getAsInt()) { - case 0: - JsonElement historyEl = jGrade.get("Historia"); - JsonArray history; - if (historyEl instanceof JsonArray && (history = historyEl.getAsJsonArray()).size() > 0) { - float sum = gradeObject.value * gradeObject.weight; - float count = gradeObject.weight; - for (JsonElement historyItemEl: history) { - JsonObject historyItem = historyItemEl.getAsJsonObject(); - - countToTheAverage = historyItem.get("DoSredniej").getAsBoolean(); - value = historyItem.get("WartoscDoSred").getAsFloat(); - float weight = historyItem.get("Waga").getAsFloat(); - - if (value > 0 && countToTheAverage) { - sum += value * weight; - count += weight; - } - - Grade historyObject = new Grade( - profileId, - gradeObject.id * -1, - historyItem.get("Kategoria").getAsString(), - Color.parseColor("#"+historyItem.get("Kolor").getAsString()), - historyItem.get("Uzasadnienie").getAsString(), - historyItem.get("Ocena").getAsString(), - value, - value > 0 && countToTheAverage ? weight * -1 : 0, - historyItem.get("Semestr").getAsInt(), - rTeacher.id, - rSubject.id); - historyObject.parentId = gradeObject.id; - - gradeList.add(historyObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_GRADE, historyObject.id, true, true, Date.fromY_m_d(historyItem.get("Data_wystaw").getAsString()).getInMillis())); - } - // update the current grade's value with an average of all historical grades and itself - if (sum > 0 && count > 0) { - gradeObject.value = sum / count; - } - gradeObject.isImprovement = true; // gradeObject is the improved grade. Originals are historyObjects - } - break; - case 1: - gradeObject.type = TYPE_SEMESTER1_FINAL; - gradeObject.name = Integer.toString((int) gradeObject.value); - gradeObject.weight = 0; - break; - case 2: - gradeObject.type = TYPE_YEAR_FINAL; - gradeObject.name = Integer.toString((int) gradeObject.value); - gradeObject.weight = 0; - break; - } - - gradeList.add(gradeObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_GRADE, gradeObject.id, profile.getEmpty(), profile.getEmpty(), Date.fromY_m_d(jGrade.get("Data_wystaw").getAsString()).getInMillis())); - } - } - r("finish", "Grades"); - }); - } - - private void getPropositionGrades() { - callback.onActionStarted(R.string.sync_action_syncing_proposition_grades); - apiRequest(Request.builder() - .url(IDZIENNIK_URL +"/mod_panelRodzica/brak_ocen/WS_BrakOcenUcznia.asmx/pobierzBrakujaceOcenyUcznia") - .userAgent(userAgent) - .addParameter("idPozDziennika", loginRegisterId) - .postJson(), (result, response) -> { - JsonObject data = result.getAsJsonObject("d"); - if (data == null) { - finishWithError(new AppError(TAG, 836, CODE_MAINTENANCE, response, result)); - return; - } - JsonArray jSubjects = data.getAsJsonArray("Przedmioty"); - for (JsonElement jSubjectEl : jSubjects) { - JsonObject jSubject = jSubjectEl.getAsJsonObject(); - // jSubject - Subject rSubject = searchSubject(jSubject.get("Przedmiot").getAsString(), -1, jSubject.get("Przedmiot").getAsString()); - String semester1Proposed = jSubject.get("OcenaSem1").getAsString(); - String semester2Proposed = jSubject.get("OcenaSem2").getAsString(); - int semester1Value = getWordGradeValue(semester1Proposed); - int semester2Value = getWordGradeValue(semester2Proposed); - long semester1Id = rSubject.id * -100 - 1; - long semester2Id = rSubject.id * -100 - 2; - - if (!semester1Proposed.equals("")) { - Grade gradeObject = new Grade( - profileId, - semester1Id, - "", - -1, - "", - Integer.toString(semester1Value), - semester1Value, - 0, - 1, - -1, - rSubject.id); - - gradeObject.type = TYPE_SEMESTER1_PROPOSED; - - gradeList.add(gradeObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_GRADE, gradeObject.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - } - - if (!semester2Proposed.equals("")) { - Grade gradeObject = new Grade( - profileId, - semester2Id, - "", - -1, - "", - Integer.toString(semester2Value), - semester2Value, - 0, - 2, - -1, - rSubject.id); - - gradeObject.type = TYPE_YEAR_PROPOSED; - - gradeList.add(gradeObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_GRADE, gradeObject.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - } - } - r("finish", "PropositionGrades"); - }); - } - - private int examsYear = Date.getToday().year; - private int examsMonth = Date.getToday().month; - private int examsMonthsChecked = 0; - private boolean examsNextMonthChecked = false; // TO DO temporary // no more // idk - private void getExams() { - callback.onActionStarted(R.string.sync_action_syncing_exams); - JsonObject postData = new JsonObject(); - postData.addProperty("idP", loginRegisterId); - postData.addProperty("rok", examsYear); - postData.addProperty("miesiac", examsMonth); - JsonObject param = new JsonObject(); - param.addProperty("strona", 1); - param.addProperty("iloscNaStrone", "99"); - param.addProperty("iloscRekordow", -1); - param.addProperty("kolumnaSort", "ss.Nazwa,sp.Data_sprawdzianu"); - param.addProperty("kierunekSort", 0); - param.addProperty("maxIloscZaznaczonych", 0); - param.addProperty("panelFiltrow", 0); - postData.add("param", param); - - apiRequest(Request.builder() - .url(IDZIENNIK_URL +"/mod_panelRodzica/sprawdziany/mod_sprawdzianyPanel.asmx/pobierzListe") - .userAgent(userAgent) - .setJsonBody(postData), (result, response) -> { - JsonObject data = result.getAsJsonObject("d"); - if (data == null) { - finishWithError(new AppError(TAG, 921, CODE_MAINTENANCE, response, result)); - return; - } - for (JsonElement jExamEl : data.getAsJsonArray("ListK")) { - JsonObject jExam = jExamEl.getAsJsonObject(); - // jExam - long eventId = jExam.get("_recordId").getAsLong(); - Subject rSubject = searchSubject(jExam.get("przedmiot").getAsString(), -1, ""); - Teacher rTeacher = searchTeacherByLastFirst(jExam.get("wpisal").getAsString()); - Date examDate = Date.fromY_m_d(jExam.get("data").getAsString()); - Lesson lessonObject = Lesson.getByWeekDayAndSubject(lessonList, examDate.getWeekDay(), rSubject.id); - Time examTime = lessonObject == null ? null : lessonObject.startTime; - - int eventType = (jExam.get("rodzaj").getAsString().equals("sprawdzian/praca klasowa") ? Event.TYPE_EXAM : Event.TYPE_SHORT_QUIZ); - Event eventObject = new Event( - profileId, - eventId, - examDate, - examTime, - jExam.get("zakres").getAsString(), - -1, - eventType, - false, - rTeacher.id, - rSubject.id, - teamClassId - ); - - eventList.add(eventObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_EVENT, eventObject.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - } - - if (profile.getEmpty() && examsMonthsChecked < 3 /* how many months backwards to check? */) { - examsMonthsChecked++; - examsMonth--; - if (examsMonth < 1) { - examsMonth = 12; - examsYear--; - } - r("get", "Exams"); - } else if (!examsNextMonthChecked /* get also one month forward */) { - Date showDate = Date.getToday().stepForward(0, 1, 0); - examsYear = showDate.year; - examsMonth = showDate.month; - examsNextMonthChecked = true; - r("get", "Exams"); - } else { - r("finish", "Exams"); - } - }); - } - - private void getNotices() { - callback.onActionStarted(R.string.sync_action_syncing_notices); - apiRequest(Request.builder() - .url(IDZIENNIK_URL +"/mod_panelRodzica/uwagi/WS_uwagiUcznia.asmx/pobierzUwagiUcznia") - .userAgent(userAgent) - .addParameter("idPozDziennika", loginRegisterId) - .postJson(), (result, response) -> { - JsonObject data = result.getAsJsonObject("d"); - if (data == null) { - finishWithError(new AppError(TAG, 982, CODE_MAINTENANCE, response, result)); - return; - } - for (JsonElement jNoticeEl : data.getAsJsonArray("SUwaga")) { - JsonObject jNotice = jNoticeEl.getAsJsonObject(); - // jExam - long noticeId = crc16(jNotice.get("id").getAsString().getBytes()); - - Teacher rTeacher = searchTeacherByLastFirst(jNotice.get("Nauczyciel").getAsString()); - Date addedDate = Date.fromY_m_d(jNotice.get("Data").getAsString()); - - int nType = TYPE_NEUTRAL; - String jType = jNotice.get("Typ").getAsString(); - if (jType.equals("n")) { - nType = TYPE_NEGATIVE; - } else if (jType.equals("p")) { - nType = TYPE_POSITIVE; - } - - Notice noticeObject = new Notice( - profileId, - noticeId, - jNotice.get("Tresc").getAsString(), - jNotice.get("Semestr").getAsInt(), - nType, - rTeacher.id); - noticeList.add(noticeObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_NOTICE, noticeObject.id, profile.getEmpty(), profile.getEmpty(), addedDate.getInMillis())); - } - r("finish", "Notices"); - }); - } - - private void getAnnouncements() { - callback.onActionStarted(R.string.sync_action_syncing_announcements); - if (loginStudentId == null) { - r("finish", "Announcements"); - return; - } - JsonObject postData = new JsonObject(); - postData.addProperty("uczenId", loginStudentId); - JsonObject param = new JsonObject(); - param.add("parametryFiltrow", new JsonArray()); - postData.add("param", param); - - apiRequest(Request.builder() - .url(IDZIENNIK_URL +"/mod_panelRodzica/tabOgl/WS_tablicaOgloszen.asmx/GetOgloszenia") - .userAgent(userAgent) - .setJsonBody(postData), (result, response) -> { - JsonObject data = result.getAsJsonObject("d"); - if (data == null) { - finishWithError(new AppError(TAG, 1033, CODE_MAINTENANCE, response, result)); - return; - } - for (JsonElement jAnnouncementEl : data.getAsJsonArray("ListK")) { - JsonObject jAnnouncement = jAnnouncementEl.getAsJsonObject(); - // jAnnouncement - long announcementId = jAnnouncement.get("Id").getAsLong(); - - Teacher rTeacher = searchTeacherByFirstLast(jAnnouncement.get("Autor").getAsString()); - long addedDate = Long.parseLong(jAnnouncement.get("DataDodania").getAsString().replaceAll("[^\\d]", "")); - Date startDate = Date.fromMillis(Long.parseLong(jAnnouncement.get("DataWydarzenia").getAsString().replaceAll("[^\\d]", ""))); - - Announcement announcementObject = new Announcement( - profileId, - announcementId, - jAnnouncement.get("Temat").getAsString(), - jAnnouncement.get("Tresc").getAsString(), - startDate, - null, - rTeacher.id - ); - announcementList.add(announcementObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_ANNOUNCEMENT, announcementObject.id, profile.getEmpty(), profile.getEmpty(), addedDate)); - } - r("finish", "Announcements"); - }); - } - - private int attendanceYear; - private int attendanceMonth; - private boolean attendancePrevMonthChecked = false; - private void getAttendance() { - callback.onActionStarted(R.string.sync_action_syncing_attendance); - apiRequest(Request.builder() - .url(IDZIENNIK_URL +"/mod_panelRodzica/obecnosci/WS_obecnosciUcznia.asmx/pobierzObecnosciUcznia") - .userAgent(userAgent) - .addParameter("idPozDziennika", loginRegisterId) - .addParameter("mc", attendanceMonth) - .addParameter("rok", attendanceYear) - .addParameter("dataTygodnia", "") - .postJson(), (result, response) -> { - JsonObject data = result.getAsJsonObject("d"); - if (data == null) { - finishWithError(new AppError(TAG, 1076, CODE_MAINTENANCE, response, result)); - return; - } - for (JsonElement jAttendanceEl : data.getAsJsonArray("Obecnosci")) { - JsonObject jAttendance = jAttendanceEl.getAsJsonObject(); - // jAttendance - int attendanceTypeIdziennik = jAttendance.get("TypObecnosci").getAsInt(); - if (attendanceTypeIdziennik == 5 || attendanceTypeIdziennik == 7) - continue; - Date attendanceDate = Date.fromY_m_d(jAttendance.get("Data").getAsString()); - Time attendanceTime = Time.fromH_m(jAttendance.get("OdDoGodziny").getAsString()); - if (attendanceDate.combineWith(attendanceTime) > System.currentTimeMillis()) - continue; - - long attendanceId = crc16(jAttendance.get("IdLesson").getAsString().getBytes()); - Subject rSubject = searchSubject(jAttendance.get("Przedmiot").getAsString(), jAttendance.get("IdPrzedmiot").getAsLong(), ""); - Teacher rTeacher = searchTeacherByFDotSpaceLast(jAttendance.get("PrzedmiotNauczyciel").getAsString()); - - String attendanceName = "obecność"; - int attendanceType = Attendance.TYPE_CUSTOM; - - switch (attendanceTypeIdziennik) { - case 1: /* nieobecność usprawiedliwiona */ - attendanceName = "nieobecność usprawiedliwiona"; - attendanceType = TYPE_ABSENT_EXCUSED; - break; - case 2: /* spóźnienie */ - attendanceName = "spóźnienie"; - attendanceType = TYPE_BELATED; - break; - case 3: /* nieobecność nieusprawiedliwiona */ - attendanceName = "nieobecność nieusprawiedliwiona"; - attendanceType = TYPE_ABSENT; - break; - case 4: /* zwolnienie */ - case 9: /* zwolniony / obecny */ - attendanceType = TYPE_RELEASED; - if (attendanceTypeIdziennik == 4) - attendanceName = "zwolnienie"; - if (attendanceTypeIdziennik == 9) - attendanceName = "zwolnienie / obecność"; - break; - case 0: /* obecny */ - case 8: /* Wycieczka */ - attendanceType = TYPE_PRESENT; - if (attendanceTypeIdziennik == 8) - attendanceName = "wycieczka"; - break; - } - - int semester = profile.dateToSemester(attendanceDate); - - Attendance attendanceObject = new Attendance( - profileId, - attendanceId, - rTeacher.id, - rSubject.id, - semester, - attendanceName, - attendanceDate, - attendanceTime, - attendanceType - ); - - attendanceList.add(attendanceObject); - if (attendanceObject.type != TYPE_PRESENT) { - metadataList.add(new Metadata(profileId, Metadata.TYPE_ATTENDANCE, attendanceObject.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - } - } - - int attendanceDateValue = attendanceYear *10000 + attendanceMonth *100; - if (profile.getEmpty() && attendanceDateValue > profile.getSemesterStart(1).getValue()) { - attendancePrevMonthChecked = true; // do not need to check prev month later - attendanceMonth--; - if (attendanceMonth < 1) { - attendanceMonth = 12; - attendanceYear--; - } - r("get", "Attendance"); - } else if (!attendancePrevMonthChecked /* get also the previous month */) { - attendanceMonth--; - if (attendanceMonth < 1) { - attendanceMonth = 12; - attendanceYear--; - } - attendancePrevMonthChecked = true; - r("get", "Attendance"); - } else { - r("finish", "Attendance"); - } - }); - } - - private void getLuckyNumberAndSemesterDates() { - if (profile.getLuckyNumberDate() != null && profile.getLuckyNumber() != -1 && profile.getLuckyNumberDate().getValue() == Date.getToday().getValue()) { - r("finish", "LuckyNumberAndSemesterDates"); - return; - } - if (loginBearerToken == null || loginStudentId == null) { - r("finish", "LuckyNumberAndSemesterDates"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_lucky_number); - apiRequest(Request.builder() - .url(IDZIENNIK_URL +"/api/Uczniowie/"+loginStudentId+"/AktualnyDziennik") - .header("Authorization", "Bearer "+loginBearerToken) - .userAgent(userAgent), (data, response) -> { - JsonObject settings = data.getAsJsonObject("ustawienia"); - if (settings == null) { - finishWithError(new AppError(TAG, 1188, CODE_MAINTENANCE, response, data)); - return; - } - // data, settings - profile.setLuckyNumber(-1); - profile.setLuckyNumberDate(today); - JsonElement luckyNumberEl = data.get("szczesliwyNumerek"); - if (luckyNumberEl != null && !(luckyNumberEl instanceof JsonNull)) { - profile.setLuckyNumber(luckyNumberEl.getAsInt()); - Time publishTime = Time.fromH_m(settings.get("godzinaPublikacjiSzczesliwegoLosu").getAsString()); - if (Time.getNow().getValue() > publishTime.getValue()) { - profile.getLuckyNumberDate().stepForward(0, 0, 1); // the lucky number is already for tomorrow - } - app.db.luckyNumberDao().add(new LuckyNumber(profileId, profile.getLuckyNumberDate(), profile.getLuckyNumber())); - } - - profile.setDateSemester1Start(Date.fromY_m_d(settings.get("poczatekSemestru1").getAsString())); - profile.setDateSemester2Start(Date.fromY_m_d(settings.get("koniecSemestru1").getAsString()).stepForward(0, 0, 1)); - profile.setDateYearEnd(Date.fromY_m_d(settings.get("koniecSemestru2").getAsString())); - - r("finish", "LuckyNumberAndSemesterDates"); - }); - } - - private void getMessagesInbox() { - if (loginBearerToken == null) { - r("finish", "MessagesInbox"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_messages); - apiRequestArray(Request.builder() - .url(IDZIENNIK_URL +"/api/Wiadomosci/Odebrane") - .header("Authorization", "Bearer "+loginBearerToken) - .userAgent(userAgent), (data, response) -> { - for (JsonElement jMessageEl: data) { - JsonObject jMessage = jMessageEl.getAsJsonObject(); - - String subject = jMessage.get("tytul").getAsString(); - if (subject.contains("(") && subject.startsWith("iDziennik - ")) - continue; - if (subject.startsWith("Uwaga dla ucznia (klasa:")) - continue; - - String messageIdStr = jMessage.get("id").getAsString(); - long messageId = crc32((messageIdStr+"0").getBytes()); - - String body = "[META:"+messageIdStr+";-1]"; - body += jMessage.get("tresc").getAsString().replaceAll("\n", "
    "); - - long readDate = jMessage.get("odczytana").getAsBoolean() ? Date.fromIso(jMessage.get("wersjaRekordu").getAsString()) : 0; - long sentDate = Date.fromIso(jMessage.get("dataWyslania").getAsString()); - - JsonObject sender = jMessage.getAsJsonObject("nadawca"); - Teacher rTeacher = searchTeacher(sender.get("imie").getAsString(), sender.get("nazwisko").getAsString()); - rTeacher.loginId = sender.get("id").getAsString()+":"+sender.get("usr").getAsString(); - - Message message = new Message( - profileId, - messageId, - subject, - body, - jMessage.get("rekordUsuniety").getAsBoolean() ? TYPE_DELETED : TYPE_RECEIVED, - rTeacher.id, - -1 - ); - - MessageRecipient messageRecipient = new MessageRecipient( - profileId, - -1 /* me */, - -1, - readDate, - /*messageId*/ messageId - ); - - messageList.add(message); - messageRecipientList.add(messageRecipient); - messageMetadataList.add(new Metadata(profileId, Metadata.TYPE_MESSAGE, message.id, readDate > 0, readDate > 0 || profile.getEmpty(), sentDate)); - } - - r("finish", "MessagesInbox"); - }); - } - - private void getMessagesOutbox() { - if (loginBearerToken == null) { - r("finish", "MessagesOutbox"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_messages); - apiRequestArray(Request.builder() - .url(IDZIENNIK_URL +"/api/Wiadomosci/Wyslane") - .header("Authorization", "Bearer "+loginBearerToken) - .userAgent(userAgent), (data, response) -> { - for (JsonElement jMessageEl: data) { - JsonObject jMessage = jMessageEl.getAsJsonObject(); - - String messageIdStr = jMessage.get("id").getAsString(); - long messageId = crc32((messageIdStr+"1").getBytes()); - - String subject = jMessage.get("tytul").getAsString(); - - String body = "[META:"+messageIdStr+";-1]"; - body += jMessage.get("tresc").getAsString().replaceAll("\n", "
    "); - - long sentDate = Date.fromIso(jMessage.get("dataWyslania").getAsString()); - - Message message = new Message( - profileId, - messageId, - subject, - body, - TYPE_SENT, - -1, - -1 - ); - - for (JsonElement recipientEl: jMessage.getAsJsonArray("odbiorcy")) { - JsonObject recipient = recipientEl.getAsJsonObject(); - String firstName = recipient.get("imie").getAsString(); - String lastName = recipient.get("nazwisko").getAsString(); - if (firstName.isEmpty() || lastName.isEmpty()) { - firstName = "usunięty"; - lastName = "użytkownik"; - } - Teacher rTeacher = searchTeacher(firstName, lastName); - rTeacher.loginId = recipient.get("id").getAsString()+":"+recipient.get("usr").getAsString(); - - MessageRecipient messageRecipient = new MessageRecipient( - profileId, - rTeacher.id, - -1, - -1, - /*messageId*/ messageId - ); - messageRecipientIgnoreList.add(messageRecipient); - } - - messageList.add(message); - metadataList.add(new Metadata(profileId, Metadata.TYPE_MESSAGE, message.id, true, true, sentDate)); - } - - r("finish", "MessagesOutbox"); - }); - } - - @Override - public Map getConfigurableEndpoints(Profile profile) { - return null; - } - - @Override - public boolean isEndpointEnabled(Profile profile, boolean defaultActive, String name) { - return defaultActive; - } - - @Override - public void syncMessages(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile) - { - } - - /* __ __ - | \/ | - | \ / | ___ ___ ___ __ _ __ _ ___ ___ - | |\/| |/ _ \/ __/ __|/ _` |/ _` |/ _ \/ __| - | | | | __/\__ \__ \ (_| | (_| | __/\__ \ - |_| |_|\___||___/___/\__,_|\__, |\___||___/ - __/ | - |__*/ - @Override - public void getMessage(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile, @NonNull MessageFull message, @NonNull MessageGetCallback messageCallback) { - if (message.body == null) - return; - String messageIdStr = null; - long messageIdBefore = -1; - Matcher matcher = Pattern.compile("\\[META:([A-z0-9]+);([0-9-]+)]").matcher(message.body); - if (matcher.find()) { - messageIdStr = matcher.group(1); - messageIdBefore = Long.parseLong(matcher.group(2)); - } - if (messageIdBefore != -1) { - boolean readByAll = true; - // load this message's recipient(s) data - message.recipients = app.db.messageRecipientDao().getAllByMessageId(profile.getId(), message.id); - for (MessageRecipientFull recipient: message.recipients) { - if (recipient.id == -1) - recipient.fullName = profile.getStudentNameLong(); - if (message.type == TYPE_SENT && recipient.readDate < 1) - readByAll = false; - } - if (!message.seen) { - app.db.metadataDao().setSeen(profile.getId(), message, true); - } - if (readByAll) { - // if a sent msg is not read by everyone, download it again to check the read status - new Handler(activityContext.getMainLooper()).post(() -> messageCallback.onSuccess(message)); - return; - } - } - - if (!prepare(activityContext, errorCallback, profile.getId(), profile, LoginStore.fromProfileFull(profile))) - return; - - String finalMessageIdStr = messageIdStr; - login(() -> apiRequest(Request.builder() - .url(IDZIENNIK_URL +"/mod_komunikator/WS_wiadomosci.asmx/PobierzWiadomosc") - .userAgent(userAgent) - .addParameter("idWiadomosci", finalMessageIdStr) - .addParameter("typWiadomosci", message.type == TYPE_SENT ? 1 : 0) - .postJson(), (result, response) -> { - JsonObject data = result.getAsJsonObject("d"); - if (data == null) { - finishWithError(new AppError(TAG, 1418, CODE_MAINTENANCE, response, result)); - return; - } - JsonObject jMessage = data.getAsJsonObject("Wiadomosc"); - if (jMessage == null) { - finishWithError(new AppError(TAG, 1423, CODE_MAINTENANCE, response, result)); - return; - } - - List messageRecipientList = new ArrayList<>(); - - long messageId = jMessage.get("_recordId").getAsLong(); - - message.body = message.body.replaceAll("\\[META:[A-z0-9]+;[0-9-]+]", "[META:"+ finalMessageIdStr +";"+ messageId +"]"); - - message.clearAttachments(); - for (JsonElement jAttachmentEl: jMessage.getAsJsonArray("ListaZal")) { - JsonObject jAttachment = jAttachmentEl.getAsJsonObject(); - message.addAttachment(jAttachment.get("Id").getAsLong(), jAttachment.get("Nazwa").getAsString(), -1); - } - - if (message.type == TYPE_RECEIVED) { - MessageRecipientFull recipient = new MessageRecipientFull(profileId, -1, message.id); - - String readDateStr = jMessage.get("DataOdczytania").getAsString(); - recipient.readDate = readDateStr.isEmpty() ? System.currentTimeMillis() : Date.fromIso(readDateStr); - - recipient.fullName = profile.getStudentNameLong(); - messageRecipientList.add(recipient); - } - else if (message.type == TYPE_SENT) { - teacherList = app.db.teacherDao().getAllNow(profileId); - for (JsonElement jReceiverEl: jMessage.getAsJsonArray("ListaOdbiorcow")) { - JsonObject jReceiver = jReceiverEl.getAsJsonObject(); - String receiverLastFirstName = jReceiver.get("NazwaOdbiorcy").getAsString(); - - Teacher teacher = searchTeacherByLastFirst(receiverLastFirstName); - - MessageRecipientFull recipient = new MessageRecipientFull(profileId, teacher.id, message.id); - - recipient.readDate = jReceiver.get("Status").getAsInt(); - - recipient.fullName = teacher.getFullName(); - messageRecipientList.add(recipient); - } - } - - if (!message.seen) { - app.db.metadataDao().setSeen(profileId, message, true); - } - app.db.messageDao().add(message); - app.db.messageRecipientDao().addAll((List)(List) messageRecipientList); // not addAllIgnore - - message.recipients = messageRecipientList; - - new Handler(activityContext.getMainLooper()).post(() -> messageCallback.onSuccess(message)); - })); - } - - @Override - public void getAttachment(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile, @NonNull MessageFull message, long attachmentId, @NonNull AttachmentGetCallback attachmentCallback) { - if (message.body == null) - return; - if (!prepare(activityContext, errorCallback, profile.getId(), profile, LoginStore.fromProfileFull(profile))) - return; - - login(() -> { - String fileName = message.attachmentNames.get(message.attachmentIds.indexOf(attachmentId)); - - long messageId = -1; - Matcher matcher = Pattern.compile("\\[META:([A-z0-9]+);([0-9-]+)]").matcher(message.body); - if (matcher.find()) { - messageId = Long.parseLong(matcher.group(2)); - } - - Request.Builder builder = Request.builder() - .url("https://iuczniowie.progman.pl/idziennik/mod_komunikator/Download.ashx") - .post() - .contentType(MediaTypeUtils.APPLICATION_FORM) - .addParameter("id", messageId) - .addParameter("fileName", fileName); - - new Handler(activityContext.getMainLooper()).post(() -> attachmentCallback.onSuccess(builder)); - }); - } - - @Override - public void getRecipientList(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile, @NonNull RecipientListGetCallback recipientListGetCallback) { - if (!prepare(activityContext, errorCallback, profile.getId(), profile, LoginStore.fromProfileFull(profile))) - return; - - if (System.currentTimeMillis() - profile.getLastReceiversSync() < 24 * 60 * 60 * 1000) { - AsyncTask.execute(() -> { - List teacherList = app.db.teacherDao().getAllNow(profileId); - new Handler(activityContext.getMainLooper()).post(() -> recipientListGetCallback.onSuccess(teacherList)); - }); - return; - } - - login(() -> { - List cookieList = app.cookieJar.loadForRequest(HttpUrl.get(IDZIENNIK_URL)); - for (Cookie cookie: cookieList) { - if (cookie.name().equalsIgnoreCase("Bearer")) { - loginBearerToken = cookie.value(); - } - } - loginStudentId = profile.getStudentData("studentId", null);// TODO: 2019-06-12 temporary duplicated token & ID extraction - - apiRequestArray(Request.builder() - .url(IDZIENNIK_URL + "/api/Wiadomosci/Odbiorcy?idUcznia="+loginStudentId) - .header("Authorization", "Bearer " + loginBearerToken) - .userAgent(userAgent), (result, response) -> { - teacherList = app.db.teacherDao().getAllNow(profileId); - for (JsonElement recipientEl: result) { - JsonObject recipient = recipientEl.getAsJsonObject(); - String name = recipient.get("nazwaKontaktu").getAsString(); - String loginId = recipient.get("idUzytkownika").getAsString(); - JsonArray typesArray = recipient.getAsJsonArray("typOsoby"); - List types = new ArrayList<>(); - for (JsonElement typeEl: typesArray) { - types.add(typeEl.getAsInt()); - } - String delimiter; - if (types.size() == 1 && types.get(0) >= 6) /* parent or student */ - delimiter = " ("; - else - delimiter = ": "; - String nameFirstLast = name.substring(0, name.indexOf(delimiter)); - Teacher teacher = searchTeacherByFirstLast(nameFirstLast); - teacher.loginId = loginId; - teacher.type = 0; - for (int type: types) { - switch (type) { - case 0: - teacher.setType(Teacher.TYPE_SCHOOL_ADMIN); - break; - case 1: - teacher.setType(Teacher.TYPE_SECRETARIAT); - break; - case 2: - teacher.setType(Teacher.TYPE_TEACHER); - teacher.typeDescription = name.substring(name.indexOf(": ")+2); - break; - case 3: - teacher.setType(Teacher.TYPE_PRINCIPAL); - break; - case 4: - teacher.setType(Teacher.TYPE_EDUCATOR); - break; - case 5: - teacher.setType(Teacher.TYPE_PEDAGOGUE); - break; - case 6: - teacher.setType(Teacher.TYPE_PARENT); - teacher.typeDescription = name.substring(name.indexOf(" (")+2, name.lastIndexOf(" (")); - break; - case 7: - teacher.setType(Teacher.TYPE_STUDENT); - break; - } - } - } - app.db.teacherDao().addAll(teacherList); - - profile.setLastReceiversSync(System.currentTimeMillis()); - app.db.profileDao().add(profile); - - new Handler(activityContext.getMainLooper()).post(() -> recipientListGetCallback.onSuccess(new ArrayList<>(teacherList))); - }); - }); - } - - @Override - public MessagesComposeInfo getComposeInfo(@NonNull ProfileFull profile) { - return new MessagesComposeInfo(0, 0, 180, 1983); - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Librus.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Librus.java deleted file mode 100644 index 5c7356e2..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Librus.java +++ /dev/null @@ -1,3872 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api; - -import android.content.Context; -import android.graphics.Color; -import android.os.AsyncTask; -import android.os.Handler; -import android.util.Base64; -import android.util.Pair; -import android.util.SparseArray; -import android.util.SparseIntArray; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import com.crashlytics.android.Crashlytics; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonNull; -import com.google.gson.JsonObject; -import com.google.gson.reflect.TypeToken; - -import org.jsoup.Jsoup; -import org.jsoup.nodes.Document; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Parser; -import org.jsoup.select.Elements; - -import java.text.DateFormat; -import java.text.DecimalFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import im.wangchao.mhttp.Request; -import im.wangchao.mhttp.Response; -import im.wangchao.mhttp.body.MediaTypeUtils; -import im.wangchao.mhttp.callback.JsonCallbackHandler; -import im.wangchao.mhttp.callback.TextCallbackHandler; -import pl.szczodrzynski.edziennik.App; -import pl.szczodrzynski.edziennik.BuildConfig; -import pl.szczodrzynski.edziennik.R; -import pl.szczodrzynski.edziennik.data.api.interfaces.AttachmentGetCallback; -import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface; -import pl.szczodrzynski.edziennik.data.api.interfaces.LoginCallback; -import pl.szczodrzynski.edziennik.data.api.interfaces.MessageGetCallback; -import pl.szczodrzynski.edziennik.data.api.interfaces.RecipientListGetCallback; -import pl.szczodrzynski.edziennik.data.api.interfaces.SyncCallback; -import pl.szczodrzynski.edziennik.data.api.v2.models.DataStore; -import pl.szczodrzynski.edziennik.data.db.modules.announcements.Announcement; -import pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance; -import pl.szczodrzynski.edziennik.data.db.modules.events.Event; -import pl.szczodrzynski.edziennik.data.db.modules.events.EventType; -import pl.szczodrzynski.edziennik.data.db.modules.grades.Grade; -import pl.szczodrzynski.edziennik.data.db.modules.grades.GradeCategory; -import pl.szczodrzynski.edziennik.data.db.modules.lessons.Lesson; -import pl.szczodrzynski.edziennik.data.db.modules.lessons.LessonChange; -import pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore; -import pl.szczodrzynski.edziennik.data.db.modules.luckynumber.LuckyNumber; -import pl.szczodrzynski.edziennik.data.db.modules.messages.Message; -import pl.szczodrzynski.edziennik.data.db.modules.messages.MessageFull; -import pl.szczodrzynski.edziennik.data.db.modules.messages.MessageRecipient; -import pl.szczodrzynski.edziennik.data.db.modules.messages.MessageRecipientFull; -import pl.szczodrzynski.edziennik.data.db.modules.metadata.Metadata; -import pl.szczodrzynski.edziennik.data.db.modules.notices.Notice; -import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile; -import pl.szczodrzynski.edziennik.data.db.modules.profiles.ProfileFull; -import pl.szczodrzynski.edziennik.data.db.modules.subjects.Subject; -import pl.szczodrzynski.edziennik.data.db.modules.teachers.Teacher; -import pl.szczodrzynski.edziennik.data.db.modules.teachers.TeacherAbsence; -import pl.szczodrzynski.edziennik.data.db.modules.teams.Team; -import pl.szczodrzynski.edziennik.ui.modules.messages.MessagesComposeInfo; -import pl.szczodrzynski.edziennik.utils.models.Date; -import pl.szczodrzynski.edziennik.utils.models.Endpoint; -import pl.szczodrzynski.edziennik.utils.models.Time; -import pl.szczodrzynski.edziennik.utils.models.Week; -import pl.szczodrzynski.edziennik.utils.Utils; - -import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; -import static java.net.HttpURLConnection.HTTP_FORBIDDEN; -import static java.net.HttpURLConnection.HTTP_GONE; -import static java.net.HttpURLConnection.HTTP_NOT_FOUND; -import static java.net.HttpURLConnection.HTTP_OK; -import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_INVALID_LOGIN; -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_LIBRUS_DISCONNECTED; -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_LIBRUS_NOT_ACTIVATED; -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_MAINTENANCE; -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_OTHER; -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_PROFILE_NOT_FOUND; -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_SYNERGIA_NOT_ACTIVATED; -import static pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance.TYPE_ABSENT; -import static pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance.TYPE_ABSENT_EXCUSED; -import static pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance.TYPE_BELATED; -import static pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance.TYPE_PRESENT; -import static pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance.TYPE_RELEASED; -import static pl.szczodrzynski.edziennik.data.db.modules.events.Event.TYPE_PT_MEETING; -import static pl.szczodrzynski.edziennik.data.db.modules.events.Event.TYPE_TEACHER_ABSENCE; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_NORMAL; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_SEMESTER1_FINAL; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_SEMESTER1_PROPOSED; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_SEMESTER2_FINAL; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_SEMESTER2_PROPOSED; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_YEAR_FINAL; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_YEAR_PROPOSED; -import static pl.szczodrzynski.edziennik.data.db.modules.lessons.LessonChange.TYPE_CANCELLED; -import static pl.szczodrzynski.edziennik.data.db.modules.lessons.LessonChange.TYPE_CHANGE; -import static pl.szczodrzynski.edziennik.data.db.modules.messages.Message.TYPE_RECEIVED; -import static pl.szczodrzynski.edziennik.data.db.modules.messages.Message.TYPE_SENT; -import static pl.szczodrzynski.edziennik.data.db.modules.notices.Notice.TYPE_NEGATIVE; -import static pl.szczodrzynski.edziennik.data.db.modules.notices.Notice.TYPE_NEUTRAL; -import static pl.szczodrzynski.edziennik.data.db.modules.notices.Notice.TYPE_POSITIVE; -import static pl.szczodrzynski.edziennik.data.db.modules.teachers.Teacher.TYPE_EDUCATOR; -import static pl.szczodrzynski.edziennik.data.db.modules.teachers.Teacher.TYPE_LIBRARIAN; -import static pl.szczodrzynski.edziennik.data.db.modules.teachers.Teacher.TYPE_OTHER; -import static pl.szczodrzynski.edziennik.data.db.modules.teachers.Teacher.TYPE_PARENTS_COUNCIL; -import static pl.szczodrzynski.edziennik.data.db.modules.teachers.Teacher.TYPE_PEDAGOGUE; -import static pl.szczodrzynski.edziennik.data.db.modules.teachers.Teacher.TYPE_SCHOOL_ADMIN; -import static pl.szczodrzynski.edziennik.data.db.modules.teachers.Teacher.TYPE_SCHOOL_PARENTS_COUNCIL; -import static pl.szczodrzynski.edziennik.data.db.modules.teachers.Teacher.TYPE_SECRETARIAT; -import static pl.szczodrzynski.edziennik.data.db.modules.teachers.Teacher.TYPE_SUPER_ADMIN; -import static pl.szczodrzynski.edziennik.data.db.modules.teachers.Teacher.TYPE_TEACHER; -import static pl.szczodrzynski.edziennik.utils.Utils.bs; -import static pl.szczodrzynski.edziennik.utils.Utils.c; -import static pl.szczodrzynski.edziennik.utils.Utils.contains; -import static pl.szczodrzynski.edziennik.utils.Utils.crc16; -import static pl.szczodrzynski.edziennik.utils.Utils.d; -import static pl.szczodrzynski.edziennik.utils.Utils.getGradeValue; -import static pl.szczodrzynski.edziennik.utils.Utils.strToInt; - -public class Librus implements EdziennikInterface { - public Librus(App app) { - this.app = app; - } - - private static final String TAG = "api.Librus"; - private static final String CLIENT_ID = "wmSyUMo8llDAs4y9tJVYY92oyZ6h4lAt7KCuy0Gv"; - private static final String REDIRECT_URL = "http://localhost/bar"; - private static final String AUTHORIZE_URL = "https://portal.librus.pl/oauth2/authorize?client_id="+CLIENT_ID+"&redirect_uri="+REDIRECT_URL+"&response_type=code"; - private static final String LOGIN_URL = "https://portal.librus.pl/rodzina/login/action"; - private static final String TOKEN_URL = "https://portal.librus.pl/oauth2/access_token"; - private static final String ACCOUNTS_URL = "https://portal.librus.pl/api/v2/SynergiaAccounts"; - private static final String ACCOUNT_URL = "https://portal.librus.pl/api/v2/SynergiaAccounts/fresh/"; // + login - private static final String API_URL = "https://api.librus.pl/2.0/"; - private static final String SYNERGIA_URL = "https://wiadomosci.librus.pl/module/"; - private static final String SYNERGIA_SANDBOX_URL = "https://sandbox.librus.pl/index.php?action="; - private static final String userAgent = "Dalvik/2.1.0 Android LibrusMobileApp"; - private static final String synergiaUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Gecko/20100101 Firefox/62.0"; - - private App app; - private Context activityContext = null; - private SyncCallback callback = null; - private int profileId = -1; - private Profile profile = null; - private LoginStore loginStore = null; - private boolean fullSync = true; - private Date today; - private List targetEndpoints = new ArrayList<>(); - - // PROGRESS - private static final int PROGRESS_LOGIN = 10; - private int PROGRESS_COUNT = 1; - private int PROGRESS_STEP = (90/PROGRESS_COUNT); - - private int onlyFeature = FEATURE_ALL; - - private List teamList; - private List teacherList; - private List teacherAbsenceList; - private List subjectList; - private List lessonList; - private List lessonChangeList; - private List gradeCategoryList; - private List gradeList; - private List eventList; - private List eventTypeList; - private List noticeList; - private List attendanceList; - private List announcementList; - private List messageList; - private List messageRecipientList; - private List messageRecipientIgnoreList; - private List metadataList; - private List messageMetadataList; - - private static boolean fakeLogin = false; - private String librusEmail = null; - private String librusPassword = null; - private String synergiaLogin = null; - private String synergiaPassword = null; - private String synergiaLastLogin = null; - private long synergiaLastLoginTime = -1; - private boolean premium = false; - private boolean enableStandardGrades = true; - private boolean enablePointGrades = false; - private boolean enableDescriptiveGrades = false; - private boolean enableTextGrades = false; - private boolean enableBehaviourGrades = true; - private long unitId = -1; - private int startPointsSemester1 = 0; - private int startPointsSemester2 = 0; - - private boolean prepare(@NonNull Context activityContext, @NonNull SyncCallback callback, int profileId, @Nullable Profile profile, @NonNull LoginStore loginStore) { - this.activityContext = activityContext; - this.callback = callback; - this.profileId = profileId; - // here we must have a login store: either with a correct ID or -1 - // there may be no profile and that's when onLoginFirst happens - this.profile = profile; - this.loginStore = loginStore; - this.fullSync = profile == null || profile.getEmpty() || profile.shouldFullSync(activityContext); - this.today = Date.getToday(); - - DataStore ds = new DataStore(app.db, profileId); - - this.librusEmail = loginStore.getLoginData("email", ""); - this.librusPassword = loginStore.getLoginData("password", ""); - if (profile == null) { - this.synergiaLogin = null; - this.synergiaPassword = null; - } - else { - this.synergiaLogin = profile.getStudentData("accountLogin", null); - this.synergiaPassword = profile.getStudentData("accountPassword", null); - } - if (librusEmail.equals("") || librusPassword.equals("")) { - finishWithError(new AppError(TAG, 214, AppError.CODE_INVALID_LOGIN, "Login field is empty")); - return false; - } - this.premium = profile != null && profile.getStudentData("isPremium", false); - this.failed = 0; - fakeLogin = BuildConfig.DEBUG && librusEmail.toLowerCase().startsWith("fake"); - this.synergiaLastLogin = null; - this.synergiaLastLoginTime = -1; - - this.refreshTokenFailed = false; - - teamList = profileId == -1 ? new ArrayList<>() : app.db.teamDao().getAllNow(profileId); - teacherList = profileId == -1 ? new ArrayList<>() : app.db.teacherDao().getAllNow(profileId); - teacherAbsenceList = new ArrayList<>(); - subjectList = new ArrayList<>(); - lessonList = new ArrayList<>(); - lessonChangeList = new ArrayList<>(); - gradeCategoryList = new ArrayList<>(); - gradeList = new ArrayList<>(); - eventList = new ArrayList<>(); - eventTypeList = new ArrayList<>(); - noticeList = new ArrayList<>(); - attendanceList = new ArrayList<>(); - announcementList = new ArrayList<>(); - messageList = new ArrayList<>(); - messageRecipientList = new ArrayList<>(); - messageRecipientIgnoreList = new ArrayList<>(); - metadataList = new ArrayList<>(); - messageMetadataList = new ArrayList<>(); - - return true; - } - - @Override - public void sync(@NonNull Context activityContext, @NonNull SyncCallback callback, int profileId, @Nullable Profile profile, @NonNull LoginStore loginStore) { - if (!prepare(activityContext, callback, profileId, profile, loginStore)) - return; - - login(() -> { - targetEndpoints = new ArrayList<>(); - targetEndpoints.add("Me"); - targetEndpoints.add("Schools"); - targetEndpoints.add("Classes"); - targetEndpoints.add("VirtualClasses"); - targetEndpoints.add("Units"); - targetEndpoints.add("Users"); - targetEndpoints.add("Subjects"); - targetEndpoints.add("Classrooms"); - targetEndpoints.add("Substitutions"); - targetEndpoints.add("Timetables"); - targetEndpoints.add("Colors"); - - targetEndpoints.add("SavedGradeCategories"); - targetEndpoints.add("GradesCategories"); - targetEndpoints.add("PointGradesCategories"); - targetEndpoints.add("DescriptiveGradesCategories"); - //targetEndpoints.add("TextGradesCategories"); - targetEndpoints.add("BehaviourGradesCategories"); // TODO: 2019-04-30 - targetEndpoints.add("SaveGradeCategories"); - - targetEndpoints.add("Grades"); - targetEndpoints.add("PointGrades"); - targetEndpoints.add("DescriptiveGrades"); - targetEndpoints.add("TextGrades"); - targetEndpoints.add("BehaviourGrades"); - targetEndpoints.add("GradesComments"); - - targetEndpoints.add("Events"); - targetEndpoints.add("TeacherFreeDays"); - targetEndpoints.add("CustomTypes"); - targetEndpoints.add("Homework"); - targetEndpoints.add("LuckyNumbers"); - targetEndpoints.add("Notices"); - targetEndpoints.add("AttendanceTypes"); - targetEndpoints.add("Attendance"); - targetEndpoints.add("Announcements"); - targetEndpoints.add("PtMeetings"); - - /*if (isEndpointEnabled(profile, true, "SchoolFreeDays")) - targetEndpoints.add("SchoolFreeDays"); - if (isEndpointEnabled(profile, true, "ClassFreeDays")) - targetEndpoints.add("ClassFreeDays");*/ - targetEndpoints.add("MessagesLogin"); - targetEndpoints.add("MessagesInbox"); - targetEndpoints.add("MessagesOutbox"); - targetEndpoints.add("Finish"); - PROGRESS_COUNT = targetEndpoints.size()-1; - PROGRESS_STEP = (90/PROGRESS_COUNT); - begin(); - }); - } - @Override - public void syncFeature(@NonNull Context activityContext, @NonNull SyncCallback callback, @NonNull ProfileFull profile, int ... featureList) { - if (featureList == null) { - sync(activityContext, callback, profile.getId(), profile, LoginStore.fromProfileFull(profile)); - return; - } - if (!prepare(activityContext, callback, profile.getId(), profile, LoginStore.fromProfileFull(profile))) - return; - - login(() -> { - targetEndpoints = new ArrayList<>(); - if (featureList.length == 1) - onlyFeature = featureList[0]; - targetEndpoints.add("Me"); - targetEndpoints.add("Schools"); - targetEndpoints.add("Classes"); - targetEndpoints.add("VirtualClasses"); - targetEndpoints.add("Units"); - targetEndpoints.add("Users"); - targetEndpoints.add("Subjects"); - targetEndpoints.add("Colors"); - boolean hasMessagesLogin = false; - for (int feature: featureList) { - switch (feature) { - case FEATURE_TIMETABLE: - targetEndpoints.add("Classrooms"); - targetEndpoints.add("Substitutions"); - targetEndpoints.add("Timetables"); - break; - case FEATURE_AGENDA: - targetEndpoints.add("Events"); - targetEndpoints.add("CustomTypes"); - targetEndpoints.add("PtMeetings"); - targetEndpoints.add("SchoolFreeDays"); - targetEndpoints.add("TeacherFreeDays"); - break; - case FEATURE_GRADES: - targetEndpoints.add("SavedGradeCategories"); - targetEndpoints.add("GradesCategories"); - targetEndpoints.add("PointGradesCategories"); - targetEndpoints.add("DescriptiveGradesCategories"); - //targetEndpoints.add("TextGradesCategories"); - targetEndpoints.add("BehaviourGradesCategories"); // TODO: 2019-04-30 - targetEndpoints.add("SaveGradeCategories"); - - targetEndpoints.add("Grades"); - targetEndpoints.add("PointGrades"); - targetEndpoints.add("DescriptiveGrades"); - targetEndpoints.add("TextGrades"); - targetEndpoints.add("BehaviourGrades"); - - targetEndpoints.add("GradesComments"); - break; - case FEATURE_HOMEWORK: - targetEndpoints.add("Homework"); - break; - case FEATURE_NOTICES: - targetEndpoints.add("Notices"); - break; - case FEATURE_ATTENDANCE: - targetEndpoints.add("AttendanceTypes"); - targetEndpoints.add("Attendance"); - break; - case FEATURE_MESSAGES_INBOX: - if (!hasMessagesLogin) { - hasMessagesLogin = true; - targetEndpoints.add("MessagesLogin"); - } - targetEndpoints.add("MessagesInbox"); - break; - case FEATURE_MESSAGES_OUTBOX: - if (!hasMessagesLogin) { - hasMessagesLogin = true; - targetEndpoints.add("MessagesLogin"); - } - targetEndpoints.add("MessagesOutbox"); - break; - case FEATURE_ANNOUNCEMENTS: - targetEndpoints.add("Announcements"); - break; - } - } - targetEndpoints.add("LuckyNumbers"); - - /*if (isEndpointEnabled(profile, true, "SchoolFreeDays")) - targetEndpoints.add("SchoolFreeDays"); - if (isEndpointEnabled(profile, true, "ClassFreeDays")) - targetEndpoints.add("ClassFreeDays");*/ - targetEndpoints.add("Finish"); - PROGRESS_COUNT = targetEndpoints.size()-1; - PROGRESS_STEP = (90/PROGRESS_COUNT); - begin(); - }); - } - - private void begin() { - if (profile == null) { - finishWithError(new AppError(TAG, 214, AppError.CODE_PROFILE_NOT_FOUND, "Profile == null WTF???")); - return; - } - String accountToken = profile.getStudentData("accountToken", null); - d(TAG, "Beginning account "+ profile.getStudentNameLong() +" sync with token "+accountToken+". Full sync enabled "+fullSync); - synergiaAccessToken = accountToken; - - callback.onProgress(PROGRESS_LOGIN); - - r("get", null); - } - - private void r(String type, String endpoint) { - // endpoint == null when beginning - if (endpoint == null) - endpoint = targetEndpoints.get(0); - int index = -1; - for (String request: targetEndpoints) { - index++; - if (request.equals(endpoint)) { - break; - } - } - if (type.equals("finish")) { - // called when finishing the action - callback.onProgress(PROGRESS_STEP); - index++; - } - if (index > targetEndpoints.size()) { - finish(); - return; - } - d(TAG, "Called r("+type+", "+endpoint+"). Getting "+targetEndpoints.get(index)); - switch (targetEndpoints.get(index)) { - case "Me": - getMe(); - break; - case "Schools": - getSchools(); - break; - case "Classes": - getClasses(); - break; - case "VirtualClasses": - getVirtualClasses(); - break; - case "Units": - getUnits(); - break; - case "Users": - getUsers(); - break; - case "Subjects": - getSubjects(); - break; - case "Classrooms": - getClassrooms(); - break; - case "Timetables": - getTimetables(); - break; - case "Substitutions": - getSubstitutions(); - break; - case "Colors": - getColors(); - break; - case "SavedGradeCategories": - getSavedGradeCategories(); - break; - case "GradesCategories": - getGradesCategories(); - break; - case "PointGradesCategories": - getPointGradesCategories(); - break; - case "DescriptiveGradesCategories": - getDescriptiveGradesSkills(); - break; - case "TextGradesCategories": - getTextGradesCategories(); - break; - case "BehaviourGradesCategories": - getBehaviourGradesCategories(); - break; - case "SaveGradeCategories": - saveGradeCategories(); - break; - case "Grades": - getGrades(); - break; - case "PointGrades": - getPointGrades(); - break; - case "DescriptiveGrades": - getDescriptiveGrades(); - break; - case "TextGrades": - getTextGrades(); - break; - case "GradesComments": - getGradesComments(); - break; - case "BehaviourGrades": - getBehaviourGrades(); - break; - case "Events": - getEvents(); - break; - case "CustomTypes": - getCustomTypes(); - break; - case "Homework": - getHomework(); - break; - case "LuckyNumbers": - getLuckyNumbers(); - break; - case "Notices": - getNotices(); - break; - case "AttendanceTypes": - getAttendanceTypes(); - break; - case "Attendance": - getAttendance(); - break; - case "Announcements": - getAnnouncements(); - break; - case "PtMeetings": - getPtMeetings(); - break; - case "TeacherFreeDaysTypes": - getTeacherFreeDaysTypes(); - break; - case "TeacherFreeDays": - getTeacherFreeDays(); - break; - case "SchoolFreeDays": - getSchoolFreeDays(); - break; - case "MessagesLogin": - getMessagesLogin(); - break; - case "MessagesInbox": - getMessagesInbox(); - break; - case "MessagesOutbox": - getMessagesOutbox(); - break; - case "Finish": - finish(); - break; - } - } - private void saveData() { - if (teamList.size() > 0) { - //app.db.teamDao().clear(profileId); - app.db.teamDao().addAll(teamList); - } - if (teacherList.size() > 0 && teacherListChanged) - app.db.teacherDao().addAllIgnore(teacherList); - if (subjectList.size() > 0) - app.db.subjectDao().addAll(subjectList); - if (lessonList.size() > 0) { - app.db.lessonDao().clear(profileId); - app.db.lessonDao().addAll(lessonList); - } - if (lessonChangeList.size() > 0) - app.db.lessonChangeDao().addAll(lessonChangeList); - if (gradeCategoryList.size() > 0 && gradeCategoryListChanged) - app.db.gradeCategoryDao().addAll(gradeCategoryList); - if (gradeList.size() > 0) { - app.db.gradeDao().clear(profileId); - app.db.gradeDao().addAll(gradeList); - } - if (eventList.size() > 0) { - app.db.eventDao().removeFuture(profileId, Date.getToday()); - app.db.eventDao().addAll(eventList); - } - if (eventTypeList.size() > 0) - app.db.eventTypeDao().addAll(eventTypeList); - if (teacherAbsenceList.size() > 0) - app.db.teacherAbsenceDao().addAll(teacherAbsenceList); - if (noticeList.size() > 0) { - app.db.noticeDao().clear(profileId); - app.db.noticeDao().addAll(noticeList); - } - if (attendanceList.size() > 0) - app.db.attendanceDao().addAll(attendanceList); - if (announcementList.size() > 0) - app.db.announcementDao().addAll(announcementList); - if (messageList.size() > 0) - app.db.messageDao().addAllIgnore(messageList); - if (messageRecipientList.size() > 0) - app.db.messageRecipientDao().addAll(messageRecipientList); - if (messageRecipientIgnoreList.size() > 0) - app.db.messageRecipientDao().addAllIgnore(messageRecipientIgnoreList); - if (metadataList.size() > 0) - app.db.metadataDao().addAllIgnore(metadataList); - if (messageMetadataList.size() > 0) - app.db.metadataDao().setSeen(messageMetadataList); - } - private void finish() { - try { - saveData(); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 480, CODE_OTHER, app.getString(R.string.sync_error_saving_data), null, null, e, null)); - } - if (fullSync) { - profile.setLastFullSync(System.currentTimeMillis()); - fullSync = false; - } - profile.setEmpty(false); - callback.onSuccess(activityContext, new ProfileFull(profile, loginStore)); - } - private void finishWithError(AppError error) { - try { - saveData(); - } - catch (Exception e) { - Crashlytics.logException(e); - } - callback.onError(activityContext, error); - } - - /* _ _ - | | (_) - | | ___ __ _ _ _ __ - | | / _ \ / _` | | '_ \ - | |___| (_) | (_| | | | | | - |______\___/ \__, |_|_| |_| - __/ | - |__*/ - public void login(@NonNull LoginCallback loginCallback) - { - - authorizeCallback = new AuthorizeCallback() { - @Override - public void onCsrfToken(String csrfToken) { - d(TAG, "Found CSRF token: "+csrfToken); - login(csrfToken, librusEmail, librusPassword, librusLoginCallback); - } - - @Override - public void onAuthorizationCode(String code) { - d(TAG, "Found auth code: "+code); - accessToken(code, null, accessTokenCallback); - } - }; - - librusLoginCallback = redirectUrl -> { - fakeAuthorize = "authorize"; - authorize(AUTHORIZE_URL, authorizeCallback); - }; - - accessTokenCallback = new AccessTokenCallback() { - @Override - public void onSuccess(String tokenType, String accessToken, String refreshToken, int expiresIn) { - d(TAG, "Got tokens: "+tokenType+" "+accessToken); - d(TAG, "Got tokens: "+refreshToken); - loginStore.putLoginData("tokenType", tokenType); - loginStore.putLoginData("accessToken", accessToken); - loginStore.putLoginData("refreshToken", refreshToken); - loginStore.putLoginData("tokenExpiryTime", System.currentTimeMillis()/1000 + expiresIn); - getSynergiaToken(tokenType, accessToken, refreshToken, System.currentTimeMillis()/1000 + expiresIn); - } - - @Override - public void onError() { - d(TAG, "Beginning login (authorize)"); - authorize(AUTHORIZE_URL, authorizeCallback); - } - }; - - synergiaAccountsCallback = data -> { - d(TAG, "Accounts: "+data.toString()); - JsonArray accounts = data.getAsJsonArray("accounts"); - if (accounts.size() == 0) { - finishWithError(new AppError(TAG, 1237, CODE_OTHER, app.getString(R.string.sync_error_register_no_students), data)); - return; - } - long accountDataTime; - List accountIds = new ArrayList<>(); - List accountLogins = new ArrayList<>(); - List accountTokens = new ArrayList<>(); - List accountNamesLong = new ArrayList<>(); - List accountNamesShort = new ArrayList<>(); - accountIds.clear(); - accountLogins.clear(); - accountTokens.clear(); - accountNamesLong.clear(); - accountNamesShort.clear(); - accountDataTime = data.get("lastModification").getAsLong(); - for (JsonElement accountEl: accounts) { - JsonObject account = accountEl.getAsJsonObject(); - - JsonElement state = account.get("state"); - if (state != null && !(state instanceof JsonNull)) { - if (state.getAsString().equals("requiring_an_action")) { - finishWithError(new AppError(TAG, 694, CODE_LIBRUS_DISCONNECTED, data)); - return; - } - if (state.getAsString().equals("need-activation")) { - finishWithError(new AppError(TAG, 701, CODE_SYNERGIA_NOT_ACTIVATED, data)); - return; - } - } - - accountIds.add(account.get("id").getAsInt()); - accountLogins.add(account.get("login").getAsString()); - accountTokens.add(account.get("accessToken").getAsString()); - accountNamesLong.add(account.get("studentName").getAsString()); - String[] nameParts = account.get("studentName").getAsString().split(" "); - accountNamesShort.add(nameParts[0]+" "+nameParts[1].charAt(0)+"."); - } - - List profileList = new ArrayList<>(); - for (int index = 0; index < accountIds.size(); index++) { - Profile newProfile = new Profile(); - newProfile.setStudentNameLong(accountNamesLong.get(index)); - newProfile.setStudentNameShort(accountNamesShort.get(index)); - newProfile.setName(newProfile.getStudentNameLong()); - newProfile.setSubname(librusEmail); - newProfile.setEmpty(true); - newProfile.setLoggedIn(true); - newProfile.putStudentData("accountId", accountIds.get(index)); - newProfile.putStudentData("accountLogin", accountLogins.get(index)); - newProfile.putStudentData("accountToken", accountTokens.get(index)); - newProfile.putStudentData("accountTokenTime", accountDataTime); - profileList.add(newProfile); - } - - callback.onLoginFirst(profileList, loginStore); - }; - - synergiaAccountCallback = data -> { - if (data == null) { - // 410 Gone - app.cookieJar.clearForDomain("portal.librus.pl"); - authorize(AUTHORIZE_URL, authorizeCallback); - return; - } - if (profile == null) { - // this cannot be run on a fresh login - finishWithError(new AppError(TAG, 1290, CODE_PROFILE_NOT_FOUND, "Profile == null", data)); - return; - } - d(TAG, "Account: "+data.toString()); - // synergiaAccount is executed when a synergia token needs a refresh - JsonElement id = data.get("id"); - JsonElement login = data.get("login"); - JsonElement accessToken = data.get("accessToken"); - if (id == null || login == null || accessToken == null) { - finishWithError(new AppError(TAG, 1284, CODE_OTHER, data)); - return; - } - profile.putStudentData("accountId", id.getAsInt()); - profile.putStudentData("accountLogin", login.getAsString()); - profile.putStudentData("accountToken", accessToken.getAsString()); - profile.putStudentData("accountTokenTime", System.currentTimeMillis() / 1000); - profile.setStudentNameLong(data.get("studentName").getAsString()); - String[] nameParts = data.get("studentName").getAsString().split(" "); - profile.setStudentNameShort(nameParts[0] + " " + nameParts[1].charAt(0) + "."); - loginCallback.onSuccess(); - }; - - String tokenType = loginStore.getLoginData("tokenType", "Bearer"); - String accessToken = loginStore.getLoginData("accessToken", null); - String refreshToken = loginStore.getLoginData("refreshToken", null); - long tokenExpiryTime = loginStore.getLoginData("tokenExpiryTime", (long)0); - String accountToken; - - if (profile != null - && (accountToken = profile.getStudentData("accountToken", null)) != null - && !accountToken.equals("") - && (System.currentTimeMillis() / 1000) - profile.getStudentData("accountTokenTime", (long)0) < 3 * 60 * 60) { - c(TAG, "synergia token should be valid"); - loginCallback.onSuccess(); - } - else { - getSynergiaToken(tokenType, accessToken, refreshToken, tokenExpiryTime); - } - } - private String synergiaAccessToken = ""; - private void getSynergiaToken(String tokenType, String accessToken, String refreshToken, long tokenExpiryTime) { - c(TAG, "we have no synergia token or it expired"); - if (!tokenType.equals("") - && refreshToken != null - && accessToken != null - && tokenExpiryTime-30 > System.currentTimeMillis() / 1000) { - c(TAG, "we have a valid librus token, so we can use the API"); - // we have to decide whether we can already proceed getting the synergiaToken - // or a list of students - if (profile != null) { - app.cookieJar.clearForDomain("portal.librus.pl"); - c(TAG, "user is logged in, refreshing synergia token"); - d(TAG, "Librus token: "+accessToken); - synergiaAccount(tokenType, accessToken, profile.getStudentData("accountLogin", null), synergiaAccountCallback); - } - else { - // this *should* be executed only once. ever. - c(TAG, "user is not logged in, getting all the accounts"); - synergiaAccounts(tokenType, accessToken, synergiaAccountsCallback); - } - } else if (refreshToken != null) { - c(TAG, "we don't have a valid token or it expired"); - c(TAG, "but we have a refresh token"); - d(TAG, "Token expired at " + tokenExpiryTime + ", " + (System.currentTimeMillis() / 1000 - tokenExpiryTime) + " seconds ago"); - app.cookieJar.clearForDomain("portal.librus.pl"); - accessToken(null, refreshToken, accessTokenCallback); - } else { - c(TAG, "we don't have any of the needed librus tokens"); - c(TAG, "we need to log in and generate"); - app.cookieJar.clearForDomain("portal.librus.pl"); - authorize(AUTHORIZE_URL, authorizeCallback); - } - } - public boolean loginSynergia(@NonNull LoginCallback loginCallback) - { - if (profile == null) { - return false; - } - if (synergiaLogin == null || synergiaPassword == null || synergiaLogin.equals("") || synergiaPassword.equals("")) { - finishWithError(new AppError(TAG, 1152, CODE_INVALID_LOGIN, "Login field is empty")); - return false; - } - if (System.currentTimeMillis() - synergiaLastLoginTime < 10 * 60 * 1000 && synergiaLogin.equals(synergiaLastLogin)) {// 10 minutes - loginCallback.onSuccess(); - return true; - } - - String escapedPassword = synergiaPassword.replace("&", "&");// TODO: 2019-05-07 check other chars to escape - - String body = - "\n" + - "

    \n" + - " \n" + - " "+synergiaLogin+"\n" + - " "+escapedPassword+"\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; - synergiaRequest("Login", body, data -> { - if (data == null) { - finishWithError(new AppError(TAG, 1176, AppError.CODE_MAINTENANCE, "data == null (975)")); - return; - } - String error = data.select("response Login status").text(); - if (error.equals("ok")) { - synergiaLastLoginTime = System.currentTimeMillis(); - synergiaLastLogin = synergiaLogin; - loginCallback.onSuccess(); - } - else { - finishWithError(new AppError(TAG, 1186, CODE_INVALID_LOGIN, (Response) null, data.outerHtml())); - } - }); - return true; - } - - /* _ _ _ _ _ _ _ - | | | | | | ___ | | | | | | - | |__| | ___| |_ __ ___ _ __ ___ ( _ ) ___ __ _| | | |__ __ _ ___| | _____ - | __ |/ _ \ | '_ \ / _ \ '__/ __| / _ \/\ / __/ _` | | | '_ \ / _` |/ __| |/ / __| - | | | | __/ | |_) | __/ | \__ \ | (_> < | (_| (_| | | | |_) | (_| | (__| <\__ \ - |_| |_|\___|_| .__/ \___|_| |___/ \___/\/ \___\__,_|_|_|_.__/ \__,_|\___|_|\_\___/ - | | - |*/ - private String fakeAuthorize = "authorize"; - private void authorize(String url, AuthorizeCallback authorizeCallback) { - callback.onActionStarted(R.string.sync_action_authorizing); - Request.builder() - .url(fakeLogin ? "http://szkolny.eu/librus/"+fakeAuthorize+".php" : url) - .userAgent(userAgent) - .withClient(app.httpLazy) - .callback(new TextCallbackHandler() { - @Override - public void onSuccess(String data, Response response) { - //d("headers "+response.headers().toString()); - String location = response.headers().get("Location"); - if (location != null) { - Matcher authMatcher = Pattern.compile(REDIRECT_URL+"\\?code=([A-z0-9]+?)$", Pattern.DOTALL | Pattern.MULTILINE).matcher(location); - if (authMatcher.find()) { - authorizeCallback.onAuthorizationCode(authMatcher.group(1)); - } - else { - //callback.onError(activityContext, Edziennik.CODE_OTHER, "Auth code not found: "+location); - authorize(location, authorizeCallback); - } - } - else { - Matcher csrfMatcher = Pattern.compile("name=\"csrf-token\" content=\"([A-z0-9=+/\\-_]+?)\"", Pattern.DOTALL).matcher(data); - if (csrfMatcher.find()) { - authorizeCallback.onCsrfToken(csrfMatcher.group(1)); - } - else { - finishWithError(new AppError(TAG, 463, CODE_OTHER, "CSRF token not found.", response, data)); - } - } - } - - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 207, CODE_OTHER, response, throwable)); - } - }) - .build() - .enqueue(); - } - - private void login(String csrfToken, String email, String password, LibrusLoginCallback librusLoginCallback) { - callback.onActionStarted(R.string.sync_action_logging_in); - Request.builder() - .url(fakeLogin ? "http://szkolny.eu/librus/login_action.php" : LOGIN_URL) - .userAgent(userAgent) - .addParameter("email", email) - .addParameter("password", password) - .addHeader("X-CSRF-TOKEN", csrfToken) - .contentType(MediaTypeUtils.APPLICATION_JSON) - .post() - .callback(new JsonCallbackHandler() { - @Override - public void onSuccess(JsonObject data, Response response) { - if (data == null) { - if (response.parserErrorBody != null && response.parserErrorBody.contains("link aktywacyjny")) { - finishWithError(new AppError(TAG, 487, CODE_LIBRUS_NOT_ACTIVATED, response)); - return; - } - finishWithError(new AppError(TAG, 489, CODE_MAINTENANCE, response)); - return; - } - if (data.get("errors") != null) { - finishWithError(new AppError(TAG, 490, CODE_OTHER, data.get("errors").getAsJsonArray().get(0).getAsString(), response, data)); - return; - } - librusLoginCallback.onLogin(data.get("redirect") != null ? data.get("redirect").getAsString() : ""); - } - - @Override - public void onFailure(Response response, Throwable throwable) { - if (response.code() == 403 - || response.code() == 401) { - finishWithError(new AppError(TAG, 248, AppError.CODE_INVALID_LOGIN, response, throwable)); - return; - } - finishWithError(new AppError(TAG, 251, CODE_OTHER, response, throwable)); - } - }) - .build() - .enqueue(); - } - - private boolean refreshTokenFailed = false; - private void accessToken(String code, String refreshToken, AccessTokenCallback accessTokenCallback) { - callback.onActionStarted(R.string.sync_action_getting_token); - List> params = new ArrayList<>(); - params.add(new Pair<>("client_id", CLIENT_ID)); - if (code != null) { - params.add(new Pair<>("grant_type", "authorization_code")); - params.add(new Pair<>("code", code)); - params.add(new Pair<>("redirect_uri", REDIRECT_URL)); - } - else if (refreshToken != null) { - params.add(new Pair<>("grant_type", "refresh_token")); - params.add(new Pair<>("refresh_token", refreshToken)); - } - Request.builder() - .url(fakeLogin ? "http://szkolny.eu/librus/access_token.php" : TOKEN_URL) - .userAgent(userAgent) - .addParams(params) - .allowErrorCode(HTTP_UNAUTHORIZED) - .post() - .callback(new JsonCallbackHandler() { - @Override - public void onSuccess(JsonObject data, Response response) { - if (data == null) { - finishWithError(new AppError(TAG, 539, CODE_MAINTENANCE, response)); - return; - } - if (data.get("error") != null) { - JsonElement message = data.get("message"); - JsonElement hint = data.get("hint"); - if (!refreshTokenFailed && refreshToken != null && hint != null && (hint.getAsString().equals("Token has been revoked") || hint.getAsString().equals("Token has expired"))) { - c(TAG, "refreshing the token failed. Trying to log in again."); - refreshTokenFailed = true; - accessTokenCallback.onError(); - return; - } - String errorText = data.get("error").getAsString()+" "+(message == null ? "" : message.getAsString())+" "+(hint == null ? "" : hint.getAsString()); - finishWithError(new AppError(TAG, 552, CODE_OTHER, errorText, response, data)); - return; - } - try { - accessTokenCallback.onSuccess( - data.get("token_type").getAsString(), - data.get("access_token").getAsString(), - data.get("refresh_token").getAsString(), - data.get("expires_in").getAsInt()); - } - catch (NullPointerException e) { - finishWithError(new AppError(TAG, 311, CODE_OTHER, response, e, data)); - } - } - - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 317, CODE_OTHER, response, throwable)); - } - }) - .build() - .enqueue(); - } - - private void synergiaAccounts(String tokenType, String accessToken, SynergiaAccountsCallback synergiaAccountsCallback) { - callback.onActionStarted(R.string.sync_action_getting_accounts); - Request.builder() - .url(fakeLogin ? "http://szkolny.eu/librus/synergia_accounts.php" : ACCOUNTS_URL) - .userAgent(userAgent) - .addHeader("Authorization", tokenType+" "+accessToken) - .get() - .allowErrorCode(HTTP_FORBIDDEN) - .allowErrorCode(HTTP_UNAUTHORIZED) - .allowErrorCode(HTTP_BAD_REQUEST) - .callback(new JsonCallbackHandler() { - @Override - public void onSuccess(JsonObject data, Response response) { - if (data == null) { - finishWithError(new AppError(TAG, 590, CODE_MAINTENANCE, response)); - return; - } - if (data.get("error") != null) { - JsonElement message = data.get("message"); - JsonElement hint = data.get("hint"); - String errorText = data.get("error").getAsString()+" "+(message == null ? "" : message.getAsString())+" "+(hint == null ? "" : hint.getAsString()); - finishWithError(new AppError(TAG, 597, CODE_OTHER, errorText, response, data)); - return; - } - try { - synergiaAccountsCallback.onSuccess(data); - } - catch (NullPointerException e) { - e.printStackTrace(); - finishWithError(new AppError(TAG, 358, CODE_OTHER, response, e, data)); - } - } - - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 364, CODE_OTHER, response, throwable)); - } - }) - .build() - .enqueue(); - } - - private boolean error410 = false; - - private void synergiaAccount(String tokenType, String accessToken, String accountLogin, SynergiaAccountCallback synergiaAccountCallback) { - callback.onActionStarted(R.string.sync_action_getting_account); - d(TAG, "Requesting "+(fakeLogin ? "http://szkolny.eu/librus/synergia_accounts_fresh.php?login="+accountLogin : ACCOUNT_URL+accountLogin)); - if (accountLogin == null) { // just for safety - synergiaAccounts(tokenType, accessToken, synergiaAccountsCallback); - return; - } - Request.builder() - .url(fakeLogin ? "http://szkolny.eu/librus/synergia_accounts_fresh.php?login="+accountLogin : ACCOUNT_URL+accountLogin) - .userAgent(userAgent) - .addHeader("Authorization", tokenType+" "+accessToken) - .get() - .allowErrorCode(HTTP_NOT_FOUND) - .allowErrorCode(HTTP_FORBIDDEN) - .allowErrorCode(HTTP_UNAUTHORIZED) - .allowErrorCode(HTTP_BAD_REQUEST) - .allowErrorCode(HTTP_GONE) - .callback(new JsonCallbackHandler() { - @Override - public void onSuccess(JsonObject data, Response response) { - if (data == null) { - finishWithError(new AppError(TAG, 641, CODE_MAINTENANCE, response)); - return; - } - if (response.code() == 410 && !error410) { - JsonElement reason = data.get("reason"); - if (reason != null && !(reason instanceof JsonNull) && reason.getAsString().equals("requires_an_action")) { - finishWithError(new AppError(TAG, 1078, CODE_LIBRUS_DISCONNECTED, response, data)); - return; - } - error410 = true; - synergiaAccountCallback.onSuccess(null); - return; - } - if (data.get("message") != null) { - String message = data.get("message").getAsString(); - if (message.equals("Account not found")) { - finishWithError(new AppError(TAG, 651, CODE_OTHER, app.getString(R.string.sync_error_register_student_not_associated_format, profile.getStudentNameLong(), accountLogin), response, data)); - return; - } - finishWithError(new AppError(TAG, 654, CODE_OTHER, message+"\n\n"+accountLogin, response, data)); - return; - } - if (response.code() == HTTP_OK) { - try { - synergiaAccountCallback.onSuccess(data); - } catch (NullPointerException e) { - e.printStackTrace(); - finishWithError(new AppError(TAG, 662, CODE_OTHER, response, e, data)); - } - } - else { - finishWithError(new AppError(TAG, 425, CODE_OTHER, response, data)); - } - } - - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 432, CODE_OTHER, response, throwable)); - } - }) - .build() - .enqueue(); - } - - private int failed = 0; - - private void apiRequest(String endpoint, ApiRequestCallback apiRequestCallback) { - d(TAG, "Requesting "+API_URL+endpoint); - Request.builder() - .url(fakeLogin ? "http://szkolny.eu/librus/api/"+endpoint : API_URL+endpoint) - .userAgent(userAgent) - .addHeader("Authorization", "Bearer "+synergiaAccessToken) - .get() - .allowErrorCode(HTTP_FORBIDDEN) - .allowErrorCode(HTTP_UNAUTHORIZED) - .allowErrorCode(HTTP_BAD_REQUEST) - .callback(new JsonCallbackHandler() { - @Override - public void onSuccess(JsonObject data, Response response) { - if (data == null) { - if (response.parserErrorBody != null && response.parserErrorBody.equals("Nieprawidłowy węzeł.")) { - apiRequestCallback.onSuccess(null); - return; - } - finishWithError(new AppError(TAG, 453, CODE_MAINTENANCE, response)); - return; - } - if (data.get("Status") != null) { - JsonElement message = data.get("Message"); - JsonElement code = data.get("Code"); - d(TAG, "apiRequest Error "+data.get("Status").getAsString()+" "+(message == null ? "" : message.getAsString())+" "+(code == null ? "" : code.getAsString())+"\n\n"+response.request().url().toString()); - if (message != null && !(message instanceof JsonNull) && message.getAsString().equals("Student timetable is not public")) { - try { - apiRequestCallback.onSuccess(null); - } - catch (NullPointerException e) { - e.printStackTrace(); - d(TAG, "apiRequest exception "+e.getMessage()); - finishWithError(new AppError(TAG, 503, CODE_OTHER, response, e, data)); - } - return; - } - if (code != null - && !(code instanceof JsonNull) - && (code.getAsString().equals("LuckyNumberIsNotActive") - || code.getAsString().equals("NotesIsNotActive") - || code.getAsString().equals("AccessDeny")) - ) { - try { - apiRequestCallback.onSuccess(null); - } - catch (NullPointerException e) { - e.printStackTrace(); - d(TAG, "apiRequest exception "+e.getMessage()); - finishWithError(new AppError(TAG, 504, CODE_OTHER, response, e, data)); - } - return; - } - String errorText = data.get("Status").getAsString()+" "+(message == null ? "" : message.getAsString())+" "+(code == null ? "" : code.getAsString()); - if (code != null && !(code instanceof JsonNull) && code.getAsString().equals("TokenIsExpired")) { - failed++; - d(TAG, "Trying to refresh synergia token, api request failed "+failed+" times now"); - if (failed > 1) { - d(TAG, "Giving up, failed "+failed+" times"); - finishWithError(new AppError(TAG, 485, CODE_OTHER, errorText, response, data)); - return; - } - String tokenType = loginStore.getLoginData("tokenType", "Bearer"); - String accessToken = loginStore.getLoginData("accessToken", null); - String refreshToken = loginStore.getLoginData("refreshToken", null); - long tokenExpiryTime = loginStore.getLoginData("tokenExpiryTime", (long)0); - getSynergiaToken(tokenType, accessToken, refreshToken, tokenExpiryTime); - return; - } - finishWithError(new AppError(TAG, 497, CODE_OTHER, errorText, response, data)); - return; - } - try { - apiRequestCallback.onSuccess(data); - } - catch (NullPointerException e) { - e.printStackTrace(); - d(TAG, "apiRequest exception "+e.getMessage()); - finishWithError(new AppError(TAG, 505, CODE_OTHER, response, e, data)); - } - } - - @Override - public void onFailure(Response response, Throwable throwable) { - if (response.code() == 405) { - // method not allowed - finishWithError(new AppError(TAG, 511, CODE_OTHER, response, throwable)); - return; - } - if (response.code() == 500) { - // TODO: 2019-09-10 dirty hotfix - if ("Classrooms".equals(endpoint)) { - apiRequestCallback.onSuccess(null); - return; - } - finishWithError(new AppError(TAG, 516, CODE_MAINTENANCE, response, throwable)); - return; - } - finishWithError(new AppError(TAG, 520, CODE_OTHER, response, throwable)); - } - }) - .build() - .enqueue(); - } - - private void synergiaRequest(String endpoint, String body, SynergiaRequestCallback synergiaRequestCallback) { - d(TAG, "Requesting "+SYNERGIA_URL+endpoint); - Request.builder() - .url(SYNERGIA_URL+endpoint) - .userAgent(synergiaUserAgent) - .setTextBody(body, MediaTypeUtils.APPLICATION_XML) - .callback(new TextCallbackHandler() { - @Override - public void onSuccess(String data, Response response) { - if ((data.contains("error") || data.contains("")) && !data.contains("Niepoprawny")) { - finishWithError(new AppError(TAG, 541, AppError.CODE_MAINTENANCE, response, data)); - return; - } - synergiaRequestCallback.onSuccess(Jsoup.parse(data, "", Parser.xmlParser())); - } - - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 556, CODE_OTHER, response, throwable)); - } - }) - .build() - .enqueue(); - } - - // CALLBACKS & INTERFACES - private interface AuthorizeCallback { - void onCsrfToken(String csrfToken); - void onAuthorizationCode(String code); - } - private interface LibrusLoginCallback { - void onLogin(String redirectUrl); - } - private interface AccessTokenCallback { - void onSuccess(String tokenType, String accessToken, String refreshToken, int expiresIn); - void onError(); - } - private interface SynergiaAccountsCallback { - void onSuccess(JsonObject data); - } - private interface SynergiaAccountCallback { - void onSuccess(JsonObject data); - } - private interface ApiRequestCallback { - void onSuccess(JsonObject data); - } - private interface SynergiaRequestCallback { - void onSuccess(Document data); - } - - private AuthorizeCallback authorizeCallback; - private LibrusLoginCallback librusLoginCallback; - private AccessTokenCallback accessTokenCallback; - private SynergiaAccountsCallback synergiaAccountsCallback; - private SynergiaAccountCallback synergiaAccountCallback; - - /* _____ _ _____ _ - | __ \ | | | __ \ | | - | | | | __ _| |_ __ _ | |__) |___ __ _ _ _ ___ ___| |_ ___ - | | | |/ _` | __/ _` | | _ // _ \/ _` | | | |/ _ \/ __| __/ __| - | |__| | (_| | || (_| | | | \ \ __/ (_| | |_| | __/\__ \ |_\__ \ - |_____/ \__,_|\__\__,_| |_| \_\___|\__, |\__,_|\___||___/\__|___/ - | | - |*/ - private void getMe() { - if (!fullSync) { - r("finish", "Me"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_account_info); - apiRequest("Me", data -> { - JsonObject me = data.get("Me").getAsJsonObject(); - me = me.get("Account").getAsJsonObject(); - //d("Got School: "+school.toString()); - try { - boolean premium = me.get("IsPremium").getAsBoolean(); - boolean premiumDemo = me.get("IsPremiumDemo").getAsBoolean(); - this.premium = premium || premiumDemo; - profile.putStudentData("isPremium", premium || premiumDemo); - r("finish", "Me"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 1316, CODE_OTHER, e, data)); - } - }); - } - - private Map> lessonRanges = new HashMap<>(); - private String schoolName = ""; - private void getSchools() { - if (!fullSync) { - try { - lessonRanges = app.gson.fromJson(profile.getStudentData("lessonRanges", "{}"), new TypeToken>>() { - }.getType()); - if (lessonRanges != null && lessonRanges.size() > 0) { - r("finish", "Schools"); - return; - } - } - catch (Exception e) { - e.printStackTrace(); - } - } - lessonRanges = new HashMap<>(); - callback.onActionStarted(R.string.sync_action_syncing_school_info); - apiRequest("Schools", data -> { - //d("Got School: "+school.toString()); - try { - JsonObject school = data.get("School").getAsJsonObject(); - int schoolId = school.get("Id").getAsInt(); - String schoolNameLong = school.get("Name").getAsString(); - StringBuilder schoolNameShort = new StringBuilder(); - for (String schoolNamePart: schoolNameLong.split(" ")) { - if (schoolNamePart.isEmpty()) - continue; - schoolNameShort.append(Character.toLowerCase(schoolNamePart.charAt(0))); - } - String schoolTown = school.get("Town").getAsString(); - schoolName = schoolId+schoolNameShort.toString()+"_"+schoolTown.toLowerCase(); - profile.putStudentData("schoolName", schoolName); - - lessonRanges.clear(); - int index = 0; - for (JsonElement lessonRangeEl: school.get("LessonsRange").getAsJsonArray()) { - JsonObject lr = lessonRangeEl.getAsJsonObject(); - JsonElement from = lr.get("From"); - JsonElement to = lr.get("To"); - if (from != null && to != null && !(from instanceof JsonNull) && !(to instanceof JsonNull)) { - lessonRanges.put(index, new Pair<>(Time.fromH_m(from.getAsString()), Time.fromH_m(to.getAsString()))); - } - index++; - } - profile.putStudentData("lessonRanges", app.gson.toJson(lessonRanges)); - r("finish", "Schools"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 1364, CODE_OTHER, e, data)); - } - }); - } - - private long teamClassId = -1; - private void getClasses() { - if (!fullSync) { - r("finish", "Classes"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_class); - apiRequest("Classes", data -> { - //d("Got Class: "+myClass.toString()); - try { - JsonObject myClass = data.get("Class").getAsJsonObject(); - String teamName = myClass.get("Number").getAsString() - + myClass.get("Symbol").getAsString(); - teamClassId = myClass.get("Id").getAsLong(); - teamList.add(new Team( - profileId, - teamClassId, - teamName, - 1, - schoolName+":"+teamName, - myClass.get("ClassTutor").getAsJsonObject().get("Id").getAsLong())); - JsonElement semester1Begin = myClass.get("BeginSchoolYear"); - JsonElement semester2Begin = myClass.get("EndFirstSemester"); - JsonElement yearEnd = myClass.get("EndSchoolYear"); - if (semester1Begin != null - && semester2Begin != null - && yearEnd != null - && !(semester1Begin instanceof JsonNull) - && !(semester2Begin instanceof JsonNull) - && !(yearEnd instanceof JsonNull)) { - profile.setDateSemester1Start(Date.fromY_m_d(semester1Begin.getAsString())); - profile.setDateSemester2Start(Date.fromY_m_d(semester2Begin.getAsString())); - profile.setDateYearEnd(Date.fromY_m_d(yearEnd.getAsString())); - } - JsonElement unit = myClass.get("Unit"); - if (unit != null && !(unit instanceof JsonNull)) { - unitId = unit.getAsJsonObject().get("Id").getAsLong(); - profile.putStudentData("unitId", unitId); - } - r("finish", "Classes"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 1411, CODE_OTHER, e, data)); - } - }); - } - - private void getVirtualClasses() { - if (!fullSync) { - r("finish", "VirtualClasses"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_teams); - apiRequest("VirtualClasses", data -> { - if (data == null) { - r("finish", "VirtualClasses"); - return; - } - try { - JsonArray classes = data.get("VirtualClasses").getAsJsonArray(); - for (JsonElement myClassEl: classes) { - JsonObject myClass = myClassEl.getAsJsonObject(); - String teamName = myClass.get("Name").getAsString(); - long teamId = myClass.get("Id").getAsLong(); - long teacherId = -1; - JsonElement el; - if ((el = myClass.get("Teacher")) != null) { - teacherId = el.getAsJsonObject().get("Id").getAsLong(); - } - teamList.add(new Team( - profileId, - teamId, - teamName, - 2, - schoolName + ":" + teamName, - teacherId)); - } - r("finish", "VirtualClasses"); - } catch (Exception e) { - finishWithError(new AppError(TAG, 1449, CODE_OTHER, e, data)); - } - }); - } - - private void getUnits() { - if (!fullSync) { - enableStandardGrades = profile.getStudentData("enableStandardGrades", true); - enablePointGrades = profile.getStudentData("enablePointGrades", false); - enableDescriptiveGrades = profile.getStudentData("enableDescriptiveGrades", false); - enableTextGrades = profile.getStudentData("enableTextGrades", false); - enableBehaviourGrades = profile.getStudentData("enableBehaviourGrades", true); - startPointsSemester1 = profile.getStudentData("startPointsSemester1", 0); - startPointsSemester2 = profile.getStudentData("startPointsSemester2", 0); - r("finish", "Units"); - return; - } - d(TAG, "Grades settings: "+enableStandardGrades+", "+enablePointGrades+", "+enableDescriptiveGrades); - callback.onActionStarted(R.string.sync_action_syncing_school_info); - apiRequest("Units", data -> { - if (data == null) { - r("finish", "Units"); - return; - } - JsonArray units = data.getAsJsonArray("Units"); - try { - long unitId = profile.getStudentData("unitId", (long)-1); - enableStandardGrades = true; // once a week or two (during a full sync) force getting the standard grade list. If there aren't any, disable it again later. - enableBehaviourGrades = true; - enableTextGrades = true; // TODO: 2019-05-13 if "DescriptiveGradesEnabled" are also TextGrades - profile.putStudentData("enableStandardGrades", true); - profile.putStudentData("enableBehaviourGrades", true); - profile.putStudentData("enableTextGrades", true); - for (JsonElement unitEl: units) { - JsonObject unit = unitEl.getAsJsonObject(); - - if (unit.get("Id").getAsLong() == unitId) { - JsonObject gradesSettings = unit.getAsJsonObject("GradesSettings"); - enablePointGrades = gradesSettings.get("PointGradesEnabled").getAsBoolean(); - enableDescriptiveGrades = gradesSettings.get("DescriptiveGradesEnabled").getAsBoolean(); - - JsonObject behaviourGradesSettings = unit.getAsJsonObject("BehaviourGradesSettings"); - JsonObject startPoints = behaviourGradesSettings.getAsJsonObject("StartPoints"); - - startPointsSemester1 = startPoints.get("Semester1").getAsInt(); - JsonElement startPointsSemester2El; - if ((startPointsSemester2El = startPoints.get("Semester2")) != null) { - startPointsSemester2 = startPointsSemester2El.getAsInt(); - } - else { - startPointsSemester2 = startPointsSemester1; - } - - profile.putStudentData("enablePointGrades", enablePointGrades); - profile.putStudentData("enableDescriptiveGrades", enableDescriptiveGrades); - profile.putStudentData("startPointsSemester1", startPointsSemester1); - profile.putStudentData("startPointsSemester2", startPointsSemester2); - break; - } - } - d(TAG, "Grades settings: "+enableStandardGrades+", "+enablePointGrades+", "+enableDescriptiveGrades); - r("finish", "Units"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 1506, CODE_OTHER, e, data)); - } - }); - } - - private boolean teacherListChanged = false; - private void getUsers() { - if (!fullSync) { - r("finish", "Users"); - teacherList = app.db.teacherDao().getAllNow(profileId); - teacherListChanged = false; - return; - } - callback.onActionStarted(R.string.sync_action_syncing_users); - apiRequest("Users", data -> { - if (data == null) { - r("finish", "Users"); - return; - } - JsonArray users = data.get("Users").getAsJsonArray(); - //d("Got Users: "+users.toString()); - try { - teacherListChanged = true; - for (JsonElement userEl : users) { - JsonObject user = userEl.getAsJsonObject(); - JsonElement firstName = user.get("FirstName"); - JsonElement lastName = user.get("LastName"); - teacherList.add(new Teacher( - profileId, - user.get("Id").getAsLong(), - firstName instanceof JsonNull ? "" : firstName.getAsString(), - lastName instanceof JsonNull ? "" : lastName.getAsString() - )); - } - r("finish", "Users"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 1544, CODE_OTHER, e, data)); - } - }); - } - - private void getSubjects() { - if (!fullSync) { - r("finish", "Subjects"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_subjects); - apiRequest("Subjects", data -> { - if (data == null) { - r("finish", "Subjects"); - return; - } - JsonArray subjects = data.get("Subjects").getAsJsonArray(); - //d("Got Subjects: "+subjects.toString()); - try { - for (JsonElement subjectEl : subjects) { - JsonObject subject = subjectEl.getAsJsonObject(); - JsonElement longName = subject.get("Name"); - JsonElement shortName = subject.get("Short"); - subjectList.add(new Subject( - profileId, - subject.get("Id").getAsLong(), - longName instanceof JsonNull ? "" : longName.getAsString(), - shortName instanceof JsonNull ? "" : shortName.getAsString() - )); - } - subjectList.add(new Subject( - profileId, - 1, - "Zachowanie", - "zach" - )); - r("finish", "Subjects"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 1588, CODE_OTHER, e, data)); - } - }); - } - - private SparseArray classrooms = new SparseArray<>(); - private void getClassrooms() { - //if (!fullSync) - // r("finish", "Classrooms"); - callback.onActionStarted(R.string.sync_action_syncing_classrooms); - apiRequest("Classrooms", data -> { - if (data == null) { - r("finish", "Classrooms"); - return; - } - if (data.get("Classrooms") == null) { - r("finish", "Classrooms"); - return; - } - JsonArray jClassrooms = data.get("Classrooms").getAsJsonArray(); - //d("Got Classrooms: "+jClassrooms.toString()); - classrooms.clear(); - try { - for (JsonElement classroomEl : jClassrooms) { - JsonObject classroom = classroomEl.getAsJsonObject(); - classrooms.put(classroom.get("Id").getAsInt(), classroom.get("Name").getAsString()); - } - r("finish", "Classrooms"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 1617, CODE_OTHER, e, data)); - } - }); - } - - private void getTimetables() { - callback.onActionStarted(R.string.sync_action_syncing_timetable); - Date weekStart = Week.getWeekStart(); - if (Date.getToday().getWeekDay() > 4) { - weekStart.stepForward(0, 0, 7); - } - apiRequest("Timetables?weekStart="+weekStart.getStringY_m_d(), data -> { - if (data == null) { - r("finish", "Timetables"); - return; - } - JsonObject timetables = data.get("Timetable").getAsJsonObject(); - try { - for (Map.Entry dayEl: timetables.entrySet()) { - JsonArray day = dayEl.getValue().getAsJsonArray(); - Date lessonDate = Date.fromY_m_d(dayEl.getKey()); - for (JsonElement lessonGroupEl: day) { - if ((lessonGroupEl instanceof JsonArray && ((JsonArray) lessonGroupEl).size() == 0) || lessonGroupEl instanceof JsonNull || lessonGroupEl == null) { - continue; - } - JsonArray lessonGroup = lessonGroupEl.getAsJsonArray(); - for (JsonElement lessonEl: lessonGroup) { - if ((lessonEl instanceof JsonArray && ((JsonArray) lessonEl).size() == 0) || lessonEl instanceof JsonNull || lessonEl == null) { - continue; - } - JsonObject lesson = lessonEl.getAsJsonObject(); - - boolean substitution = false; - boolean cancelled = false; - JsonElement isSubstitutionClass; - if ((isSubstitutionClass = lesson.get("IsSubstitutionClass")) != null) { - substitution = isSubstitutionClass.getAsBoolean(); - } - JsonElement isCanceled; - if ((isCanceled = lesson.get("IsCanceled")) != null) { - cancelled = isCanceled.getAsBoolean(); - } - - if (substitution && cancelled) { - // the lesson is probably shifted. Skip this one - continue; - } - - Time startTime = null; - Time endTime = null; - try { - startTime = Time.fromH_m(lesson.get(substitution && !cancelled ? "OrgHourFrom" : "HourFrom").getAsString()); - endTime = Time.fromH_m(lesson.get(substitution && !cancelled ? "OrgHourTo" : "HourTo").getAsString()); - } - catch (Exception ignore) { - try { - JsonElement lessonNo; - if (!((lessonNo = lesson.get("LessonNo")) instanceof JsonNull)) { - Pair timePair = lessonRanges.get(strToInt(lessonNo.getAsString())); - if (timePair != null) { - startTime = timePair.first; - endTime = timePair.second; - } - } - } - catch (Exception ignore2) { } - } - - - Lesson lessonObject = new Lesson( - profileId, - lesson.get("DayNo").getAsInt() - 1, - startTime, - endTime - ); - - JsonElement subject; - if ((subject = lesson.get(substitution && !cancelled ? "OrgSubject" : "Subject")) != null) { - lessonObject.subjectId = subject.getAsJsonObject().get("Id").getAsLong(); - } - - JsonElement teacher; - if ((teacher = lesson.get(substitution && !cancelled ? "OrgTeacher" : "Teacher")) != null) { - lessonObject.teacherId = teacher.getAsJsonObject().get("Id").getAsLong(); - } - - JsonElement myClass; - if ((myClass = lesson.get("Class")) != null) { - lessonObject.teamId = myClass.getAsJsonObject().get("Id").getAsLong(); - } - if (myClass == null && (myClass = lesson.get("VirtualClass")) != null) { - lessonObject.teamId = myClass.getAsJsonObject().get("Id").getAsLong(); - } - - JsonElement classroom; - JsonElement substitutionClassroom; - if (substitution && !cancelled) { - classroom = lesson.get("OrgClassroom"); - substitutionClassroom = lesson.get("Classroom"); - - if (classroom != null) - lessonObject.classroomName = classrooms.get(classroom.getAsJsonObject().get("Id").getAsInt()); - - if (substitutionClassroom != null) { - for (LessonChange lessonChange : lessonChangeList) { - if(lessonChange.lessonDate.compareTo(lessonDate) == 0) { - lessonChange.classroomName - = classrooms.get(substitutionClassroom.getAsJsonObject().get("Id").getAsInt()); - break; - } - } - } - } else { - classroom = lesson.get("Classroom"); - if (classroom != null) - lessonObject.classroomName = classrooms.get(classroom.getAsJsonObject().get("Id").getAsInt()); - } - - lessonList.add(lessonObject); - } - } - } - r("finish", "Timetables"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 1704, CODE_OTHER, e, data)); - } - }); - } - - private void getSubstitutions() { - callback.onActionStarted(R.string.sync_action_syncing_timetable_changes); - apiRequest("Calendars/Substitutions", data -> { - if (data == null) { - r("finish", "Substitutions"); - return; - } - - JsonArray substitutions = data.get("Substitutions").getAsJsonArray(); - try { - List ignoreList = new ArrayList<>(); - for (JsonElement substitutionEl : substitutions) { - JsonObject substitution = substitutionEl.getAsJsonObject(); - - String str_date = substitution.get("OrgDate").getAsString(); - Date lessonDate = Date.fromY_m_d(str_date); - - Time startTime = Time.getNow(); - JsonElement lessonNo; - if (!((lessonNo = substitution.get("OrgLessonNo")) instanceof JsonNull)) { - Pair timePair = lessonRanges.get(lessonNo.getAsInt()); - if (timePair != null) - startTime = timePair.first; - } - - JsonElement isShifted; - JsonElement isCancelled; - if ((isShifted = substitution.get("IsShifted")) != null && isShifted.getAsBoolean()) { - // a lesson is shifted - // add a TYPE_CANCELLED for the source lesson and a TYPE_CHANGE for the destination lesson - - // source lesson: cancel - LessonChange lessonCancelled = new LessonChange(profileId, lessonDate, startTime, startTime.clone().stepForward(0, 45, 0)); - lessonCancelled.type = TYPE_CANCELLED; - lessonChangeList.add(lessonCancelled); - metadataList.add(new Metadata(profileId, Metadata.TYPE_LESSON_CHANGE, lessonCancelled.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - - // target lesson: change - startTime = Time.getNow(); - if (!((lessonNo = substitution.get("LessonNo")) instanceof JsonNull)) { - Pair timePair = lessonRanges.get(lessonNo.getAsInt()); - if (timePair != null) - startTime = timePair.first; - } - - LessonChange lessonChanged = new LessonChange(profileId, lessonDate, startTime, startTime.clone().stepForward(0, 45, 0)); - lessonChanged.type = TYPE_CHANGE; - JsonElement subject; - if ((subject = substitution.get("Subject")) != null) { - lessonChanged.subjectId = subject.getAsJsonObject().get("Id").getAsLong(); - } - JsonElement teacher; - if ((teacher = substitution.get("Teacher")) != null) { - lessonChanged.teacherId = teacher.getAsJsonObject().get("Id").getAsLong(); - } - JsonElement myClass; - if ((myClass = substitution.get("Class")) != null) { - lessonChanged.teamId = myClass.getAsJsonObject().get("Id").getAsLong(); - } - if (myClass == null && (myClass = substitution.get("VirtualClass")) != null) { - lessonChanged.teamId = myClass.getAsJsonObject().get("Id").getAsLong(); - } - lessonChangeList.add(lessonChanged); - metadataList.add(new Metadata(profileId, Metadata.TYPE_LESSON_CHANGE, lessonChanged.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - - // ignore the target lesson in further array elements - it's already changed - ignoreList.add(lessonChanged.lessonDate.combineWith(lessonChanged.startTime)); - } - else if ((isCancelled = substitution.get("IsCancelled")) != null && isCancelled.getAsBoolean()) { - LessonChange lessonChange = new LessonChange(profileId, lessonDate, startTime, startTime.clone().stepForward(0, 45, 0)); - // if it's actually a lesson shift - ignore the target lesson cancellation - if (ignoreList.size() > 0 && ignoreList.contains(lessonChange.lessonDate.combineWith(lessonChange.startTime))) - continue; - lessonChange.type = TYPE_CANCELLED; - lessonChangeList.add(lessonChange); - metadataList.add(new Metadata(profileId, Metadata.TYPE_LESSON_CHANGE, lessonChange.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - } - else { - LessonChange lessonChange = new LessonChange(profileId, lessonDate, startTime, startTime.clone().stepForward(0, 45, 0)); - - lessonChange.type = TYPE_CHANGE; - - JsonElement subject; - if ((subject = substitution.get("Subject")) != null) { - lessonChange.subjectId = subject.getAsJsonObject().get("Id").getAsLong(); - } - JsonElement teacher; - if ((teacher = substitution.get("Teacher")) != null) { - lessonChange.teacherId = teacher.getAsJsonObject().get("Id").getAsLong(); - } - - JsonElement myClass; - if ((myClass = substitution.get("Class")) != null) { - lessonChange.teamId = myClass.getAsJsonObject().get("Id").getAsLong(); - } - if (myClass == null && (myClass = substitution.get("VirtualClass")) != null) { - lessonChange.teamId = myClass.getAsJsonObject().get("Id").getAsLong(); - } - - lessonChangeList.add(lessonChange); - metadataList.add(new Metadata(profileId, Metadata.TYPE_LESSON_CHANGE, lessonChange.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - } - - } - r("finish", "Substitutions"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 1822, CODE_OTHER, e, data)); - } - }); - } - - private SparseIntArray colors = new SparseIntArray(); - private void getColors() { - colors.put( 1, 0xFFF0E68C); - colors.put( 2, 0xFF87CEFA); - colors.put( 3, 0xFFB0C4DE); - colors.put( 4, 0xFFF0F8FF); - colors.put( 5, 0xFFF0FFFF); - colors.put( 6, 0xFFF5F5DC); - colors.put( 7, 0xFFFFEBCD); - colors.put( 8, 0xFFFFF8DC); - colors.put( 9, 0xFFA9A9A9); - colors.put(10, 0xFFBDB76B); - colors.put(11, 0xFF8FBC8F); - colors.put(12, 0xFFDCDCDC); - colors.put(13, 0xFFDAA520); - colors.put(14, 0xFFE6E6FA); - colors.put(15, 0xFFFFA07A); - colors.put(16, 0xFF32CD32); - colors.put(17, 0xFF66CDAA); - colors.put(18, 0xFF66CDAA); - colors.put(19, 0xFFC0C0C0); - colors.put(20, 0xFFD2B48C); - colors.put(21, 0xFF3333FF); - colors.put(22, 0xFF7B68EE); - colors.put(23, 0xFFBA55D3); - colors.put(24, 0xFFFFB6C1); - colors.put(25, 0xFFFF1493); - colors.put(26, 0xFFDC143C); - colors.put(27, 0xFFFF0000); - colors.put(28, 0xFFFF8C00); - colors.put(29, 0xFFFFD700); - colors.put(30, 0xFFADFF2F); - colors.put(31, 0xFF7CFC00); - r("finish", "Colors"); - /* - apiRequest("Colors", data -> { - JsonArray jColors = data.get("Colors").getAsJsonArray(); - d("Got Colors: "+jColors.toString()); - colors.clear(); - try { - for (JsonElement colorEl : jColors) { - JsonObject color = colorEl.getAsJsonObject(); - colors.put(color.get("Id").getAsInt(), Color.parseColor("#"+color.get("RGB").getAsString())); - } - } - catch (Exception e) { - e.printStackTrace(); - } - getGrades(); - });*/ - } - - private boolean gradeCategoryListChanged = false; - private void getSavedGradeCategories() { - gradeCategoryList = app.db.gradeCategoryDao().getAllNow(profileId); - gradeCategoryListChanged = false; - r("finish", "SavedGradeCategories"); - } - - private void saveGradeCategories() { - r("finish", "SaveGradeCategories"); - } - - private void getGradesCategories() { - if (!fullSync && false) { - // cancel every not-full sync; no need to download categories again - // every full sync it'll be enabled to make sure there are no grades - by getUnits - r("finish", "GradesCategories"); - return; - } - // not a full sync. Will get all grade categories. Clear the current list. - //gradeCategoryList.clear(); - - callback.onActionStarted(R.string.sync_action_syncing_grade_categories); - apiRequest("Grades/Categories", data -> { - if (data == null) { - r("finish", "GradesCategories"); - return; - } - JsonArray categories = data.get("Categories").getAsJsonArray(); - enableStandardGrades = categories.size() > 0; - profile.putStudentData("enableStandardGrades", enableStandardGrades); - if (!enableStandardGrades) { - r("finish", "GradesCategories"); - return; - } - gradeCategoryListChanged = true; - //d("Got Grades/Categories: "+categories.toString()); - try { - for (JsonElement categoryEl : categories) { - JsonObject category = categoryEl.getAsJsonObject(); - JsonElement name = category.get("Name"); - JsonElement weight = category.get("Weight"); - JsonElement color = category.get("Color"); - JsonElement countToTheAverage = category.get("CountToTheAverage"); - int colorInt = Color.BLUE; - if (!(color instanceof JsonNull) && color != null) { - colorInt = colors.get(color.getAsJsonObject().get("Id").getAsInt()); - } - boolean countToTheAverageBool = !(countToTheAverage instanceof JsonNull) && countToTheAverage != null && countToTheAverage.getAsBoolean(); - int weightInt = weight instanceof JsonNull || weight == null || !countToTheAverageBool ? 0 : weight.getAsInt(); - int categoryId = category.get("Id").getAsInt(); - gradeCategoryList.add(new GradeCategory( - profileId, - categoryId, - weightInt, - colorInt, - name instanceof JsonNull || name == null ? "" : name.getAsString() - )); - } - r("finish", "GradesCategories"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 1954, CODE_OTHER, e, data)); - } - }); - } - - private void getGradesComments() { - callback.onActionStarted(R.string.sync_action_syncing_grade_comments); - apiRequest("Grades/Comments", data -> { - if (data == null) { - r("finish", "GradesComments"); - return; - } - - JsonArray comments = data.get("Comments").getAsJsonArray(); - for (JsonElement commentEl : comments) { - JsonObject comment = commentEl.getAsJsonObject(); - long gradeId = comment.get("Grade").getAsJsonObject().get("Id").getAsLong(); - String text = comment.get("Text").getAsString(); - - for (Grade grade : gradeList) { - if (grade.id == gradeId) { - grade.description = text; - break; - } - } - } - - r("finish", "GradesComments"); - }); - } - - private void getPointGradesCategories() { - if (!fullSync || !enablePointGrades) { - // cancel every not-full sync; no need to download categories again - // or - // if it's a full sync, point grades may have already been disabled in getUnits - r("finish", "PointGradesCategories"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_point_grade_categories); - apiRequest("PointGrades/Categories", data -> { - if (data == null) { - r("finish", "PointGradesCategories"); - return; - } - JsonArray categories = data.get("Categories").getAsJsonArray(); - enablePointGrades = categories.size() > 0; - profile.putStudentData("enablePointGrades", enablePointGrades); - if (!enablePointGrades) { - r("finish", "PointGradesCategories"); - return; - } - gradeCategoryListChanged = true; - //d("Got Grades/Categories: "+categories.toString()); - for (JsonElement categoryEl : categories) { - JsonObject category = categoryEl.getAsJsonObject(); - JsonElement name = category.get("Name"); - JsonElement weight = category.get("Weight"); - JsonElement color = category.get("Color"); - JsonElement countToTheAverage = category.get("CountToTheAverage"); - JsonElement valueFrom = category.get("ValueFrom"); - JsonElement valueTo = category.get("ValueTo"); - int colorInt = Color.BLUE; - if (!(color instanceof JsonNull) && color != null) { - colorInt = colors.get(color.getAsJsonObject().get("Id").getAsInt()); - } - boolean countToTheAverageBool = !(countToTheAverage instanceof JsonNull) && countToTheAverage != null && countToTheAverage.getAsBoolean(); - int weightInt = weight instanceof JsonNull || weight == null || !countToTheAverageBool ? 0 : weight.getAsInt(); - int categoryId = category.get("Id").getAsInt(); - float valueFromFloat = valueFrom.getAsFloat(); - float valueToFloat = valueTo.getAsFloat(); - gradeCategoryList.add( - new GradeCategory( - profileId, - categoryId, - weightInt, - colorInt, - name instanceof JsonNull || name == null ? "" : name.getAsString() - ).setValueRange(valueFromFloat, valueToFloat) - ); - } - r("finish", "PointGradesCategories"); - }); - } - - private void getDescriptiveGradesSkills() { - if (!fullSync || !enableDescriptiveGrades) { - // cancel every not-full sync; no need to download categories again - // or - // if it's a full sync, descriptive grades may have already been disabled in getUnits - r("finish", "DescriptiveGradesCategories"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_descriptive_grade_categories); - apiRequest("DescriptiveTextGrades/Skills", data -> { - if (data == null) { - r("finish", "DescriptiveGradesCategories"); - return; - } - JsonArray categories = data.get("Skills").getAsJsonArray(); - enableDescriptiveGrades = categories.size() > 0; - profile.putStudentData("enableDescriptiveGrades", enableDescriptiveGrades); - if (!enableDescriptiveGrades) { - r("finish", "DescriptiveGradesCategories"); - return; - } - gradeCategoryListChanged = true; - //d("Got Grades/Categories: "+categories.toString()); - for (JsonElement categoryEl : categories) { - JsonObject category = categoryEl.getAsJsonObject(); - JsonElement name = category.get("Name"); - JsonElement color = category.get("Color"); - int colorInt = Color.BLUE; - if (!(color instanceof JsonNull) && color != null) { - colorInt = colors.get(color.getAsJsonObject().get("Id").getAsInt()); - } - int weightInt = -1; - int categoryId = category.get("Id").getAsInt(); - gradeCategoryList.add(new GradeCategory( - profileId, - categoryId, - weightInt, - colorInt, - name instanceof JsonNull || name == null ? "" : name.getAsString() - )); - } - r("finish", "DescriptiveGradesCategories"); - }); - } - - private void getTextGradesCategories() { - if (!fullSync || !enableTextGrades) { - // cancel every not-full sync; no need to download categories again - // or - // if it's a full sync, text grades may have already been disabled in getUnits - r("finish", "TextGradesCategories"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_descriptive_grade_categories); - apiRequest("TextGrades/Categories", data -> { - if (data == null) { - r("finish", "TextGradesCategories"); - return; - } - JsonArray categories = data.get("Categories").getAsJsonArray(); - enableTextGrades = categories.size() > 0; - profile.putStudentData("enableTextGrades", enableTextGrades); - if (!enableTextGrades) { - r("finish", "TextGradesCategories"); - return; - } - gradeCategoryListChanged = true; - //d("Got Grades/Categories: "+categories.toString()); - for (JsonElement categoryEl : categories) { - JsonObject category = categoryEl.getAsJsonObject(); - JsonElement name = category.get("Name"); - JsonElement color = category.get("Color"); - int colorInt = Color.BLUE; - if (!(color instanceof JsonNull) && color != null) { - colorInt = colors.get(color.getAsJsonObject().get("Id").getAsInt()); - } - int weightInt = -1; - int categoryId = category.get("Id").getAsInt(); - gradeCategoryList.add(new GradeCategory( - profileId, - categoryId, - weightInt, - colorInt, - name instanceof JsonNull || name == null ? "" : name.getAsString() - )); - } - r("finish", "TextGradesCategories"); - }); - } - - private void getBehaviourGradesCategories() { - if (!fullSync || !enableBehaviourGrades) { - // cancel every not-full sync; no need to download categories again - // or - // if it's a full sync, descriptive grades may have already been disabled in getUnits - r("finish", "BehaviourGradesCategories"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_behaviour_grade_categories); - apiRequest("BehaviourGrades/Points/Categories", data -> { - if (data == null) { - r("finish", "BehaviourGradesCategories"); - return; - } - JsonArray categories = data.get("Categories").getAsJsonArray(); - enableBehaviourGrades = categories.size() > 0; - profile.putStudentData("enableBehaviourGrades", enableBehaviourGrades); - if (!enableBehaviourGrades) { - r("finish", "BehaviourGradesCategories"); - return; - } - gradeCategoryListChanged = true; - //d("Got Grades/Categories: "+categories.toString()); - for (JsonElement categoryEl : categories) { - JsonObject category = categoryEl.getAsJsonObject(); - JsonElement name = category.get("Name"); - JsonElement valueFrom = category.get("ValueFrom"); - JsonElement valueTo = category.get("ValueTo"); - int colorInt = Color.BLUE; - int categoryId = category.get("Id").getAsInt(); - float valueFromFloat = valueFrom.getAsFloat(); - float valueToFloat = valueTo.getAsFloat(); - gradeCategoryList.add( - new GradeCategory( - profileId, - categoryId, - -1, - colorInt, - name instanceof JsonNull || name == null ? "" : name.getAsString() - ).setValueRange(valueFromFloat, valueToFloat) - ); - } - r("finish", "BehaviourGradesCategories"); - }); - } - - private void getGrades() { - d(TAG, "Grades settings: "+enableStandardGrades+", "+enablePointGrades+", "+enableDescriptiveGrades); - if (!enableStandardGrades && false) { - // cancel only if grades have been disabled before - // TODO do not cancel. this does not show any grades until a full sync happens. wtf - // in KOTLIN api, maybe this will be forced when user synchronises this feature exclusively - r("finish", "Grades"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_grades); - apiRequest("Grades", data -> { - if (data == null) { - r("finish", "Grades"); - return; - } - JsonArray grades = data.get("Grades").getAsJsonArray(); - enableStandardGrades = grades.size() > 0; - profile.putStudentData("enableStandardGrades", enableStandardGrades); - if (!enableStandardGrades) { - r("finish", "Grades"); - return; - } - //d("Got Grades: "+grades.toString()); - for (JsonElement gradeEl : grades) { - JsonObject grade = gradeEl.getAsJsonObject(); - long id = grade.get("Id").getAsLong(); - long teacherId = grade.get("AddedBy").getAsJsonObject().get("Id").getAsLong(); - int semester = grade.get("Semester").getAsInt(); - long categoryId = grade.get("Category").getAsJsonObject().get("Id").getAsLong(); - long subjectId = grade.get("Subject").getAsJsonObject().get("Id").getAsLong(); - String name = grade.get("Grade").getAsString(); - float value = getGradeValue(name); - - String str_date = grade.get("AddDate").getAsString(); - long addedDate = Date.fromIso(str_date); - - float weight = 0.0f; - String category = ""; - int color = -1; - GradeCategory gradeCategory = GradeCategory.search(gradeCategoryList, categoryId); - if (gradeCategory != null) { - weight = gradeCategory.weight; - category = gradeCategory.text; - color = gradeCategory.color; - } - - if (name.equals("-") || name.equals("+") || name.equalsIgnoreCase("np") || name.equalsIgnoreCase("bz")) { - // fix for + and - grades that lower the average - weight = 0; - } - - Grade gradeObject = new Grade( - profileId, - id, - category, - color, - "", - name, - value, - weight, - semester, - teacherId, - subjectId - ); - - if (grade.get("IsConstituent").getAsBoolean()) { - // normal grade - gradeObject.type = TYPE_NORMAL; - } - if (grade.get("IsSemester").getAsBoolean()) { - // semester final - gradeObject.type = (gradeObject.semester == 1 ? TYPE_SEMESTER1_FINAL : TYPE_SEMESTER2_FINAL); - } - else if (grade.get("IsSemesterProposition").getAsBoolean()) { - // semester proposed - gradeObject.type = (gradeObject.semester == 1 ? TYPE_SEMESTER1_PROPOSED : TYPE_SEMESTER2_PROPOSED); - } - else if (grade.get("IsFinal").getAsBoolean()) { - // year final - gradeObject.type = TYPE_YEAR_FINAL; - } - else if (grade.get("IsFinalProposition").getAsBoolean()) { - // year final - gradeObject.type = TYPE_YEAR_PROPOSED; - } - - JsonElement historyEl = grade.get("Improvement"); - if (historyEl != null) { - JsonObject history = historyEl.getAsJsonObject(); - long historicalId = history.get("Id").getAsLong(); - for (Grade historicalGrade: gradeList) { - if (historicalGrade.id != historicalId) - continue; - // historicalGrade - historicalGrade.parentId = gradeObject.id; - if (historicalGrade.name.equals("nb")) { - historicalGrade.weight = 0; - } - break; - } - gradeObject.isImprovement = true; - } - - /*if (RegisterGradeCategory.getById(app.register, registerGrade.categoryId, -1) == null) { - getGradesCategories = true; - }*/ - - gradeList.add(gradeObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_GRADE, gradeObject.id, profile.getEmpty(), profile.getEmpty(), addedDate)); - } - r("finish", "Grades"); - }); - } - - private void getPointGrades() { - d(TAG, "Grades settings: "+enableStandardGrades+", "+enablePointGrades+", "+enableDescriptiveGrades); - if (!enablePointGrades) { - // cancel only if grades have been disabled before - r("finish", "PointGrades"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_point_grades); - apiRequest("PointGrades", data -> { - if (data == null) { - r("finish", "PointGrades"); - return; - } - JsonArray grades = data.get("Grades").getAsJsonArray(); - enablePointGrades = grades.size() > 0; - profile.putStudentData("enablePointGrades", enablePointGrades); - if (!enablePointGrades) { - r("finish", "PointGrades"); - return; - } - //d("Got Grades: "+grades.toString()); - for (JsonElement gradeEl : grades) { - JsonObject grade = gradeEl.getAsJsonObject(); - long id = grade.get("Id").getAsLong(); - long teacherId = grade.get("AddedBy").getAsJsonObject().get("Id").getAsLong(); - int semester = grade.get("Semester").getAsInt(); - long categoryId = grade.get("Category").getAsJsonObject().get("Id").getAsLong(); - long subjectId = grade.get("Subject").getAsJsonObject().get("Id").getAsLong(); - String name = grade.get("Grade").getAsString(); - float originalValue = grade.get("GradeValue").getAsFloat(); - - String str_date = grade.get("AddDate").getAsString(); - long addedDate = Date.fromIso(str_date); - - float weight = 0.0f; - String category = ""; - int color = -1; - float value = 0.0f; - float maxPoints = 0.0f; - GradeCategory gradeCategory = GradeCategory.search(gradeCategoryList, categoryId); - if (gradeCategory != null) { - weight = gradeCategory.weight; - category = gradeCategory.text; - color = gradeCategory.color; - maxPoints = gradeCategory.valueTo; - value = originalValue; - } - - Grade gradeObject = new Grade( - profileId, - id, - category, - color, - "", - name, - value, - weight, - semester, - teacherId, - subjectId - ); - gradeObject.type = Grade.TYPE_POINT; - gradeObject.valueMax = maxPoints; - - gradeList.add(gradeObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_GRADE, gradeObject.id, profile.getEmpty(), profile.getEmpty(), addedDate)); - } - r("finish", "PointGrades"); - }); - } - - private void getDescriptiveGrades() { - d(TAG, "Grades settings: "+enableStandardGrades+", "+enablePointGrades+", "+enableDescriptiveGrades); - if (!enableDescriptiveGrades && !enableTextGrades) { - // cancel only if grades have been disabled before - r("finish", "DescriptiveGrades"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_descriptive_grades); - apiRequest("BaseTextGrades", data -> { - if (data == null) { - r("finish", "DescriptiveGrades"); - return; - } - JsonArray grades = data.get("Grades").getAsJsonArray(); - int descriptiveGradesCount = 0; - int textGradesCount = 0; - //d("Got Grades: "+grades.toString()); - for (JsonElement gradeEl : grades) { - JsonObject grade = gradeEl.getAsJsonObject(); - long id = grade.get("Id").getAsLong(); - long teacherId = grade.get("AddedBy").getAsJsonObject().get("Id").getAsLong(); - int semester = grade.get("Semester").getAsInt(); - long subjectId = grade.get("Subject").getAsJsonObject().get("Id").getAsLong(); - String description = grade.get("Grade").getAsString(); - - long categoryId = -1; - JsonElement categoryEl = grade.get("Category"); - JsonElement skillEl = grade.get("Skill"); - if (categoryEl != null) { - categoryId = categoryEl.getAsJsonObject().get("Id").getAsLong(); - textGradesCount++; - } - if (skillEl != null) { - categoryId = skillEl.getAsJsonObject().get("Id").getAsLong(); - descriptiveGradesCount++; - } - - String str_date = grade.get("AddDate").getAsString(); - long addedDate = Date.fromIso(str_date); - - String category = ""; - int color = -1; - GradeCategory gradeCategory = GradeCategory.search(gradeCategoryList, categoryId); - if (gradeCategory != null) { - category = gradeCategory.text; - color = gradeCategory.color; - } - - Grade gradeObject = new Grade( - profileId, - id, - category, - color, - description, - " ", - 0.0f, - 0, - semester, - teacherId, - subjectId - ); - gradeObject.type = Grade.TYPE_DESCRIPTIVE; - if (categoryEl != null) { - gradeObject.type = Grade.TYPE_TEXT; - } - if (skillEl != null) { - gradeObject.type = Grade.TYPE_DESCRIPTIVE; - } - - gradeList.add(gradeObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_GRADE, gradeObject.id, profile.getEmpty(), profile.getEmpty(), addedDate)); - } - enableDescriptiveGrades = descriptiveGradesCount > 0; - enableTextGrades = textGradesCount > 0; - profile.putStudentData("enableDescriptiveGrades", enableDescriptiveGrades); - profile.putStudentData("enableTextGrades", enableTextGrades); - r("finish", "DescriptiveGrades"); - }); - } - - private void getTextGrades() { - callback.onActionStarted(R.string.sync_action_syncing_descriptive_grades); - apiRequest("DescriptiveGrades", data -> { - if (data == null) { - r("finish", "TextGrades"); - return; - } - JsonArray grades = data.get("Grades").getAsJsonArray(); - //d("Got Grades: "+grades.toString()); - for (JsonElement gradeEl : grades) { - JsonObject grade = gradeEl.getAsJsonObject(); - long id = grade.get("Id").getAsLong(); - long teacherId = grade.get("AddedBy").getAsJsonObject().get("Id").getAsLong(); - int semester = grade.get("Semester").getAsInt(); - long subjectId = grade.get("Subject").getAsJsonObject().get("Id").getAsLong(); - JsonElement map = grade.get("Map"); - JsonElement realGrade = grade.get("RealGradeValue"); - String description = ""; - if (map != null) { - description = map.getAsString(); - } - else if (realGrade != null) { - description = realGrade.getAsString(); - } - - long categoryId = -1; - JsonElement skillEl = grade.get("Skill"); - if (skillEl != null) { - categoryId = skillEl.getAsJsonObject().get("Id").getAsLong(); - } - - String str_date = grade.get("AddDate").getAsString(); - long addedDate = Date.fromIso(str_date); - - String category = ""; - int color = -1; - GradeCategory gradeCategory = GradeCategory.search(gradeCategoryList, categoryId); - if (gradeCategory != null) { - category = gradeCategory.text; - color = gradeCategory.color; - } - - Grade gradeObject = new Grade( - profileId, - id, - category, - color, - "", - description, - 0.0f, - 0, - semester, - teacherId, - subjectId - ); - gradeObject.type = Grade.TYPE_DESCRIPTIVE; - - gradeList.add(gradeObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_GRADE, gradeObject.id, profile.getEmpty(), profile.getEmpty(), addedDate)); - } - r("finish", "TextGrades"); - }); - } - - private void getBehaviourGrades() { - d(TAG, "Grades settings: "+enableStandardGrades+", "+enablePointGrades+", "+enableDescriptiveGrades); - if (!enableBehaviourGrades) { - // cancel only if grades have been disabled before - r("finish", "BehaviourGrades"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_behaviour_grades); - apiRequest("BehaviourGrades/Points", data -> { - if (data == null) { - r("finish", "BehaviourGrades"); - return; - } - JsonArray grades = data.get("Grades").getAsJsonArray(); - enableBehaviourGrades = grades.size() > 0; - profile.putStudentData("enableBehaviourGrades", enableBehaviourGrades); - if (!enableBehaviourGrades) { - r("finish", "BehaviourGrades"); - return; - } - //d("Got Grades: "+grades.toString()); - DecimalFormat nameFormat = new DecimalFormat("#.##"); - - Grade gradeStartSemester1 = new Grade( - profileId, - -1, - app.getString(R.string.grade_start_points), - 0xffbdbdbd, - app.getString(R.string.grade_start_points_format, 1), - nameFormat.format(startPointsSemester1), - startPointsSemester1, - -1, - 1, - -1, - 1 - ); - gradeStartSemester1.type = Grade.TYPE_BEHAVIOUR; - Grade gradeStartSemester2 = new Grade( - profileId, - -2, - app.getString(R.string.grade_start_points), - 0xffbdbdbd, - app.getString(R.string.grade_start_points_format, 2), - nameFormat.format(startPointsSemester2), - startPointsSemester2, - -1, - 2, - -1, - 1 - ); - gradeStartSemester2.type = Grade.TYPE_BEHAVIOUR; - - gradeList.add(gradeStartSemester1); - gradeList.add(gradeStartSemester2); - metadataList.add(new Metadata(profileId, Metadata.TYPE_GRADE, -1, true, true, profile.getSemesterStart(1).getInMillis())); - metadataList.add(new Metadata(profileId, Metadata.TYPE_GRADE, -2, true, true, profile.getSemesterStart(2).getInMillis())); - - for (JsonElement gradeEl : grades) { - JsonObject grade = gradeEl.getAsJsonObject(); - long id = grade.get("Id").getAsLong(); - long teacherId = grade.get("AddedBy").getAsJsonObject().get("Id").getAsLong(); - int semester = grade.get("Semester").getAsInt(); - long categoryId = grade.get("Category").getAsJsonObject().get("Id").getAsLong(); - long subjectId = 1; - - float value = 0.0f; - String name = "?"; - JsonElement nameValue; - if ((nameValue = grade.get("Value")) != null) { - value = nameValue.getAsFloat(); - name = value < 0 ? nameFormat.format(value) : "+"+nameFormat.format(value); - } - else if ((nameValue = grade.get("ShortName")) != null) { - name = nameValue.getAsString(); - } - - String str_date = grade.get("AddDate").getAsString(); - long addedDate = Date.fromIso(str_date); - - int color = value > 0 ? 16 : value < 0 ? 26 : 12; - color = colors.get(color); - - String category = ""; - float maxPoints = 0.0f; - GradeCategory gradeCategory = GradeCategory.search(gradeCategoryList, categoryId); - if (gradeCategory != null) { - category = gradeCategory.text; - maxPoints = gradeCategory.valueTo; - } - - Grade gradeObject = new Grade( - profileId, - id, - category, - color, - "", - name, - value, - -1, - semester, - teacherId, - subjectId - ); - gradeObject.type = Grade.TYPE_BEHAVIOUR; - gradeObject.valueMax = maxPoints; - - gradeList.add(gradeObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_GRADE, gradeObject.id, profile.getEmpty(), profile.getEmpty(), addedDate)); - } - r("finish", "BehaviourGrades"); - }); - } - - //private boolean eventTypeListChanged = false; - private void getEvents() { - //eventTypeList = app.db.eventTypeDao().getAllNow(profileId); - // eventTypeListChanged = false; - callback.onActionStarted(R.string.sync_action_syncing_events); - apiRequest("HomeWorks", data -> { - if (data == null) { - r("finish", "Events"); - return; - } - JsonArray events = data.get("HomeWorks").getAsJsonArray(); - //d("Got Grades: "+events.toString()); - boolean getCustomTypes = false; - try { - for (JsonElement eventEl : events) { - JsonObject event = eventEl.getAsJsonObject(); - - JsonElement el; - JsonObject obj; - - long id = event.get("Id").getAsLong(); - long teacherId = -1; - long subjectId = -1; - int type = -1; - - if ((el = event.get("CreatedBy")) != null - && (obj = el.getAsJsonObject()) != null - && (el = obj.get("Id")) != null) { - teacherId = el.getAsLong(); - } - if ((el = event.get("Subject")) != null - && (obj = el.getAsJsonObject()) != null - && (el = obj.get("Id")) != null) { - subjectId = el.getAsLong(); - } - String topic = event.get("Content").getAsString(); - - if ((el = event.get("Category")) != null - && (obj = el.getAsJsonObject()) != null - && (el = obj.get("Id")) != null) { - type = el.getAsInt(); - } - /*EventType typeObject = app.db.eventTypeDao().getByIdNow(profileId, type); - if (typeObject == null) { - getCustomTypes = true; - }*/ - - JsonElement myClass = event.get("Class"); - long teamId = myClass == null ? -1 : myClass.getAsJsonObject().get("Id").getAsLong(); - - String str_date = event.get("AddDate").getAsString(); - long addedDate = Date.fromIso(str_date); - - str_date = event.get("Date").getAsString(); - Date eventDate = Date.fromY_m_d(str_date); - - - Time startTime = null; - JsonElement lessonNo; - JsonElement timeFrom; - if (!((lessonNo = event.get("LessonNo")) instanceof JsonNull)) { - Pair timePair = lessonRanges.get(lessonNo.getAsInt()); - if(timePair != null) - startTime = timePair.first; - } - if (startTime == null && !((timeFrom = event.get("TimeFrom")) instanceof JsonNull)) { - startTime = Time.fromH_m(timeFrom.getAsString()); - } - - Event eventObject = new Event( - profileId, - id, - eventDate, - startTime, - topic, - -1, - type, - false, - teacherId, - subjectId, - teamId - ); - - eventList.add(eventObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_EVENT, eventObject.id, profile.getEmpty(), profile.getEmpty(), addedDate)); - } - r("finish", "Events"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 2541, CODE_OTHER, e, data)); - } - }); - } - - private void getCustomTypes() { - if (!fullSync) { - r("finish", "CustomTypes"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_event_categories); - apiRequest("HomeWorks/Categories", data -> { - if (data == null) { - r("finish", "CustomTypes"); - return; - } - JsonArray jCategories = data.get("Categories").getAsJsonArray(); - //d("Got Classrooms: "+jClassrooms.toString()); - try { - for (JsonElement categoryEl : jCategories) { - JsonObject category = categoryEl.getAsJsonObject(); - eventTypeList.add(new EventType(profileId, category.get("Id").getAsInt(), category.get("Name").getAsString(), colors.get(category.get("Color").getAsJsonObject().get("Id").getAsInt()))); - } - r("finish", "CustomTypes"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 2573, CODE_OTHER, e, data)); - } - }); - } - - private void getHomework() { - if (!premium) { - r("finish", "Homework"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_homework); - apiRequest("HomeWorkAssignments", data -> { - if (data == null) { - r("finish", "Homework"); - return; - } - JsonArray homeworkList = data.get("HomeWorkAssignments").getAsJsonArray(); - //d("Got Grades: "+events.toString()); - try { - for (JsonElement homeworkEl : homeworkList) { - JsonObject homework = homeworkEl.getAsJsonObject(); - - JsonElement el; - JsonObject obj; - - long id = homework.get("Id").getAsLong(); - long teacherId = -1; - long subjectId = -1; - - if ((el = homework.get("Teacher")) != null - && (obj = el.getAsJsonObject()) != null - && (el = obj.get("Id")) != null) { - teacherId = el.getAsLong(); - } - - String topic = ""; - try { - topic = homework.get("Topic").getAsString() + "\n"; - topic += homework.get("Text").getAsString(); - } - catch (Exception e) { - e.printStackTrace(); - } - - String str_date = homework.get("Date").getAsString(); - Date addedDate = Date.fromY_m_d(str_date); - - str_date = homework.get("DueDate").getAsString(); - Date eventDate = Date.fromY_m_d(str_date); - - - Time startTime = null; - - Event eventObject = new Event( - profileId, - id, - eventDate, - startTime, - topic, - -1, - -1, - false, - teacherId, - subjectId, - -1 - ); - - eventList.add(eventObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_EVENT, eventObject.id, profile.getEmpty(), profile.getEmpty(), addedDate.getInMillis())); - } - r("finish", "Homework"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 2648, CODE_OTHER, e, data)); - } - }); - } - - private void getLuckyNumbers() { - if (!profile.getLuckyNumberEnabled() || (profile.getLuckyNumberDate() != null && profile.getLuckyNumberDate().getValue() == Date.getToday().getValue())) { - r("finish", "LuckyNumbers"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_lucky_number); - apiRequest("LuckyNumbers", data -> { - if (data == null) { - profile.setLuckyNumberEnabled(false); - } - else { - profile.setLuckyNumber(-1); - profile.setLuckyNumberDate(Date.getToday()); - try { - JsonElement luckyNumberEl = data.get("LuckyNumber"); - if (luckyNumberEl != null) { - JsonObject luckyNumber = luckyNumberEl.getAsJsonObject(); - profile.setLuckyNumber(luckyNumber.get("LuckyNumber").getAsInt()); - profile.setLuckyNumberDate(Date.fromY_m_d(luckyNumber.get("LuckyNumberDay").getAsString())); - } - } catch (Exception e) { - finishWithError(new AppError(TAG, 2678, CODE_OTHER, e, data)); - } - finally { - app.db.luckyNumberDao().add(new LuckyNumber(profileId, profile.getLuckyNumberDate(), profile.getLuckyNumber())); - } - } - r("finish", "LuckyNumbers"); - }); - } - - private void getNotices() { - callback.onActionStarted(R.string.sync_action_syncing_notices); - apiRequest("Notes", data -> { - if (data == null) { - r("finish", "Notices"); - return; - } - try { - JsonArray jNotices = data.get("Notes").getAsJsonArray(); - - for (JsonElement noticeEl : jNotices) { - JsonObject notice = noticeEl.getAsJsonObject(); - - int type = notice.get("Positive").getAsInt(); - switch (type) { - case 0: - type = TYPE_NEGATIVE; - break; - case 1: - type = TYPE_POSITIVE; - break; - case 2: - type = TYPE_NEUTRAL; - break; - } - - long id = notice.get("Id").getAsLong(); - - Date addedDate = Date.fromY_m_d(notice.get("Date").getAsString()); - - int semester = profile.dateToSemester(addedDate); - - JsonElement el; - JsonObject obj; - long teacherId = -1; - if ((el = notice.get("Teacher")) != null - && (obj = el.getAsJsonObject()) != null - && (el = obj.get("Id")) != null) { - teacherId = el.getAsLong(); - } - - Notice noticeObject = new Notice( - profileId, - id, - notice.get("Text").getAsString(), - semester, - type, - teacherId - ); - - noticeList.add(noticeObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_NOTICE, noticeObject.id, profile.getEmpty(), profile.getEmpty(), addedDate.getInMillis())); - } - r("finish", "Notices"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 2750, CODE_OTHER, e, data)); - } - }); - } - - private SparseArray> attendanceTypes = new SparseArray<>(); - private void getAttendanceTypes() { - callback.onActionStarted(R.string.sync_action_syncing_attendance_types); - apiRequest("Attendances/Types", data -> { - if (data == null) { - r("finish", "AttendanceTypes"); - return; - } - try { - JsonArray jTypes = data.get("Types").getAsJsonArray(); - for (JsonElement typeEl : jTypes) { - JsonObject type = typeEl.getAsJsonObject(); - int id = type.get("Id").getAsInt(); - attendanceTypes.put(id, - new Pair<>( - type.get("Standard").getAsBoolean() ? id : type.getAsJsonObject("StandardType").get("Id").getAsInt(), - type.get("Name").getAsString() - ) - ); - } - r("finish", "AttendanceTypes"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 2782, CODE_OTHER, e, data)); - } - }); - } - - private void getAttendance() { - callback.onActionStarted(R.string.sync_action_syncing_attendance); - apiRequest("Attendances"+(fullSync ? "" : "?dateFrom="+ Date.getToday().stepForward(0, -1, 0).getStringY_m_d()), data -> { - if (data == null) { - r("finish", "Attendance"); - return; - } - - try { - JsonArray jAttendance = data.get("Attendances").getAsJsonArray(); - - for (JsonElement attendanceEl : jAttendance) { - JsonObject attendance = attendanceEl.getAsJsonObject(); - - int type = attendance.getAsJsonObject("Type").get("Id").getAsInt(); - Pair attendanceType; - if ((attendanceType = attendanceTypes.get(type)) != null) { - type = attendanceType.first; - } - switch (type) { - case 1: - type = TYPE_ABSENT; - break; - case 2: - type = TYPE_BELATED; - break; - case 3: - type = TYPE_ABSENT_EXCUSED; - break; - case 4: - type = TYPE_RELEASED; - break; - default: - case 100: - type = TYPE_PRESENT; - break; - } - - String idStr = attendance.get("Id").getAsString(); - int id = strToInt(idStr.replaceAll("[^\\d.]", "")); - - long addedDate = Date.fromIso(attendance.get("AddDate").getAsString()); - - Time startTime = Time.getNow(); - Pair timePair = lessonRanges.get(attendance.get("LessonNo").getAsInt()); - if (timePair != null) - startTime = timePair.first; - Date lessonDate = Date.fromY_m_d(attendance.get("Date").getAsString()); - int lessonWeekDay = lessonDate.getWeekDay(); - long subjectId = -1; - String topic = ""; - if (attendanceType != null) { - topic = attendanceType.second; - } - - for (Lesson lesson: lessonList) { - if (lesson.weekDay == lessonWeekDay && lesson.startTime.getValue() == startTime.getValue()) { - subjectId = lesson.subjectId; - } - } - - Attendance attendanceObject = new Attendance( - profileId, - id, - attendance.getAsJsonObject("AddedBy").get("Id").getAsLong(), - subjectId, - attendance.get("Semester").getAsInt(), - topic, - lessonDate, - startTime, - type); - - attendanceList.add(attendanceObject); - if (attendanceObject.type != TYPE_PRESENT) { - metadataList.add(new Metadata(profileId, Metadata.TYPE_ATTENDANCE, attendanceObject.id, profile.getEmpty(), profile.getEmpty(), addedDate)); - } - } - r("finish", "Attendance"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 2872, CODE_OTHER, e, data)); - } - }); - } - - private void getAnnouncements() { - callback.onActionStarted(R.string.sync_action_syncing_announcements); - apiRequest("SchoolNotices", data -> { - if (data == null) { - r("finish", "Announcements"); - return; - } - try { - JsonArray jAnnouncements = data.get("SchoolNotices").getAsJsonArray(); - - for (JsonElement announcementEl : jAnnouncements) { - JsonObject announcement = announcementEl.getAsJsonObject(); - - String idStr = announcement.get("Id").getAsString(); - long id = crc16(idStr.getBytes()); - - long addedDate = Date.fromIso(announcement.get("CreationDate").getAsString()); - - boolean read = announcement.get("WasRead").getAsBoolean(); - - String subject = ""; - String text = ""; - Date startDate = null; - Date endDate = null; - try { - subject = announcement.get("Subject").getAsString(); - text = announcement.get("Content").getAsString(); - startDate = Date.fromY_m_d(announcement.get("StartDate").getAsString()); - endDate = Date.fromY_m_d(announcement.get("EndDate").getAsString()); - } - catch (Exception e) { - e.printStackTrace(); - } - - JsonElement el; - JsonObject obj; - long teacherId = -1; - if ((el = announcement.get("AddedBy")) != null - && (obj = el.getAsJsonObject()) != null - && (el = obj.get("Id")) != null) { - teacherId = el.getAsLong(); - } - - Announcement announcementObject = new Announcement( - profileId, - id, - subject, - text, - startDate, - endDate, - teacherId - ); - - announcementList.add(announcementObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_ANNOUNCEMENT, announcementObject.id, read, read, addedDate)); - } - r("finish", "Announcements"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 2944, CODE_OTHER, e, data)); - } - }); - } - - private void getPtMeetings() { - if (!fullSync) { - r("finish", "PtMeetings"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_pt_meetings); - apiRequest("ParentTeacherConferences", data -> { - if (data == null) { - r("finish", "PtMeetings"); - return; - } - try { - JsonArray jMeetings = data.get("ParentTeacherConferences").getAsJsonArray(); - for (JsonElement meetingEl: jMeetings) { - JsonObject meeting = meetingEl.getAsJsonObject(); - - long id = meeting.get("Id").getAsLong(); - Event eventObject = new Event( - profileId, - id, - Date.fromY_m_d(meeting.get("Date").getAsString()), - Time.fromH_m(meeting.get("Time").getAsString()), - meeting.get("Topic").getAsString(), - -1, - TYPE_PT_MEETING, - false, - meeting.getAsJsonObject("Teacher").get("Id").getAsLong(), - -1, - teamClassId - ); - eventList.add(eventObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_EVENT, eventObject.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - } - r("finish", "PtMeetings"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 2996, CODE_OTHER, e, data)); - } - }); - } - - private SparseArray teacherFreeDaysTypes = new SparseArray<>(); - private void getTeacherFreeDaysTypes() { - if (!fullSync) { - r("finish", "TeacherFreeDaysTypes"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_teacher_free_days_types); - apiRequest("TeacherFreeDays/Types", data -> { - if (data == null) { - r("finish", "TeacherFreeDays"); - return; - } - try { - JsonArray jTypes = data.get("Types").getAsJsonArray(); - for (JsonElement typeEl : jTypes) { - JsonObject type = typeEl.getAsJsonObject(); - int id = type.get("Id").getAsInt(); - teacherFreeDaysTypes.put(id, type.get("Name").getAsString()); - } - r("finish", "TeacherFreeDaysTypes"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 3019, CODE_OTHER, e, data)); - } - }); - } - - private void getTeacherFreeDays() { - callback.onActionStarted(R.string.sync_action_syncing_teacher_free_days); - apiRequest("TeacherFreeDays", data -> { - if (data == null) { - r("finish", "TeacherFreeDays"); - return; - } - try { - JsonArray jFreeDays = data.get("TeacherFreeDays").getAsJsonArray(); - for (JsonElement freeDayEl: jFreeDays) { - JsonObject freeDay = freeDayEl.getAsJsonObject(); - - long id = freeDay.get("Id").getAsLong(); - long teacherId = freeDay.getAsJsonObject("Teacher").get("Id").getAsLong(); - - Date dateFrom = Date.fromY_m_d(freeDay.get("DateFrom").getAsString()); - Date dateTo = Date.fromY_m_d(freeDay.get("DateTo").getAsString()); - - Time timeFrom = null; - Time timeTo = null; - - if (freeDay.get("TimeFrom") != null && freeDay.get("TimeTo") != null) { - timeFrom = Time.fromH_m_s(freeDay.get("TimeFrom").getAsString()); - timeTo = Time.fromH_m_s(freeDay.get("TimeTo").getAsString()); - } - - long type = freeDay.getAsJsonObject("Type").get("Id").getAsLong(); - - //String topic = teacherFreeDaysTypes.get(type)+"\n"+(dateFrom.getValue() != dateTo.getValue() ? dateFrom.getFormattedString()+" - "+dateTo.getFormattedString() : ""); - - TeacherAbsence teacherAbsence = new TeacherAbsence( - profileId, - id, - teacherId, - type, - dateFrom, - dateTo, - timeFrom, - timeTo - ); - - teacherAbsenceList.add(teacherAbsence); - metadataList.add( - new Metadata( - profileId, - Metadata.TYPE_TEACHER_ABSENCE, - teacherAbsence.getId(), - true, - true, - System.currentTimeMillis()) - ); - - } - r("finish", "TeacherFreeDays"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 3069, CODE_OTHER, e, data)); - } - }); - } - - private void getSchoolFreeDays() { - callback.onActionStarted(R.string.sync_action_syncing_school_free_days); - apiRequest("SchoolFreeDays" + (unitId != -1 ? "?unit=" + unitId : ""), data -> { - if (data == null) { - r("finish", "SchoolFreeDays"); - return; - } - try { - JsonArray jFreeDays = data.get("SchoolFreeDays").getAsJsonArray(); - - for (JsonElement freeDayEl: jFreeDays) { - continue; - } - r("finish", "SchoolFreeDays"); - } catch (Exception e) { - finishWithError(new AppError(TAG, 3069, CODE_OTHER, e, data)); - } - }); - } - - private void getMessagesLogin() { - if (synergiaPassword == null) { - // skip messages - r("finish", "MessagesOutbox"); - return; - } - loginSynergia(() -> { - r("finish", "MessagesLogin"); - }); - } - - private void getMessagesInbox() { - String body = - "\n" + - "
    \n" + - " \n" + - " 0\n" + - " \n" + - ""; - synergiaRequest("Inbox/action/GetList", body, data -> { - try { - long startTime = System.currentTimeMillis(); - - for (Element e: data.select("response GetList data ArrayItem")) { - - long id = Long.parseLong(e.select("messageId").text()); - - String subject = e.select("topic").text(); - - String senderFirstName = e.select("senderFirstName").text(); - String senderLastName = e.select("senderLastName").text(); - - long senderId = -1; - - for (Teacher teacher: teacherList) { - if (teacher.name.equalsIgnoreCase(senderFirstName) && teacher.surname.equalsIgnoreCase(senderLastName)) { - senderId = teacher.id; - break; - } - } - if (senderId == -1) { - Teacher teacher = new Teacher(profileId, -1 * Utils.crc16((senderFirstName+" "+senderLastName).getBytes()), senderFirstName, senderLastName); - senderId = teacher.id; - teacherList.add(teacher); - teacherListChanged = true; - } - - long readDate = 0; - long sentDate; - - String readDateStr = e.select("readDate").text(); - String sentDateStr = e.select("sendDate").text(); - - DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); - if (!readDateStr.isEmpty()) { - readDate = formatter.parse(readDateStr).getTime(); - } - sentDate = formatter.parse(sentDateStr).getTime(); - - Message message = new Message( - profileId, - id, - subject, - null, - TYPE_RECEIVED, - senderId, - -1 - ); - - MessageRecipient messageRecipient = new MessageRecipient( - profileId, - -1 /* me */, - -1, - readDate, - /*messageId*/ id - ); - - if (!e.select("isAnyFileAttached").text().equals("0")) - message.setHasAttachments(); - - messageList.add(message); - messageRecipientList.add(messageRecipient); - messageMetadataList.add(new Metadata(profileId, Metadata.TYPE_MESSAGE, message.id, readDate > 0, readDate > 0 || profile.getEmpty(), sentDate)); - } - - } catch (Exception e3) { - finishWithError(new AppError(TAG, 3164, CODE_OTHER, e3, data.outerHtml())); - return; - } - - r("finish", "MessagesInbox"); - }); - } - - private void getMessagesOutbox() { - if (!fullSync && onlyFeature != FEATURE_MESSAGES_OUTBOX && !profile.getEmpty()) { - // a quick sync and the profile is already synced at least once - r("finish", "MessagesOutbox"); - return; - } - String body = - "\n" + - "
    \n" + - " \n" + - " 0\n" + - " \n" + - ""; - synergiaRequest("Outbox/action/GetList", body, data -> { - try { - long startTime = System.currentTimeMillis(); - - for (Element e: data.select("response GetList data ArrayItem")) { - - long id = Long.parseLong(e.select("messageId").text()); - - String subject = e.select("topic").text(); - - String receiverFirstName = e.select("receiverFirstName").text(); - String receiverLastName = e.select("receiverLastName").text(); - - long receiverId = -1; - - for (Teacher teacher: teacherList) { - if (teacher.name.equalsIgnoreCase(receiverFirstName) && teacher.surname.equalsIgnoreCase(receiverLastName)) { - receiverId = teacher.id; - break; - } - } - if (receiverId == -1) { - Teacher teacher = new Teacher(profileId, -1 * Utils.crc16((receiverFirstName+" "+receiverLastName).getBytes()), receiverFirstName, receiverLastName); - receiverId = teacher.id; - teacherList.add(teacher); - teacherListChanged = true; - } - - long sentDate; - - String sentDateStr = e.select("sendDate").text(); - - DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); - sentDate = formatter.parse(sentDateStr).getTime(); - - Message message = new Message( - profileId, - id, - subject, - null, - TYPE_SENT, - -1, - -1 - ); - - MessageRecipient messageRecipient = new MessageRecipient( - profileId, - receiverId, - -1, - -1, - /*messageId*/ id - ); - - if (!e.select("isAnyFileAttached").text().equals("0")) - message.setHasAttachments(); - - messageList.add(message); - messageRecipientIgnoreList.add(messageRecipient); - metadataList.add(new Metadata(profileId, Metadata.TYPE_MESSAGE, message.id, true, true, sentDate)); - } - - } catch (Exception e3) { - finishWithError(new AppError(TAG, 3270, CODE_OTHER, e3, data.outerHtml())); - return; - } - - r("finish", "MessagesOutbox"); - }); - } - - @Override - public Map getConfigurableEndpoints(Profile profile) { - Map configurableEndpoints = new LinkedHashMap<>(); - configurableEndpoints.put("Classrooms", new Endpoint("Classrooms",true, false, profile.getChangedEndpoints())); - configurableEndpoints.put("Timetables", new Endpoint("Timetables",true, false, profile.getChangedEndpoints())); - configurableEndpoints.put("Substitutions", new Endpoint("Substitutions",true, false, profile.getChangedEndpoints())); - configurableEndpoints.put("Grades", new Endpoint("Grades",true, false, profile.getChangedEndpoints())); - configurableEndpoints.put("PointGrades", new Endpoint("PointGrades",true, false, profile.getChangedEndpoints())); - configurableEndpoints.put("Events", new Endpoint("Events",true, false, profile.getChangedEndpoints())); - configurableEndpoints.put("Homework", new Endpoint("Homework",true, false, profile.getChangedEndpoints())); - configurableEndpoints.put("LuckyNumbers", new Endpoint("LuckyNumbers",true, false, profile.getChangedEndpoints())); - configurableEndpoints.put("Notices", new Endpoint("Notices",true, false, profile.getChangedEndpoints())); - configurableEndpoints.put("Attendance", new Endpoint("Attendance",true, false, profile.getChangedEndpoints())); - configurableEndpoints.put("Announcements", new Endpoint("Announcements",true, true, profile.getChangedEndpoints())); - configurableEndpoints.put("PtMeetings", new Endpoint("PtMeetings",true, true, profile.getChangedEndpoints())); - configurableEndpoints.put("TeacherFreeDays", new Endpoint("TeacherFreeDays",false, false, profile.getChangedEndpoints())); - //configurableEndpoints.put("SchoolFreeDays", new Endpoint("SchoolFreeDays",true, true, profile.changedEndpoints)); - //configurableEndpoints.put("ClassFreeDays", new Endpoint("ClassFreeDays",true, true, profile.changedEndpoints)); - configurableEndpoints.put("MessagesInbox", new Endpoint("MessagesInbox", true, false, profile.getChangedEndpoints())); - configurableEndpoints.put("MessagesOutbox", new Endpoint("MessagesOutbox", true, true, profile.getChangedEndpoints())); - return configurableEndpoints; - } - - @Override - public boolean isEndpointEnabled(Profile profile, boolean defaultActive, String name) { - return defaultActive ^ contains(profile.getChangedEndpoints(), name); - } - - @Override - public void syncMessages(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile) - { - if (!prepare(activityContext, errorCallback, profile.getId(), profile, LoginStore.fromProfileFull(profile))) - return; - - login(() -> { - Librus.this.profile.setEmpty(true); - targetEndpoints = new ArrayList<>(); - targetEndpoints.add("Users"); - targetEndpoints.add("MessagesLogin"); - targetEndpoints.add("MessagesInbox"); - targetEndpoints.add("MessagesOutbox"); - targetEndpoints.add("Finish"); - PROGRESS_COUNT = targetEndpoints.size()-1; - PROGRESS_STEP = (90/PROGRESS_COUNT); - begin(); - }); - } - - /* __ __ - | \/ | - | \ / | ___ ___ ___ __ _ __ _ ___ ___ - | |\/| |/ _ \/ __/ __|/ _` |/ _` |/ _ \/ __| - | | | | __/\__ \__ \ (_| | (_| | __/\__ \ - |_| |_|\___||___/___/\__,_|\__, |\___||___/ - __/ | - |__*/ - @Override - public void getMessage(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile, @NonNull MessageFull message, @NonNull MessageGetCallback messageCallback) - { - if (message.body != null) { - boolean readByAll = true; - // load this message's recipient(s) data - message.recipients = app.db.messageRecipientDao().getAllByMessageId(profile.getId(), message.id); - for (MessageRecipientFull recipient: message.recipients) { - if (recipient.id == -1) - recipient.fullName = profile.getStudentNameLong(); - if (message.type == TYPE_SENT && recipient.readDate < 1) - readByAll = false; - } - if (!message.seen) { - app.db.metadataDao().setSeen(profile.getId(), message, true); - } - if (readByAll) { - // if a sent msg is not read by everyone, download it again to check the read status - new Handler(activityContext.getMainLooper()).post(() -> { - messageCallback.onSuccess(message); - }); - return; - } - } - - if (!prepare(activityContext, errorCallback, profile.getId(), profile, LoginStore.fromProfileFull(profile))) - return; - - loginSynergia(() -> { - String requestBody = - "\n" + - "
    \n" + - " \n" + - " "+message.id+"\n" + - " 0\n" + - " \n" + - ""; - synergiaRequest("GetMessage", requestBody, data -> { - - List messageRecipientList = new ArrayList<>(); - - try { - Element e = data.select("response GetMessage data").first(); - - String body = e.select("Message").text(); - body = new String(Base64.decode(body, Base64.DEFAULT)); - body = body.replaceAll("\n", "
    "); - body = body.replaceAll("", ""); - - message.clearAttachments(); - Elements attachments = e.select("attachments ArrayItem"); - if (attachments != null) { - for (Element attachment: attachments) { - message.addAttachment(Long.parseLong(attachment.select("id").text()), attachment.select("filename").text(), -1); - } - } - - message.body = body; - - if (message.type == TYPE_RECEIVED) { - app.db.teacherDao().updateLoginId(profileId, message.senderId, e.select("senderId").text()); - - MessageRecipientFull recipient = new MessageRecipientFull(profileId, -1, message.id); - - long readDate = 0; - String readDateStr = e.select("readDate").text(); - if (!readDateStr.isEmpty()) { - DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); - readDate = formatter.parse(readDateStr).getTime(); - } - recipient.readDate = readDate; - - recipient.fullName = profile.getStudentNameLong(); - messageRecipientList.add(recipient); - - } - else if (message.type == TYPE_SENT) { - List teacherList = app.db.teacherDao().getAllNow(profileId); - for (Element receiver: e.select("receivers ArrayItem")) { - String receiverFirstName = e.select("firstName").text(); - String receiverLastName = e.select("lastName").text(); - - long receiverId = -1; - - for (Teacher teacher: teacherList) { - if (teacher.name.equalsIgnoreCase(receiverFirstName) && teacher.surname.equalsIgnoreCase(receiverLastName)) { - receiverId = teacher.id; - break; - } - } - - app.db.teacherDao().updateLoginId(profileId, receiverId, receiver.select("receiverId").text()); - - MessageRecipientFull recipient = new MessageRecipientFull(profileId, receiverId, message.id); - - long readDate = 0; - String readDateStr = e.select("readed").text(); - if (!readDateStr.isEmpty()) { - DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); - readDate = formatter.parse(readDateStr).getTime(); - } - recipient.readDate = readDate; - - recipient.fullName = receiverFirstName+" "+receiverLastName; - messageRecipientList.add(recipient); - } - } - - } - catch (Exception e) { - finishWithError(new AppError(TAG, 795, CODE_OTHER, e, data.outerHtml())); - return; - } - - if (!message.seen) { - app.db.metadataDao().setSeen(profileId, message, true); - } - app.db.messageDao().add(message); - app.db.messageRecipientDao().addAll((List)(List) messageRecipientList); // not addAllIgnore - - message.recipients = messageRecipientList; - - new Handler(activityContext.getMainLooper()).post(() -> { - messageCallback.onSuccess(message); - }); - }); - }); - } - - @Override - public void getAttachment(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile, @NonNull MessageFull message, long attachmentId, @NonNull AttachmentGetCallback attachmentCallback) { - if (!prepare(activityContext, errorCallback, profile.getId(), profile, LoginStore.fromProfileFull(profile))) - return; - - loginSynergia(() -> { - String requestBody = - "\n" + - "
    \n" + - " \n" + - " "+attachmentId+"\n" + - " "+message.id+"\n" + - " 0\n" + - " \n" + - ""; - synergiaRequest("GetFileDownloadLink", requestBody, data -> { - String downloadLink = data.select("response GetFileDownloadLink downloadLink").text(); - Matcher keyMatcher = Pattern.compile("singleUseKey=([0-9A-f_]+)").matcher(downloadLink); - if (keyMatcher.find()) { - getAttachmentCheckKeyTries = 0; - getAttachmentCheckKey(keyMatcher.group(1), attachmentCallback); - } - else { - finishWithError(new AppError(TAG, 629, CODE_OTHER, "Błąd pobierania tokenu. Skontaktuj się z twórcą aplikacji.", data.outerHtml())); - } - }); - }); - } - private int getAttachmentCheckKeyTries = 0; - private void getAttachmentCheckKey(String attachmentKey, AttachmentGetCallback attachmentCallback) { - Request.builder() - .url(SYNERGIA_SANDBOX_URL+"CSCheckKey") - .userAgent(synergiaUserAgent) - .addParameter("singleUseKey", attachmentKey) - .post() - .callback(new JsonCallbackHandler() { - @Override - public void onSuccess(JsonObject data, Response response) { - if (data == null) { - finishWithError(new AppError(TAG, 645, AppError.CODE_MAINTENANCE, response)); - return; - } - try { - String status = data.get("status").getAsString(); - if (status.equals("not_downloaded_yet")) { - if (getAttachmentCheckKeyTries++ > 5) { - finishWithError(new AppError(TAG, 658, CODE_OTHER, "Załącznik niedostępny. Przekroczono czas oczekiwania.", response, data)); - return; - } - new Handler(activityContext.getMainLooper()).postDelayed(() -> { - getAttachmentCheckKey(attachmentKey, attachmentCallback); - }, 2000); - } - else if (status.equals("ready")) { - Request.Builder builder = Request.builder() - .url(SYNERGIA_SANDBOX_URL+"CSDownload&singleUseKey="+attachmentKey); - new Handler(activityContext.getMainLooper()).post(() -> { - attachmentCallback.onSuccess(builder); - }); - } - else { - finishWithError(new AppError(TAG, 667, AppError.CODE_ATTACHMENT_NOT_AVAILABLE, response, data)); - } - } - catch (Exception e) { - finishWithError(new AppError(TAG, 671, AppError.CODE_OTHER, response, e, data)); - } - } - - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 677, CODE_OTHER, response, throwable)); - } - }) - .build() - .enqueue(); - } - - @Override - public void getRecipientList(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile, @NonNull RecipientListGetCallback recipientListGetCallback) { - if (!prepare(activityContext, errorCallback, profile.getId(), profile, LoginStore.fromProfileFull(profile))) - return; - - if (System.currentTimeMillis() - profile.getLastReceiversSync() < 24 * 60 * 60 * 1000) { - AsyncTask.execute(() -> { - List teacherList = app.db.teacherDao().getAllNow(profileId); - new Handler(activityContext.getMainLooper()).post(() -> recipientListGetCallback.onSuccess(teacherList)); - }); - return; - } - - loginSynergia(() -> { - String requestBody = - "\n" + - "
    \n" + - " \n" + - " 1\n" + - " \n" + - ""; - synergiaRequest("Receivers/action/GetTypes", requestBody, data -> { - - teacherList = app.db.teacherDao().getAllNow(profileId); - - for (Teacher teacher: teacherList) { - teacher.typeDescription = null; // TODO: 2019-06-13 it better - } - - Elements categories = data.select("response GetTypes data list ArrayItem"); - for (Element category: categories) { - String categoryId = category.select("id").text(); - String categoryName = category.select("name").text(); - Elements categoryList = getRecipientCategory(categoryId); - if (categoryList == null) - return; // the error callback is already executed - for (Element item: categoryList) { - if (item.select("list").size() == 1) { - String className = item.select("label").text(); - Elements list = item.select("list ArrayItem"); - for (Element teacher: list) { - updateTeacher(categoryId, Long.parseLong(teacher.select("id").text()), teacher.select("label").text(), categoryName, className); - } - } - else { - updateTeacher(categoryId, Long.parseLong(item.select("id").text()), item.select("label").text(), categoryName, null); - } - } - } - - app.db.teacherDao().addAll(teacherList); - - profile.setLastReceiversSync(System.currentTimeMillis()); - app.db.profileDao().add(profile); - - new Handler(activityContext.getMainLooper()).post(() -> recipientListGetCallback.onSuccess(new ArrayList<>(teacherList))); - }); - }); - } - private Elements getRecipientCategory(String categoryId) { - Response response = null; - try { - String endpoint = "Receivers/action/GetListForType"; - d(TAG, "Requesting "+SYNERGIA_URL+endpoint); - String body = - "\n" + - "
    \n" + - " \n" + - " "+categoryId+"\n" + - " \n" + - ""; - response = Request.builder() - .url(SYNERGIA_URL+endpoint) - .userAgent(synergiaUserAgent) - .setTextBody(body, MediaTypeUtils.APPLICATION_XML) - .build().execute(); - if (response.code() != 200) { - finishWithError(new AppError(TAG, 3569, CODE_OTHER, response)); - return null; - } - String data = new TextCallbackHandler().backgroundParser(response); - if (data.contains("error") || data.contains("")) { - finishWithError(new AppError(TAG, 3556, AppError.CODE_MAINTENANCE, response, data)); - return null; - } - Document doc = Jsoup.parse(data, "", Parser.xmlParser()); - return doc.select("response GetListForType data ArrayItem"); - } catch (Exception e) { - finishWithError(new AppError(TAG, 3562, CODE_OTHER, response, e)); - return null; - } - } - private void updateTeacher(String category, long loginId, String nameLastFirst, String typeDescription, String className) { - nameLastFirst = nameLastFirst.replaceAll("\\s+", " "); - int type = TYPE_OTHER; - String position; - switch (category) { - case "tutors": - type = TYPE_EDUCATOR; - break; - case "teachers": - type = TYPE_TEACHER; - break; - case "pedagogue": - type = TYPE_PEDAGOGUE; - break; - case "librarian": - type = TYPE_LIBRARIAN; - break; - case "admin": - type = TYPE_SCHOOL_ADMIN; - break; - case "secretary": - type = TYPE_SECRETARIAT; - break; - case "sadmin": - type = TYPE_SUPER_ADMIN; - break; - case "parentsCouncil": - type = TYPE_PARENTS_COUNCIL; - int index = nameLastFirst.indexOf(" - "); - position = index == -1 ? "" : nameLastFirst.substring(index+3); - nameLastFirst = index == -1 ? nameLastFirst : nameLastFirst.substring(0, index); - typeDescription = bs(className)+bs(": ", position); - break; - case "schoolParentsCouncil": - type = TYPE_SCHOOL_PARENTS_COUNCIL; - index = nameLastFirst.indexOf(" - "); - position = index == -1 ? "" : nameLastFirst.substring(index+3); - nameLastFirst = index == -1 ? nameLastFirst : nameLastFirst.substring(0, index); - typeDescription = bs(position); - break; - case "contactsGroups": - return; - } - Teacher teacher = Teacher.getByFullNameLastFirst(teacherList, nameLastFirst); - if (teacher == null) { - String[] nameParts = nameLastFirst.split(" ", Integer.MAX_VALUE); - teacher = new Teacher(profileId, -1 * Utils.crc16((nameParts.length > 1 ? nameParts[1]+" "+nameParts[0] : nameParts[0]).getBytes()), nameParts.length > 1 ? nameParts[1] : "", nameParts[0]); - teacherList.add(teacher); - } - teacher.loginId = String.valueOf(loginId); - teacher.type = 0; - teacher.setType(type); - if (type == TYPE_OTHER) { - teacher.typeDescription = typeDescription+bs(" ", teacher.typeDescription); - } - else { - teacher.typeDescription = typeDescription; - } - } - - @Override - public MessagesComposeInfo getComposeInfo(@NonNull ProfileFull profile) { - return new MessagesComposeInfo(0, 0, 150, 20000); - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/LoginMethods.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/LoginMethods.kt new file mode 100644 index 00000000..b3db9f71 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/LoginMethods.kt @@ -0,0 +1,147 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-20. + */ + +package pl.szczodrzynski.edziennik.data.api + +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.login.EdudziennikLoginWeb +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.login.LibrusLoginApi +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.login.LibrusLoginMessages +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.login.LibrusLoginPortal +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.login.LibrusLoginSynergia +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.login.MobidziennikLoginApi2 +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.login.MobidziennikLoginWeb +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.login.PodlasieLoginApi +import pl.szczodrzynski.edziennik.data.api.edziennik.template.login.TemplateLoginApi +import pl.szczodrzynski.edziennik.data.api.edziennik.template.login.TemplateLoginWeb +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.login.VulcanLoginHebe +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.login.VulcanLoginWebMain +import pl.szczodrzynski.edziennik.data.api.models.LoginMethod + +// librus +// mobidziennik +// idziennik [*] +// vulcan +// mobireg + +const val SYNERGIA_API_ENABLED = false + + +const val LOGIN_TYPE_IDZIENNIK = 3 + +const val LOGIN_TYPE_TEMPLATE = 21 + +// LOGIN MODES +const val LOGIN_MODE_TEMPLATE_WEB = 0 + +// LOGIN METHODS +const val LOGIN_METHOD_NOT_NEEDED = -1 +const val LOGIN_METHOD_TEMPLATE_WEB = 100 +const val LOGIN_METHOD_TEMPLATE_API = 200 + +const val LOGIN_TYPE_LIBRUS = 2 +const val LOGIN_MODE_LIBRUS_EMAIL = 0 +const val LOGIN_MODE_LIBRUS_SYNERGIA = 1 +const val LOGIN_MODE_LIBRUS_JST = 2 +const val LOGIN_METHOD_LIBRUS_PORTAL = 100 +const val LOGIN_METHOD_LIBRUS_API = 200 +const val LOGIN_METHOD_LIBRUS_SYNERGIA = 300 +const val LOGIN_METHOD_LIBRUS_MESSAGES = 400 +val librusLoginMethods = listOf( + LoginMethod(LOGIN_TYPE_LIBRUS, LOGIN_METHOD_LIBRUS_PORTAL, LibrusLoginPortal::class.java) + .withIsPossible { _, loginStore -> + loginStore.mode == LOGIN_MODE_LIBRUS_EMAIL + } + .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_NOT_NEEDED }, + + LoginMethod(LOGIN_TYPE_LIBRUS, LOGIN_METHOD_LIBRUS_API, LibrusLoginApi::class.java) + .withIsPossible { _, loginStore -> + loginStore.mode != LOGIN_MODE_LIBRUS_SYNERGIA || SYNERGIA_API_ENABLED + } + .withRequiredLoginMethod { _, loginStore -> + if (loginStore.mode == LOGIN_MODE_LIBRUS_EMAIL) LOGIN_METHOD_LIBRUS_PORTAL else LOGIN_METHOD_NOT_NEEDED + }, + + LoginMethod(LOGIN_TYPE_LIBRUS, LOGIN_METHOD_LIBRUS_SYNERGIA, LibrusLoginSynergia::class.java) + .withIsPossible { _, loginStore -> !loginStore.hasLoginData("fakeLogin") } + .withRequiredLoginMethod { profile, _ -> + if (profile?.hasStudentData("accountPassword") == false || true) LOGIN_METHOD_LIBRUS_API else LOGIN_METHOD_NOT_NEEDED + }, + + LoginMethod(LOGIN_TYPE_LIBRUS, LOGIN_METHOD_LIBRUS_MESSAGES, LibrusLoginMessages::class.java) + .withIsPossible { _, loginStore -> !loginStore.hasLoginData("fakeLogin") } + .withRequiredLoginMethod { profile, _ -> + if (profile?.hasStudentData("accountPassword") == false || true) LOGIN_METHOD_LIBRUS_SYNERGIA else LOGIN_METHOD_NOT_NEEDED + } +) + +const val LOGIN_TYPE_MOBIDZIENNIK = 1 +const val LOGIN_MODE_MOBIDZIENNIK_WEB = 0 +const val LOGIN_METHOD_MOBIDZIENNIK_WEB = 100 +const val LOGIN_METHOD_MOBIDZIENNIK_API2 = 300 +val mobidziennikLoginMethods = listOf( + LoginMethod(LOGIN_TYPE_MOBIDZIENNIK, LOGIN_METHOD_MOBIDZIENNIK_WEB, MobidziennikLoginWeb::class.java) + .withIsPossible { _, _ -> true } + .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_NOT_NEEDED }, + + LoginMethod(LOGIN_TYPE_MOBIDZIENNIK, LOGIN_METHOD_MOBIDZIENNIK_API2, MobidziennikLoginApi2::class.java) + .withIsPossible { profile, _ -> profile?.getStudentData("email", null) != null } + .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_NOT_NEEDED } +) + +const val LOGIN_TYPE_VULCAN = 4 +const val LOGIN_MODE_VULCAN_API = 0 +const val LOGIN_MODE_VULCAN_WEB = 1 +const val LOGIN_MODE_VULCAN_HEBE = 2 +const val LOGIN_METHOD_VULCAN_WEB_MAIN = 100 +const val LOGIN_METHOD_VULCAN_WEB_NEW = 200 +const val LOGIN_METHOD_VULCAN_WEB_OLD = 300 +const val LOGIN_METHOD_VULCAN_WEB_MESSAGES = 400 +const val LOGIN_METHOD_VULCAN_HEBE = 600 +val vulcanLoginMethods = listOf( + LoginMethod(LOGIN_TYPE_VULCAN, LOGIN_METHOD_VULCAN_WEB_MAIN, VulcanLoginWebMain::class.java) + .withIsPossible { _, loginStore -> loginStore.hasLoginData("webHost") } + .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_NOT_NEEDED }, + + /*LoginMethod(LOGIN_TYPE_VULCAN, LOGIN_METHOD_VULCAN_WEB_NEW, VulcanLoginWebNew::class.java) + .withIsPossible { _, _ -> false } + .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_VULCAN_WEB_MAIN }, + + LoginMethod(LOGIN_TYPE_VULCAN, LOGIN_METHOD_VULCAN_WEB_OLD, VulcanLoginWebOld::class.java) + .withIsPossible { _, _ -> false } + .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_VULCAN_WEB_MAIN },*/ + + LoginMethod(LOGIN_TYPE_VULCAN, LOGIN_METHOD_VULCAN_HEBE, VulcanLoginHebe::class.java) + .withIsPossible { _, loginStore -> + loginStore.mode != LOGIN_MODE_VULCAN_API + } + .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_NOT_NEEDED } +) + +const val LOGIN_TYPE_EDUDZIENNIK = 5 +const val LOGIN_MODE_EDUDZIENNIK_WEB = 0 +const val LOGIN_METHOD_EDUDZIENNIK_WEB = 100 +val edudziennikLoginMethods = listOf( + LoginMethod(LOGIN_TYPE_EDUDZIENNIK, LOGIN_METHOD_EDUDZIENNIK_WEB, EdudziennikLoginWeb::class.java) + .withIsPossible { _, _ -> true } + .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_NOT_NEEDED } +) + +const val LOGIN_TYPE_PODLASIE = 6 +const val LOGIN_MODE_PODLASIE_API = 0 +const val LOGIN_METHOD_PODLASIE_API = 100 +val podlasieLoginMethods = listOf( + LoginMethod(LOGIN_TYPE_PODLASIE, LOGIN_METHOD_PODLASIE_API, PodlasieLoginApi::class.java) + .withIsPossible { _, _ -> true } + .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_NOT_NEEDED } +) + +val templateLoginMethods = listOf( + LoginMethod(LOGIN_TYPE_TEMPLATE, LOGIN_METHOD_TEMPLATE_WEB, TemplateLoginWeb::class.java) + .withIsPossible { _, _ -> true } + .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_NOT_NEEDED }, + + LoginMethod(LOGIN_TYPE_TEMPLATE, LOGIN_METHOD_TEMPLATE_API, TemplateLoginApi::class.java) + .withIsPossible { _, _ -> true } + .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_TEMPLATE_WEB } +) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Mobidziennik.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Mobidziennik.java deleted file mode 100644 index 355b4bbd..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Mobidziennik.java +++ /dev/null @@ -1,2428 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api; - -import android.content.Context; -import android.graphics.Color; -import android.os.AsyncTask; -import android.os.Handler; -import android.text.Html; -import android.util.Pair; -import android.util.SparseArray; -import android.util.SparseIntArray; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import com.crashlytics.android.Crashlytics; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; - -import org.jsoup.Jsoup; -import org.jsoup.nodes.Document; -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import im.wangchao.mhttp.Request; -import im.wangchao.mhttp.Response; -import im.wangchao.mhttp.callback.TextCallbackHandler; -import pl.szczodrzynski.edziennik.App; -import pl.szczodrzynski.edziennik.BuildConfig; -import pl.szczodrzynski.edziennik.R; -import pl.szczodrzynski.edziennik.data.api.interfaces.AttachmentGetCallback; -import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface; -import pl.szczodrzynski.edziennik.data.api.interfaces.LoginCallback; -import pl.szczodrzynski.edziennik.data.api.interfaces.MessageGetCallback; -import pl.szczodrzynski.edziennik.data.api.interfaces.RecipientListGetCallback; -import pl.szczodrzynski.edziennik.data.api.interfaces.SyncCallback; -import pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance; -import pl.szczodrzynski.edziennik.data.db.modules.events.Event; -import pl.szczodrzynski.edziennik.data.db.modules.grades.Grade; -import pl.szczodrzynski.edziennik.data.db.modules.grades.GradeCategory; -import pl.szczodrzynski.edziennik.data.db.modules.lessons.Lesson; -import pl.szczodrzynski.edziennik.data.db.modules.lessons.LessonChange; -import pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore; -import pl.szczodrzynski.edziennik.data.db.modules.luckynumber.LuckyNumber; -import pl.szczodrzynski.edziennik.data.db.modules.messages.Message; -import pl.szczodrzynski.edziennik.data.db.modules.messages.MessageFull; -import pl.szczodrzynski.edziennik.data.db.modules.messages.MessageRecipient; -import pl.szczodrzynski.edziennik.data.db.modules.messages.MessageRecipientFull; -import pl.szczodrzynski.edziennik.data.db.modules.metadata.Metadata; -import pl.szczodrzynski.edziennik.data.db.modules.notices.Notice; -import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile; -import pl.szczodrzynski.edziennik.data.db.modules.profiles.ProfileFull; -import pl.szczodrzynski.edziennik.data.db.modules.subjects.Subject; -import pl.szczodrzynski.edziennik.data.db.modules.teachers.Teacher; -import pl.szczodrzynski.edziennik.data.db.modules.teams.Team; -import pl.szczodrzynski.edziennik.ui.modules.messages.MessagesComposeInfo; -import pl.szczodrzynski.edziennik.utils.models.Date; -import pl.szczodrzynski.edziennik.utils.models.Endpoint; -import pl.szczodrzynski.edziennik.utils.models.Time; -import pl.szczodrzynski.edziennik.utils.models.Week; - -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_INVALID_LOGIN; -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_MAINTENANCE; -import static pl.szczodrzynski.edziennik.data.api.AppError.CODE_OTHER; -import static pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance.TYPE_ABSENT; -import static pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance.TYPE_ABSENT_EXCUSED; -import static pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance.TYPE_BELATED; -import static pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance.TYPE_CUSTOM; -import static pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance.TYPE_PRESENT; -import static pl.szczodrzynski.edziennik.data.db.modules.attendance.Attendance.TYPE_RELEASED; -import static pl.szczodrzynski.edziennik.data.db.modules.events.Event.TYPE_DEFAULT; -import static pl.szczodrzynski.edziennik.data.db.modules.events.Event.TYPE_EXAM; -import static pl.szczodrzynski.edziennik.data.db.modules.events.Event.TYPE_SHORT_QUIZ; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_SEMESTER1_FINAL; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_SEMESTER1_PROPOSED; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_SEMESTER2_FINAL; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_SEMESTER2_PROPOSED; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_YEAR_FINAL; -import static pl.szczodrzynski.edziennik.data.db.modules.grades.Grade.TYPE_YEAR_PROPOSED; -import static pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore.LOGIN_TYPE_MOBIDZIENNIK; -import static pl.szczodrzynski.edziennik.data.db.modules.messages.Message.TYPE_DELETED; -import static pl.szczodrzynski.edziennik.data.db.modules.messages.Message.TYPE_RECEIVED; -import static pl.szczodrzynski.edziennik.data.db.modules.messages.Message.TYPE_SENT; -import static pl.szczodrzynski.edziennik.utils.Utils.bs; -import static pl.szczodrzynski.edziennik.utils.Utils.crc16; -import static pl.szczodrzynski.edziennik.utils.Utils.d; -import static pl.szczodrzynski.edziennik.utils.Utils.monthFromName; -import static pl.szczodrzynski.edziennik.utils.Utils.strToInt; - -public class Mobidziennik implements EdziennikInterface { - public Mobidziennik(App app) { - this.app = app; - } - - private static final String TAG = "api.Mobidziennik"; - private static final String API_KEY = "szkolny_eu_72c7dbc8b97f1e5dd2d118cacf51c2b8543d15c0f65b7a59979adb0a1296b235d7febb826dd2a28688def6efe0811b924b04d7f3c7b7d005354e06dc56815d57"; - - private App app; - private Context activityContext = null; - private SyncCallback callback = null; - private int profileId = -1; - private Profile profile = null; - private LoginStore loginStore = null; - private boolean fullSync = true; - private Date today = Date.getToday(); - private List targetEndpoints = new ArrayList<>(); - - // PROGRESS - private static final int PROGRESS_LOGIN = 10; - private int PROGRESS_COUNT = 1; - private int PROGRESS_STEP = (90/PROGRESS_COUNT); - - private int onlyFeature = FEATURE_ALL; - - private List teamList; - private List teacherList; - private List subjectList; - private List lessonList; - private List lessonChangeList; - private SparseArray gradeAddedDates; - private SparseArray gradeAverages; - private SparseIntArray gradeColors; - private List gradeList; - private List eventList; - private List noticeList; - private List attendanceList; - private List messageList; - private List messageRecipientList; - private List messageRecipientIgnoreList; - private List metadataList; - private List messageMetadataList; - - private static boolean fakeLogin = false && !(BuildConfig.BUILD_TYPE.equals("release")); - private String lastLogin = null; - private long lastLoginTime = 0; - private String lastResponse = null; - private String loginServerName = null; - private String loginUsername = null; - private String loginPassword = null; - private int studentId = -1; - - private long attendanceLastSync = 0; - - private boolean prepare(@NonNull Context activityContext, @NonNull SyncCallback callback, int profileId, @Nullable Profile profile, @NonNull LoginStore loginStore) { - this.activityContext = activityContext; - this.callback = callback; - this.profileId = profileId; - // here we must have a login store: either with a correct ID or -1 - // there may be no profile and that's when onLoginFirst happens - this.profile = profile; - this.loginStore = loginStore; - this.fullSync = profile == null || profile.getEmpty() || profile.shouldFullSync(activityContext); - this.today = Date.getToday(); - - this.loginServerName = loginStore.getLoginData("serverName", ""); - this.loginUsername = loginStore.getLoginData("username", ""); - this.loginPassword = loginStore.getLoginData("password", ""); - if (loginServerName.equals("") || loginUsername.equals("") || loginPassword.equals("")) { - finishWithError(new AppError(TAG, 157, AppError.CODE_INVALID_LOGIN, "Login field is empty")); - return false; - } - this.studentId = profile == null ? -1 : profile.getStudentData("studentId", -1); - this.attendanceLastSync = profile == null ? 0 : profile.getStudentData("attendanceLastSync", (long)0); - fakeLogin = BuildConfig.DEBUG && loginUsername.toLowerCase().startsWith("fake"); - - teamList = profileId == -1 ? new ArrayList<>() : app.db.teamDao().getAllNow(profileId); - teacherList = profileId == -1 ? new ArrayList<>() : app.db.teacherDao().getAllNow(profileId); - subjectList = new ArrayList<>(); - lessonList = new ArrayList<>(); - lessonChangeList = new ArrayList<>(); - gradeAddedDates = new SparseArray<>(); - gradeAverages = new SparseArray<>(); - gradeColors = new SparseIntArray(); - gradeList = new ArrayList<>(); - eventList = new ArrayList<>(); - noticeList = new ArrayList<>(); - attendanceList = new ArrayList<>(); - messageList = new ArrayList<>(); - messageRecipientList = new ArrayList<>(); - messageRecipientIgnoreList = new ArrayList<>(); - metadataList = new ArrayList<>(); - messageMetadataList = new ArrayList<>(); - - return true; - } - - @Override - public void sync(@NonNull Context activityContext, @NonNull SyncCallback callback, int profileId, @Nullable Profile profile, @NonNull LoginStore loginStore) { - if (!prepare(activityContext, callback, profileId, profile, loginStore)) - return; - - login(() -> { - targetEndpoints = new ArrayList<>(); - targetEndpoints.add("GetData"); - targetEndpoints.add("ProcessData"); - targetEndpoints.add("Attendance"); - targetEndpoints.add("ClassCalendar"); - targetEndpoints.add("GradeDetails"); - targetEndpoints.add("NoticeDetails"); - targetEndpoints.add("Messages"); - targetEndpoints.add("MessagesInbox"); - targetEndpoints.add("Finish"); - PROGRESS_COUNT = targetEndpoints.size()-1; - PROGRESS_STEP = (90/PROGRESS_COUNT); - begin(); - }); - } - @Override - public void syncFeature(@NonNull Context activityContext, @NonNull SyncCallback callback, @NonNull ProfileFull profile, @Nullable int ... featureList) { - if (featureList == null) { - sync(activityContext, callback, profile.getId(), profile, LoginStore.fromProfileFull(profile)); - return; - } - if (!prepare(activityContext, callback, profile.getId(), profile, LoginStore.fromProfileFull(profile))) - return; - - login(() -> { - targetEndpoints = new ArrayList<>(); - if (featureList.length == 1) - onlyFeature = featureList[0]; - if (featureList.length == 1 && (featureList[0] == FEATURE_MESSAGES_INBOX || featureList[0] == FEATURE_MESSAGES_OUTBOX)) { - teacherList = app.db.teacherDao().getAllNow(profileId); - for (Teacher teacher: teacherList) { - teachersMap.put((int) teacher.id, teacher.getFullNameLastFirst()); - } - if (featureList[0] == FEATURE_MESSAGES_INBOX) { - targetEndpoints.add("MessagesInbox"); - } - else { - targetEndpoints.add("Messages"); - } - } - else { - // this is needed for all features except messages - targetEndpoints.add("GetData"); - targetEndpoints.add("ProcessData"); - for (int feature: featureList) { - switch (feature) { - case FEATURE_AGENDA: - targetEndpoints.add("ClassCalendar"); - break; - case FEATURE_GRADES: - targetEndpoints.add("GradeDetails"); - break; - case FEATURE_NOTICES: - targetEndpoints.add("NoticeDetails"); - break; - case FEATURE_ATTENDANCE: - targetEndpoints.add("Attendance"); - break; - case FEATURE_MESSAGES_INBOX: - targetEndpoints.add("MessagesInbox"); - break; - case FEATURE_MESSAGES_OUTBOX: - targetEndpoints.add("Messages"); - break; - } - } - } - targetEndpoints.add("Finish"); - PROGRESS_COUNT = targetEndpoints.size()-1; - PROGRESS_STEP = (90/PROGRESS_COUNT); - begin(); - }); - } - - private void begin() { - callback.onProgress(PROGRESS_LOGIN); - - r("get", null); - } - - private void r(String type, String endpoint) { - // endpoint == null when beginning - if (endpoint == null) - endpoint = targetEndpoints.get(0); - int index = -1; - for (String request: targetEndpoints) { - index++; - if (request.equals(endpoint)) { - break; - } - } - if (type.equals("finish")) { - // called when finishing the action - callback.onProgress(PROGRESS_STEP); - index++; - } - d(TAG, "Called r("+type+", "+endpoint+"). Getting "+targetEndpoints.get(index)); - switch (targetEndpoints.get(index)) { - case "GetData": - getData(); - break; - case "ProcessData": - processData(); - break; - case "ClassCalendar": - getClassCalendar(); - break; - case "GradeDetails": - getGradeDetails(); - break; - case "NoticeDetails": - getNoticeDetails(); - break; - case "Attendance": - getAttendance(); - break; - case "Messages": - getAllMessages(); - break; - case "MessagesInbox": - getMessagesInbox(); - break; - case "Finish": - finish(); - break; - } - } - private void saveData() { - if (teamList.size() > 0) { - app.db.teamDao().clear(profileId); - app.db.teamDao().addAll(teamList); - } - if (teacherList.size() > 0) - app.db.teacherDao().addAllIgnore(teacherList); - if (subjectList.size() > 0) - app.db.subjectDao().addAll(subjectList); - if (lessonList.size() > 0) { - app.db.lessonDao().clear(profileId); - app.db.lessonDao().addAll(lessonList); - } - if (lessonChangeList.size() > 0) - app.db.lessonChangeDao().addAll(lessonChangeList); - if (gradeList.size() > 0) { - app.db.gradeDao().clearForSemester(profileId, profile.getCurrentSemester()); - app.db.gradeDao().addAll(gradeList); - app.db.gradeDao().updateDetails(profileId, gradeAverages, gradeAddedDates, gradeColors); - } - if (eventList.size() > 0) { - app.db.eventDao().removeFuture(profileId, today); - app.db.eventDao().addAll(eventList); - } - if (noticeList.size() > 0) { - app.db.noticeDao().clear(profileId); - app.db.noticeDao().addAll(noticeList); - } - if (attendanceList.size() > 0) { - // clear only last two weeks - //app.db.attendanceDao().clearAfterDate(profileId, Date.getToday().stepForward(0, 0, -14)); - app.db.attendanceDao().addAll(attendanceList); - } - if (messageList.size() > 0) - app.db.messageDao().addAllIgnore(messageList); - if (messageRecipientList.size() > 0) - app.db.messageRecipientDao().addAll(messageRecipientList); - if (messageRecipientIgnoreList.size() > 0) - app.db.messageRecipientDao().addAllIgnore(messageRecipientIgnoreList); - if (metadataList.size() > 0) - app.db.metadataDao().addAllIgnore(metadataList); - if (messageMetadataList.size() > 0) - app.db.metadataDao().setSeen(messageMetadataList); - } - private void finish() { - try { - saveData(); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 303, CODE_OTHER, app.getString(R.string.sync_error_saving_data), null, null, e, null)); - } - if (fullSync) { - profile.setLastFullSync(System.currentTimeMillis()); - fullSync = false; - } - profile.setEmpty(false); - callback.onSuccess(activityContext, new ProfileFull(profile, loginStore)); - } - private void finishWithError(AppError error) { - try { - saveData(); - } - catch (Exception e) { - Crashlytics.logException(e); - } - callback.onError(activityContext, error); - } - - /* _ _ - | | (_) - | | ___ __ _ _ _ __ - | | / _ \ / _` | | '_ \ - | |___| (_) | (_| | | | | | - |______\___/ \__, |_|_| |_| - __/ | - |__*/ - private void login(@NonNull LoginCallback loginCallback) { - if (System.currentTimeMillis() - lastLoginTime < 10*60*1000 - && lastLogin.equals(loginServerName+":"+loginUsername)) { - loginCallback.onSuccess(); - return; - } - app.cookieJar.clearForDomain(loginServerName+".mobidziennik.pl"); - - Request.builder() - .url(fakeLogin ? "https://szkolny.eu/mobimobi/mobi_mod_log.php" : "https://"+loginServerName+".mobidziennik.pl/api/") - .userAgent(System.getProperty( "http.agent" )) - .contentType("application/x-www-form-urlencoded; charset=UTF-8") - .addParameter("wersja", "20") - .addParameter("ip", app.deviceId) - .addParameter("login", loginUsername) - .addParameter("haslo", loginPassword) - .addParameter("token", app.appConfig.fcmTokens.get(LOGIN_TYPE_MOBIDZIENNIK).first) - .addParameter("ta_api", API_KEY) - .post() - .callback(new TextCallbackHandler() { - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 333, CODE_OTHER, response, throwable)); - } - - @Override - public void onSuccess(String data, Response response) { - - //app.profile.loggedIn = (data != null && data.equals("ok")); - if (data == null || data.equals("")) { // for safety - finishWithError(new AppError(TAG, 339, CODE_MAINTENANCE, response)); - } - else if (data.equals("Nie jestes zalogowany")) { - finishWithError(new AppError(TAG, 343, AppError.CODE_INVALID_LOGIN, response, data)); - } - else if (data.equals("ifun")) { - finishWithError(new AppError(TAG, 346, AppError.CODE_INVALID_DEVICE, response, data)); - } - else if (data.equals("stare haslo")) { - finishWithError(new AppError(TAG, 349, AppError.CODE_OLD_PASSWORD, response, data)); - } - else if (data.equals("Archiwum")) { - finishWithError(new AppError(TAG, 352, AppError.CODE_ARCHIVED, response, data)); - } - else if (data.equals("Trwają prace techniczne lub pojawił się jakiś problem")) { - finishWithError(new AppError(TAG, 355, CODE_MAINTENANCE, data, response, data)); - } - else if (data.equals("ok")) - { - // a successful login - if (profile != null && studentId != -1) { - lastLogin = loginServerName+":"+loginUsername; - lastLoginTime = System.currentTimeMillis(); - loginCallback.onSuccess(); - return; - } - getData((data1 -> { - String[] tables = data1.split("T@B#LA"); - - List studentIds = new ArrayList<>(); - List studentNamesLong = new ArrayList<>(); - List studentNamesShort = new ArrayList<>(); - String[] student = tables[8].split("\n"); - for (String aStudent : student) { - if (aStudent.isEmpty()) { - continue; - } - String[] student1 = aStudent.split("\\|", Integer.MAX_VALUE); - if (student1.length == 2) - continue; - studentIds.add(strToInt(student1[0])); - studentNamesLong.add(student1[2] + " " + student1[4]); - studentNamesShort.add(student1[2] + " " + student1[4].charAt(0) + "."); - } - - List profileList = new ArrayList<>(); - - for (int index = 0; index < studentIds.size(); index++) { - Profile profile = new Profile(); - profile.setStudentNameLong(studentNamesLong.get(index)); - profile.setStudentNameShort(studentNamesShort.get(index)); - profile.setName(profile.getStudentNameLong()); - profile.setSubname(loginUsername); - profile.setEmpty(true); - profile.setLoggedIn(true); - profile.putStudentData("studentId", studentIds.get(index)); - profileList.add(profile); - } - - callback.onLoginFirst(profileList, loginStore); - })); - } - else { - if (data.contains("Uuuups... nieprawidłowy adres")) { - finishWithError(new AppError(TAG, 404, AppError.CODE_INVALID_SERVER_ADDRESS, response, data)); - return; - } - finishWithError(new AppError(TAG, 407, AppError.CODE_MAINTENANCE, response, data)); - } - } - }) - .build() - .enqueue(); - } - - /* _ _ _ _ _ _ _ - | | | | | | ___ | | | | | | - | |__| | ___| |_ __ ___ _ __ ___ ( _ ) ___ __ _| | | |__ __ _ ___| | _____ - | __ |/ _ \ | '_ \ / _ \ '__/ __| / _ \/\ / __/ _` | | | '_ \ / _` |/ __| |/ / __| - | | | | __/ | |_) | __/ | \__ \ | (_> < | (_| (_| | | | |_) | (_| | (__| <\__ \ - |_| |_|\___|_| .__/ \___|_| |___/ \___/\/ \___\__,_|_|_|_.__/ \__,_|\___|_|\_\___/ - | | - |*/ - private interface GetDataCallback { - void onSuccess(String data); - } - private void getData(GetDataCallback getDataCallback) { - callback.onActionStarted(R.string.sync_action_syncing); - Request.builder() - .url(fakeLogin ? "https://szkolny.eu/mobimobi/mobi_mod.php?"+System.currentTimeMillis() : "https://"+ loginServerName +".mobidziennik.pl/api/zrzutbazy") - .userAgent(System.getProperty( "http.agent" )) - .callback(new TextCallbackHandler() { - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 427, CODE_OTHER, response, throwable)); - } - - @Override - public void onSuccess(String data, Response response) { - if (data == null || data.equals("")) { - finishWithError(new AppError(TAG, 432, CODE_MAINTENANCE, response)); - return; - } - if (data.equals("Nie jestes zalogowany")) { - finishWithError(new AppError(TAG, 437, CODE_INVALID_LOGIN, response, data)); - lastLoginTime = 0; - return; - } - - lastResponse = data; - - getDataCallback.onSuccess(data); - } - }) - .build() - .enqueue(); - } - private void getData() { - getData((data -> r("finish", "GetData"))); - } - - /* _____ _ _____ _ - | __ \ | | | __ \ | | - | | | | __ _| |_ __ _ | |__) |___ __ _ _ _ ___ ___| |_ ___ - | | | |/ _` | __/ _` | | _ // _ \/ _` | | | |/ _ \/ __| __/ __| - | |__| | (_| | || (_| | | | \ \ __/ (_| | |_| | __/\__ \ |_\__ \ - |_____/ \__,_|\__\__,_| |_| \_\___|\__, |\__,_|\___||___/\__|___/ - | | - |*/ - private void processData() { - callback.onActionStarted(R.string.sync_action_processing_data); - String[] tables = lastResponse.split("T@B#LA"); - - if (studentId == -1) { - return; - } - try { - int i = 0; - for (String table : tables) { - if (i == 0) { - processUsers(table); - } - if (i == 3) { - processDates(table); - } - if (i == 4) { - processSubjects(table); - } - if (i == 7) { - processTeams(table, null); - } - if (i == 8) { - processStudent(table, loginUsername); - } - if (i == 9) { - processTeams(null, table); - } - if (i == 14) { - processGradeCategories(table); - } - if (i == 15) { - processLessons(table); - } - if (i == 16) { - processAttendance(table); - } - if (i == 17) { - processNotices(table); - } - if (i == 18) { - processGrades(table); - } - if (i == 21) { - processEvents(table); - } - if (i == 23) { - processHomework(table); - } - if (i == 24) { - processTimetable(table); - } - i++; - } - r("finish", "ProcessData"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 511, CODE_OTHER, e, lastResponse)); - } - } - - private void getClassCalendar() { - callback.onActionStarted(R.string.sync_action_syncing_calendar); - Request.builder() - .url(fakeLogin ? "https://szkolny.eu/mobimobi/mobi_mod_kalendarzklasowy.php" : "https://" + loginServerName + ".mobidziennik.pl/dziennik/kalendarzklasowy") - .userAgent(System.getProperty("http.agent")) - .callback(new TextCallbackHandler() { - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 523, CODE_OTHER, response, throwable)); - } - - @Override - public void onSuccess(String data, Response response) { - // just skip any failures here - if (data == null || data.equals("")) { - r("finish", "ClassCalendar"); - return; - } - if (data.contains("nie-pamietam-hasla")) { - r("finish", "ClassCalendar"); - return; - } - - if (profile.getLuckyNumberEnabled() - && (profile.getLuckyNumberDate() == null || profile.getLuckyNumberDate().getValue() != Date.getToday().getValue() || profile.getLuckyNumber() == -1)) { - // set the current date as we checked the lucky number today - profile.setLuckyNumber(-1); - profile.setLuckyNumberDate(Date.getToday()); - - Matcher matcher = Pattern.compile("class=\"szczesliwy_numerek\".*>0*([0-9]+)(?:/0*[0-9]+)*", Pattern.DOTALL).matcher(data); - if (matcher.find()) { - try { - profile.setLuckyNumber(Integer.parseInt(matcher.group(1))); - } catch (Exception e3) { - e3.printStackTrace(); - } - } - app.db.luckyNumberDao().add(new LuckyNumber(profileId, profile.getLuckyNumberDate(), profile.getLuckyNumber())); - } - - Matcher matcher = Pattern.compile("events: (.+),$", Pattern.MULTILINE).matcher(data); - if (matcher.find()) { - try { - //d(TAG, matcher.group(1)); - JsonArray events = new JsonParser().parse(matcher.group(1)).getAsJsonArray(); - //d(TAG, "Events size "+events.size()); - for (JsonElement eventEl: events) { - JsonObject event = eventEl.getAsJsonObject(); - - //d(TAG, "Event "+event.toString()); - - JsonElement idEl = event.get("id"); - String idStr; - if (idEl != null && (idStr = idEl.getAsString()).startsWith("kalendarz;")) { - String[] idParts = idStr.split(";", Integer.MAX_VALUE); - if (idParts.length > 2) { - long id = idParts[2].isEmpty() ? -1 : strToInt(idParts[2]); - long targetStudentId = strToInt(idParts[1]); - if (targetStudentId != studentId) - continue; - - // TODO null-safe getAs..() - Date eventDate = Date.fromY_m_d(event.get("start").getAsString()); - //if (eventDate.getValue() < today.getValue()) - // continue; - - String eventColor = event.get("color").getAsString(); - - int eventType = Event.TYPE_INFORMATION; - - switch (eventColor) { - case "#C54449": - case "#c54449": - eventType = Event.TYPE_SHORT_QUIZ; - break; - case "#AB0001": - case "#ab0001": - eventType = Event.TYPE_EXAM; - break; - case "#008928": - eventType = Event.TYPE_CLASS_EVENT; - break; - case "#b66000": - case "#B66000": - eventType = Event.TYPE_EXCURSION; - break; - } - - String title = event.get("title").getAsString(); - String comment = event.get("comment").getAsString(); - - String topic = title; - if (!title.equals(comment)) { - topic += "\n"+comment; - } - - if (id == -1) { - id = crc16(topic.getBytes()); - } - - Event eventObject = new Event( - profileId, - id, - eventDate, - null, - topic, - -1, - eventType, - false, - -1, - -1, - teamClass != null ? teamClass.id : -1 - ); - - - //d(TAG, "Event "+eventObject); - eventList.add(eventObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_EVENT, eventObject.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis() /* no addedDate here though */)); - } - } - } - r("finish", "ClassCalendar"); - } catch (Exception e3) { - finishWithError(new AppError(TAG, 638, CODE_OTHER, response, e3, data)); - } - } - else { - r("finish", "ClassCalendar"); - } - } - }) - .build() - .enqueue(); - } - - private void getGradeDetails() { - callback.onActionStarted(R.string.sync_action_syncing_grade_details); - Request.builder() - .url(fakeLogin ? "https://szkolny.eu/mobimobi/mobi_mod_oceny.php" : "https://" + loginServerName + ".mobidziennik.pl/dziennik/oceny?semestr="+ profile.getCurrentSemester()) - .userAgent(System.getProperty("http.agent")) - .callback(new TextCallbackHandler() { - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 658, CODE_OTHER, response, throwable)); - } - - @Override - public void onSuccess(String data, Response response) { - // just skip any failures here - if (data == null || data.equals("")) { - r("finish", "GradeDetails"); - return; - } - if (data.contains("nie-pamietam-hasla")) { - r("finish", "GradeDetails"); - return; - } - - try { - Document doc = Jsoup.parse(data); - - Elements grades = doc.select("table.spis a, table.spis span, table.spis div"); - - String gradeCategory = ""; - int gradeColor = -1; - String subjectName = ""; - - for (Element e: grades) { - switch (e.tagName()) { - case "div": { - //d(TAG, "Outer HTML "+e.outerHtml()); - Matcher matcher = Pattern.compile("\\n*\\s*(.+?)\\s*\\n*(?:<.*?)??", Pattern.DOTALL).matcher(e.outerHtml()); - if (matcher.find()) { - subjectName = matcher.group(1); - } - break; - } - case "span": { - String css = e.attr("style"); - Matcher matcher = Pattern.compile("background-color:([#A-Fa-f0-9]+);", Pattern.DOTALL).matcher(css); - if (matcher.find()) { - gradeColor = Color.parseColor(matcher.group(1)); - } - matcher = Pattern.compile("> (.+?):", Pattern.DOTALL).matcher(e.outerHtml()); - if (matcher.find()) { - gradeCategory = matcher.group(1); - } - break; - } - case "a": { - int gradeId = strToInt(e.attr("rel")); - float gradeClassAverage = -1; - Date gradeAddedDate = null; - long gradeAddedDateMillis = -1; - - String html = e.html(); - Matcher matcher = Pattern.compile("Średnia ocen:.*([0-9]*\\.?[0-9]*)", Pattern.DOTALL).matcher(html); - if (matcher.find()) { - gradeClassAverage = Float.parseFloat(matcher.group(1)); - } - - matcher = Pattern.compile("Wpisano:.*.+?,\\s([0-9]+)\\s(.+?)\\s([0-9]{4}),\\sgodzina\\s([0-9:]+)", Pattern.DOTALL).matcher(html); - int month = 1; - if (matcher.find()) { - switch (matcher.group(2)) { - case "stycznia": - month = 1; - break; - case "lutego": - month = 2; - break; - case "marca": - month = 3; - break; - case "kwietnia": - month = 4; - break; - case "maja": - month = 5; - break; - case "czerwca": - month = 6; - break; - case "lipca": - month = 7; - break; - case "sierpnia": - month = 8; - break; - case "września": - month = 9; - break; - case "października": - month = 10; - break; - case "listopada": - month = 11; - break; - case "grudnia": - month = 12; - break; - } - gradeAddedDate = new Date( - strToInt(matcher.group(3)), - month, - strToInt(matcher.group(1)) - ); - Time time = Time.fromH_m_s( - matcher.group(4) - ); - gradeAddedDateMillis = gradeAddedDate.combineWith(time); - } - - matcher = Pattern.compile("Liczona do średniej:.*?nie
    ", Pattern.DOTALL).matcher(html); - if (matcher.find()) { - matcher = Pattern.compile("(.+?).*?.+?.*?\\((.+?)\\).*?.*?Wartość oceny:.*?([0-9.]+).*?Wpisał\\(a\\):.*?(.+?)", Pattern.DOTALL).matcher(html); - if (matcher.find()) { - String gradeName = matcher.group(1); - String gradeDescription = matcher.group(2); - float gradeValue = Float.parseFloat(matcher.group(3)); - String teacherName = matcher.group(4); - - long teacherId = -1; - long subjectId = -1; - - //d(TAG, "Grade "+gradeName+" "+gradeCategory+" subject "+subjectName+" teacher "+teacherName); - - if (!subjectName.equals("")) { - int subjectIndex = -1; - for (int i = 0; i < subjectsMap.size(); i++) { - if (subjectsMap.valueAt(i).equals(subjectName)) { - subjectIndex = i; - } - } - //d(TAG, "subjectIndex "+subjectIndex); - if (subjectIndex >= 0 && subjectIndex < subjectsMap.size()) { - subjectId = subjectsMap.keyAt(subjectIndex); - } - } - - if (!teacherName.equals("")) { - //d(TAG, "teacherName "+teacherName); - int teacherIndex = -1; - for (int i = 0; i < teachersMap.size(); i++) { - if (teachersMap.valueAt(i).equals(teacherName)) { - teacherIndex = i; - } - } - //d(TAG, "teacherIndex "+teacherIndex); - if (teacherIndex >= 0 && teacherIndex < teachersMap.size()) { - teacherId = teachersMap.keyAt(teacherIndex); - } - } - - int semester = profile.dateToSemester(gradeAddedDate); - - Grade gradeObject = new Grade( - profileId, - gradeId, - gradeCategory, - gradeColor, - "NLDŚR, "+gradeDescription, - gradeName, - gradeValue, - 0, - semester, - teacherId, - subjectId - ); - - gradeObject.classAverage = gradeClassAverage; - - gradeList.add(gradeObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_GRADE, gradeObject.id, profile.getEmpty(), profile.getEmpty(), gradeAddedDateMillis)); - } - } else { - gradeAverages.put(gradeId, gradeClassAverage); - gradeAddedDates.put(gradeId, gradeAddedDateMillis); - gradeColors.put(gradeId, gradeColor); - } - break; - } - } - } - - r("finish", "GradeDetails"); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 852, CODE_OTHER, response, e, data)); - } - } - }) - .build() - .enqueue(); - } - - // TODO: 2019-06-04 punkty z zachowania znikają po synchronizacji - private void getNoticeDetails() { - if (noticeList.size() == 0) { - r("finish", "NoticeDetails"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_notice_details); - Request.builder() - .url(fakeLogin ? "https://szkolny.eu/mobimobi/mobi_mod_zachowanie.php" : "https://" + loginServerName + ".mobidziennik.pl/mobile/zachowanie") - .userAgent(System.getProperty("http.agent")) - .callback(new TextCallbackHandler() { - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 873, CODE_OTHER, response, throwable)); - } - - @Override - public void onSuccess(String data, Response response) { - // just skip any failures here - if (data == null || data.equals("")) { - r("finish", "NoticeDetails"); - return; - } - if (data.contains("nie-pamietam-hasla")) { - r("finish", "NoticeDetails"); - return; - } - - Matcher matcher = Pattern.compile("(?:([0-9-.,]+).+?)?
    .+?Treść:.+?(?:Kategoria: (.+?).+?)?Czas", Pattern.DOTALL).matcher(data); - while (matcher.find()) { - try { - String pointsStr = matcher.group(1); - String idStr = matcher.group(2); - String categoryStr = matcher.groupCount() == 3 ? matcher.group(3) : null; - float points = pointsStr == null ? 0 : Float.parseFloat(pointsStr); - long id = Long.parseLong(idStr); - for (Notice notice: noticeList) { - if (notice.id != id) - continue; - notice.points = points; - notice.category = categoryStr; - } - } catch (Exception e) { - Crashlytics.logException(e); - e.printStackTrace(); - if (onlyFeature == FEATURE_NOTICES) - finishWithError(new AppError(TAG, 880, CODE_OTHER, response, e, data)); - else - r("finish", "NoticeDetails"); - return; - } - } - r("finish", "NoticeDetails"); - } - }) - .build() - .enqueue(); - } - - public static class AttendanceLessonRange { - int weekDay; - int lessonNumber; - Time startTime; - Time endTime; - List lessons; - - public AttendanceLessonRange(int section, int number, int lessonNumber, Time startTime, Time endTime) { - this.weekDay = section == 1 ? number + 4 : number; - this.lessonNumber = lessonNumber; - this.startTime = startTime; - this.endTime = endTime; - this.lessons = new ArrayList<>(); - } - public void addLesson(AttendanceLesson lesson) { - lessons.add(lesson); - } - } - public static class AttendanceLesson { - String subjectName; - String topic; - String teamName; - String teacherName; - long lessonId; - - public AttendanceLesson(String subjectName, String topic, String teamName, String teacherName, long lessonId) { - this.subjectName = subjectName; - this.topic = topic; - this.teamName = teamName; - this.teacherName = teacherName; - this.lessonId = lessonId; - } - } - private Date attendanceCheckDate = Week.getWeekStart(); - private void getAttendance() { - r("finish", "Attendance"); - // TODO: 2019-09-10 please download attendance from /dziennik/frekwencja. /mobile does not work above v13.0 - if (true) { - return; - } - callback.onActionStarted(R.string.sync_action_syncing_attendance); - d(TAG, "Get attendance for week "+ attendanceCheckDate.getStringY_m_d()); - Request.builder() - .url(fakeLogin ? "https://szkolny.eu/mobimobi/mobi_mod_frekwencja.php" : "https://" + loginServerName + ".mobidziennik.pl/mobile/frekwencja") - .userAgent(System.getProperty("http.agent")) - .addParameter("uczen", studentId) - .addParameter("data_poniedzialek", attendanceCheckDate.getStringY_m_d()) - .post() - .callback(new TextCallbackHandler() { - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 944, CODE_OTHER, response, throwable)); - } - - @Override - public void onSuccess(String data, Response response) { - // just skip any failures here - if (data == null || data.equals("")) { - r("finish", "Attendance"); - return; - } - if (data.contains("nie-pamietam-hasla")) { - r("finish", "Attendance"); - return; - } - - List ranges = new ArrayList<>(); - - try { - Matcher matcher = Pattern.compile("
    .*?

    ([0-9]{2}):([0-9]{2}) - ([0-9]{2}):([0-9]{2}) (.+?)\\s*?

    .*?

    ", Pattern.DOTALL).matcher(data); - while (matcher.find()) { - int section = strToInt(matcher.group(1)); - int number = strToInt(matcher.group(2)); - int lessonNumber = strToInt(matcher.group(3)); - int startHour = strToInt(matcher.group(4)); - int startMinute = strToInt(matcher.group(5)); - int endHour = strToInt(matcher.group(6)); - int endMinute = strToInt(matcher.group(7)); - String lessonsString = matcher.group(8); - AttendanceLessonRange range = new AttendanceLessonRange(section, number, lessonNumber, new Time(startHour, startMinute, 0), new Time(endHour, endMinute, 0)); - Matcher matcher2 = Pattern.compile("(.+?) - (.+?)??.+?.+?\\(([0-9]{1,2}) (.+?),\\s+(.+?), id lekcji: ([0-9]+?)\\).+?", Pattern.DOTALL).matcher(lessonsString); - while (matcher2.find()) { - String topic = matcher2.group(2); - topic = topic == null ? "" : Html.fromHtml(topic).toString(); - if (topic.startsWith("Lekcja odwołana:")) - continue; - String teamName = matcher2.group(3)+matcher2.group(4); - boolean notFound = true; - for (Team team: teamList) { - if (teamName.equals(team.name)) { - notFound = false; - break; - } - } - if (notFound) - continue; - range.addLesson( - new AttendanceLesson( - matcher2.group(1), - topic, - teamName, - matcher2.group(5), - strToInt(matcher2.group(6)) - ) - ); - } - ranges.add(range); - } - matcher = Pattern.compile("([.|sz+]+)?", Pattern.DOTALL).matcher(data); - int index = 0; - while (matcher.find()) { - int currentIndex = index++; - String markers = matcher.groupCount() == 1 ? matcher.group(1) : null; - if (markers == null) - continue; - AttendanceLessonRange range = ranges.get(currentIndex); - - Date date = attendanceCheckDate.clone().stepForward(0, 0, range.weekDay); - long addedDate = date.combineWith(range.startTime); - - int markerIndex = 0; - for (char marker: markers.toCharArray()) { - int type = TYPE_CUSTOM; - switch (marker) { - case '.': - type = TYPE_PRESENT; - break; - case '|': - type = TYPE_ABSENT; - break; - case 's': - type = TYPE_BELATED; - break; - case 'z': - type = TYPE_RELEASED; - break; - case '+': - type = TYPE_ABSENT_EXCUSED; - } - AttendanceLesson lesson; - if (markerIndex >= range.lessons.size()) { - lesson = new AttendanceLesson("", "Nieznana lekcja", "???", "", addedDate); - } - else { - lesson = range.lessons.get(markerIndex); - } - - long teacherId = -1; - long subjectId = -1; - - int teacherIndex = -1; - for (int i = 0; i < teachersMap.size(); i++) { - if (teachersMap.valueAt(i).equals(lesson.teacherName)) { - teacherIndex = i; - } - } - if (teacherIndex >= 0 && teacherIndex < teachersMap.size()) { - teacherId = teachersMap.keyAt(teacherIndex); - } - - int subjectIndex = -1; - for (int i = 0; i < subjectsMap.size(); i++) { - if (subjectsMap.valueAt(i).equals(lesson.subjectName)) { - subjectIndex = i; - } - } - if (subjectIndex >= 0 && subjectIndex < subjectsMap.size()) { - subjectId = subjectsMap.keyAt(subjectIndex); - } - - Attendance attendanceObject = new Attendance( - profileId, - lesson.lessonId, - teacherId, - subjectId, - profile.dateToSemester(date), - lesson.topic, - date, - range.startTime, - type); - markerIndex++; - attendanceList.add(attendanceObject); - if (attendanceObject.type != TYPE_PRESENT) { - boolean markAsRead = onlyFeature == FEATURE_ATTENDANCE && attendanceLastSync == 0; - metadataList.add(new Metadata(profileId, Metadata.TYPE_ATTENDANCE, attendanceObject.id, profile.getEmpty() || markAsRead, profile.getEmpty() || markAsRead, addedDate)); - } - } - } - } catch (Exception e) { - Crashlytics.logException(e); - e.printStackTrace(); - if (onlyFeature == FEATURE_ATTENDANCE) - finishWithError(new AppError(TAG, 955, CODE_OTHER, response, e, data)); - else - r("finish", "Attendance"); - return; - } - - if (onlyFeature == FEATURE_ATTENDANCE) { - // syncing attendance exclusively - if (attendanceLastSync == 0) { - // first sync - get attendance until it's start of the school year - attendanceLastSync = profile.getSemesterStart(1).getInMillis(); - } - Date lastSyncDate = Date.fromMillis(attendanceLastSync); - lastSyncDate.stepForward(0, 0, -7); - if (lastSyncDate.getValue() < attendanceCheckDate.getValue()) { - attendanceCheckDate.stepForward(0, 0, -7); - r("get", "Attendance"); - } - else { - profile.putStudentData("attendanceLastSync", System.currentTimeMillis()); - r("finish", "Attendance"); - } - } - else { - if (attendanceLastSync != 0) { - // not a first sync - Date lastSyncDate = Date.fromMillis(attendanceLastSync); - lastSyncDate.stepForward(0, 0, 2); - if (lastSyncDate.getValue() >= attendanceCheckDate.getValue()) { - profile.putStudentData("attendanceLastSync", System.currentTimeMillis()); - } - } - r("finish", "Attendance"); - } - } - }) - .build() - .enqueue(); - } - - private void getAllMessages() { - if (!fullSync && onlyFeature != FEATURE_MESSAGES_OUTBOX) { - r("finish", "Messages"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_messages); - Request.builder() - .url(fakeLogin ? "https://szkolny.eu/mobimobi/mobi_mod_wiadomosci_szukaj.php" : "https://" + loginServerName + ".mobidziennik.pl/dziennik/wyszukiwarkawiadomosci?q=+") - .userAgent(System.getProperty("http.agent")) - .callback(new TextCallbackHandler() { - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 1012, CODE_OTHER, response, throwable)); - } - - @Override - public void onSuccess(String data, Response response) { - // just skip any failures here - if (data == null || data.equals("")) { - r("finish", "GradeDetails"); - return; - } - if (data.contains("nie-pamietam-hasla")) { - r("finish", "GradeDetails"); - return; - } - - try { - long startTime = System.currentTimeMillis(); - Document doc = Jsoup.parse(data); - - Element listElement = doc.getElementsByClass("spis").first(); - if (listElement == null) { - r("finish", "Messages"); - return; - } - Elements list = listElement.getElementsByClass("podswietl"); - for (Element item: list) { - long id = Long.parseLong(item.attr("rel").replaceAll("[^\\d]", "" )); - - Element subjectEl = item.select("td:eq(0) div").first(); - String subject = subjectEl.text(); - - Element addedDateEl = item.select("td:eq(1)").first(); - String addedDateStr = addedDateEl.text(); - long addedDate = Date.fromIsoHm(addedDateStr); - - Element typeEl = item.select("td:eq(2) img").first(); - int type = TYPE_RECEIVED; - if (typeEl.outerHtml().contains("mail_send.png")) - type = TYPE_SENT; - - Element senderEl = item.select("td:eq(3) div").first(); - long senderId = -1; - if (type == TYPE_RECEIVED) { - String senderName = senderEl.text(); - for (int i = 0; i < teachersMap.size(); i++) { - if (senderName.equals(teachersMap.valueAt(i))) { - senderId = teachersMap.keyAt(i); - break; - } - } - messageRecipientList.add(new MessageRecipient(profileId, -1, id)); - } - else { - // TYPE_SENT, so multiple recipients possible - String[] recipientNames = senderEl.text().split(", "); - for (String recipientName: recipientNames) { - long recipientId = -1; - for (int i = 0; i < teachersMap.size(); i++) { - if (recipientName.equals(teachersMap.valueAt(i))) { - recipientId = teachersMap.keyAt(i); - break; - } - } - messageRecipientIgnoreList.add(new MessageRecipient(profileId, recipientId, id)); - } - } - - Message message = new Message( - profileId, - id, - subject, - null, - type, - senderId, - -1 - ); - - messageList.add(message); - metadataList.add(new Metadata(profileId, Metadata.TYPE_MESSAGE, message.id, true, true, addedDate)); - } - - } catch (Exception e3) { - finishWithError(new AppError(TAG, 949, CODE_OTHER, response, e3, data)); - return; - } - - r("finish", "Messages"); - } - }) - .build() - .enqueue(); - } - - private void getMessagesInbox() { - callback.onActionStarted(R.string.sync_action_syncing_messages); - Request.builder() - .url(fakeLogin ? "https://szkolny.eu/mobimobi/mobi_mod_wiadomosci.php" : "https://" + loginServerName + ".mobidziennik.pl/dziennik/wiadomosci") - .userAgent(System.getProperty("http.agent")) - .callback(new TextCallbackHandler() { - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 972, CODE_OTHER, response, throwable)); - } - - @Override - public void onSuccess(String data, Response response) { - // just skip any failures here - if (data == null || data.equals("")) { - r("finish", "GradeDetails"); - return; - } - if (data.contains("nie-pamietam-hasla")) { - r("finish", "GradeDetails"); - return; - } - - try { - if (data.contains("Brak wiadomości odebranych.")) { - r("finish", "MessagesInbox"); - return; - } - Document doc = Jsoup.parse(data); - - Elements list = doc.getElementsByClass("spis").first().getElementsByClass("podswietl"); - for (Element item: list) { - long id = Long.parseLong(item.attr("rel")); - - Element subjectEl = item.select("td:eq(0)").first(); - //d(TAG, "subjectEl "+subjectEl.outerHtml()); - boolean hasAttachments = false; - if (subjectEl.getElementsByTag("a").size() != 0) { - hasAttachments = true; - } - String subject = subjectEl.ownText(); - - Element addedDateEl = item.select("td:eq(1) small").first(); - //d(TAG, "addedDateEl "+addedDateEl.outerHtml()); - String addedDateStr = addedDateEl.text(); - long addedDate = Date.fromIsoHm(addedDateStr); - - Element senderEl = item.select("td:eq(2)").first(); - //d(TAG, "senderEl "+senderEl.outerHtml()); - String senderName = senderEl.ownText(); - long senderId = -1; - for (int i = 0; i < teachersMap.size(); i++) { - if (senderName.equals(teachersMap.valueAt(i))) { - senderId = teachersMap.keyAt(i); - break; - } - } - messageRecipientIgnoreList.add(new MessageRecipient(profileId, -1, id)); - - boolean isRead = item.select("td:eq(3) span").first().hasClass("wiadomosc_przeczytana"); - - Message message = new Message( - profileId, - id, - subject, - null, - TYPE_RECEIVED, - senderId, - -1 - ); - - if (hasAttachments) - message.setHasAttachments(); - - - messageList.add(message); - messageMetadataList.add(new Metadata(profileId, Metadata.TYPE_MESSAGE, message.id, isRead, isRead || profile.getEmpty(), addedDate)); - } - r("finish", "MessagesInbox"); - } catch (Exception e3) { - finishWithError(new AppError(TAG, 1044, CODE_OTHER, response, e3, data)); - } - } - }) - .build() - .enqueue(); - } - - private SparseArray teachersMap = new SparseArray<>(); - private void processUsers(String table) - { - String[] users = table.split("\n"); - - //app.db.teacherDao().clear(profileId); - for (String userStr: users) - { - if (userStr.isEmpty()) { - continue; - } - String[] user = userStr.split("\\|", Integer.MAX_VALUE); - - teachersMap.put(strToInt(user[0]), user[5].trim()+" "+user[4].trim()); - teacherList.add(new Teacher(profileId, strToInt(user[0]), user[4].trim(), user[5].trim())); - } - } - - private void processDates(String table) - { - String[] dates = table.split("\n"); - for (String dateStr: dates) - { - if (dateStr.isEmpty()) { - continue; - } - String[] date = dateStr.split("\\|", Integer.MAX_VALUE); - switch (date[1]) { - case "semestr1_poczatek": - profile.setDateSemester1Start(Date.fromYmd(date[3])); - break; - case "semestr2_poczatek": - profile.setDateSemester2Start(Date.fromYmd(date[3])); - break; - case "koniec_roku_szkolnego": - profile.setDateYearEnd(Date.fromYmd(date[3])); - break; - } - } - } - - private SparseArray subjectsMap = new SparseArray<>(); - private void processSubjects(String table) - { - String[] subjects = table.split("\n"); - - // because a student may no longer have a subject - // which he had before - // therefore, this subject's grades do not get deleted - // so we should keep the subject for correct naming - //app.db.subjectDao().clear(profileId); - for (String subjectStr: subjects) - { - if (subjectStr.isEmpty()) { - continue; - } - String[] subject = subjectStr.split("\\|", Integer.MAX_VALUE); - - subjectsMap.put(strToInt(subject[0]), subject[1]); - subjectList.add(new Subject(profileId, strToInt(subject[0]), subject[1], subject[2])); - } - } - - private Team teamClass = null; - private SparseArray teamsMap = new SparseArray<>(); - private List allTeams = new ArrayList<>(); - private void processTeams(String tableTeams, String tableRelations) - { - if (tableTeams != null) - { - allTeams.clear(); - String[] teams = tableTeams.split("\n"); - for (String teamStr: teams) { - if (teamStr.isEmpty()) { - continue; - } - String[] team = teamStr.split("\\|", Integer.MAX_VALUE); - Team teamObject = new Team( - profileId, - strToInt(team[0]), - team[1]+team[2], - strToInt(team[3]), - loginServerName+":"+team[1]+team[2],// TODO zrobiłem to na szybko - strToInt(team[4], -1)); - allTeams.add(teamObject); - } - } - if (tableRelations != null) - { - app.db.teamDao().clear(profileId); - String[] teams = tableRelations.split("\n"); - for (String teamStr: teams) { - if (teamStr.isEmpty()) { - continue; - } - String[] team = teamStr.split("\\|", Integer.MAX_VALUE); - if (strToInt(team[1]) != studentId) - continue; - Team teamObject = Team.getById(allTeams, strToInt(team[2])); - if (teamObject != null) { - if (teamObject.type == 1) { - profile.setStudentNumber(strToInt(team[4])); - teamClass = teamObject; - } - teamsMap.put((int)teamObject.id, teamObject.name); - teamList.add(teamObject); - } - } - } - } - - private SparseArray> students = new SparseArray<>(); - private boolean processStudent(String table, String loginUsername) - { - students.clear(); - String[] student = table.split("\n"); - for (int i = 0; i < student.length; i++) { - if (student[i].isEmpty()) { - continue; - } - String[] student1 = student[i].split("\\|", Integer.MAX_VALUE); - String[] student2 = student[++i].split("\\|", Integer.MAX_VALUE); - students.put(strToInt(student1[0]), new Pair<>(student1, student2)); - } - Pair studentData = students.get(studentId); - try { - profile.setAttendancePercentage(Float.parseFloat(studentData.second[1])); - } - catch (Exception e) { - e.printStackTrace(); - } - return true; - } - - private SparseArray gradeCategoryList = new SparseArray<>(); - private void processGradeCategories(String table) - { - String[] gradeCategories = table.split("\n"); - - for (String gradeCategoryStr: gradeCategories) - { - if (gradeCategoryStr.isEmpty()) { - continue; - } - String[] gradeCategory = gradeCategoryStr.split("\\|", Integer.MAX_VALUE); - List columns = new ArrayList<>(); - Collections.addAll(columns, gradeCategory[7].split(";")); - - if (teamsMap.indexOfKey(strToInt(gradeCategory[1])) >= 0) { - gradeCategoryList.put( - Integer.parseInt(gradeCategory[0]), - new GradeCategory( - profileId, - Integer.parseInt(gradeCategory[0]), - Float.parseFloat(gradeCategory[3]), - Color.parseColor("#"+gradeCategory[6]), - gradeCategory[4] - ).addColumns(columns) - ); - } - } - } - - private class MobiLesson { - long id; - int subjectId; - int teacherId; - int teamId; - String topic; - Date date; - Time startTime; - Time endTime; - int presentCount; - int absentCount; - int lessonNumber; - String signed; - - MobiLesson(long id, int subjectId, int teacherId, int teamId, String topic, Date date, Time startTime, Time endTime, int presentCount, int absentCount, int lessonNumber, String signed) { - this.id = id; - this.subjectId = subjectId; - this.teacherId = teacherId; - this.teamId = teamId; - this.topic = topic; - this.date = date; - this.startTime = startTime; - this.endTime = endTime; - this.presentCount = presentCount; - this.absentCount = absentCount; - this.lessonNumber = lessonNumber; - this.signed = signed; - } - } - - private List mobiLessons = new ArrayList<>(); - - private MobiLesson getLesson(long id) { - for (MobiLesson mobiLesson : mobiLessons) { - if (mobiLesson.id == id) - return mobiLesson; - } - return null; - } - - private void processLessons(String table) - { - mobiLessons.clear(); - - String[] lessons2 = table.split("\n"); - for (String lessonStr: lessons2) - { - if (lessonStr.isEmpty()) { - continue; - } - String[] lesson = lessonStr.split("\\|", Integer.MAX_VALUE); - - MobiLesson newMobiLesson = new MobiLesson( - Long.parseLong(lesson[0]), - strToInt(lesson[1]), - strToInt(lesson[2]), - strToInt(lesson[3]), - lesson[4], - Date.fromYmd(lesson[5]), - Time.fromYmdHm(lesson[6]), - Time.fromYmdHm(lesson[7]), - strToInt(lesson[8]), - strToInt(lesson[9]), - strToInt(lesson[10]), - lesson[11]); - mobiLessons.add(newMobiLesson); - } - } - - private void processAttendance(String table) - { - if (true) - return; - String[] attendanceList = table.split("\n"); - for (String attendanceStr: attendanceList) - { - if (attendanceStr.isEmpty()) { - continue; - } - String[] attendance = attendanceStr.split("\\|", Integer.MAX_VALUE); - - if (strToInt(attendance[2]) != studentId) - continue; - //RegisterAttendance oldAttendance = RegisterAttendance.getById(oldAttendances, Long.parseLong(attendance[0])); - - MobiLesson mobiLesson = getLesson(Long.parseLong(attendance[1])); - if (mobiLesson != null) { - int type = TYPE_PRESENT; - switch (attendance[4]) { - case "2": - type = TYPE_ABSENT; - break; - case "5": - type = TYPE_ABSENT_EXCUSED; - break; - case "4": - type = TYPE_RELEASED; - break; - } - - int semester = profile.dateToSemester(mobiLesson.date); - - Attendance attendanceObject = new Attendance( - profileId, - strToInt(attendance[0]), - mobiLesson.teacherId, - mobiLesson.subjectId, - semester, - mobiLesson.topic, - mobiLesson.date, - mobiLesson.startTime, - type); - this.attendanceList.add(attendanceObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_ATTENDANCE, attendanceObject.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - } - } - - } - - private void processNotices(String table) - { - String[] notices = table.split("\n"); - - for (String noticeStr: notices) - { - if (noticeStr.isEmpty()) { - continue; - } - String[] notice = noticeStr.split("\\|", Integer.MAX_VALUE); - - if (strToInt(notice[2]) != studentId) - continue; - - Notice noticeObject = new Notice( - profileId, - strToInt(notice[0]), - notice[4], - strToInt(notice[6]), - (notice[3] != null ? (notice[3].equals("1") ? Notice.TYPE_POSITIVE : Notice.TYPE_NEGATIVE) : Notice.TYPE_NEUTRAL), - strToInt(notice[5]) - ); - - Metadata metadata = new Metadata(profileId, Metadata.TYPE_NOTICE, noticeObject.id, profile.getEmpty(), profile.getEmpty(), new Date().parseFromYmd(notice[7]).getInMillis()); - - noticeList.add(noticeObject); - metadataList.add(metadata); - } - } - - private void processGrades(String table) - { - app.db.gradeDao().getDetails(profileId, gradeAddedDates, gradeAverages, gradeColors); - - String[] grades = table.split("\n"); - - long addedDate = Date.getNowInMillis(); - for (String gradeStr: grades) - { - if (gradeStr.isEmpty()) { - continue; - } - String[] grade = gradeStr.split("\\|", Integer.MAX_VALUE); - - if (strToInt(grade[1]) != studentId) - continue; - - if (grade[6].equals("")) { - grade[6] = "-1"; - } - if (grade[10].equals("")) { - grade[10] = "1"; - } - - float weight = 0.0f; - String category = ""; - String description = ""; - int color = -1; - int categoryId = strToInt(grade[6]); - GradeCategory gradeCategory = gradeCategoryList.get(categoryId); - if (gradeCategory != null) { - weight = gradeCategory.weight; - category = gradeCategory.text; - description = gradeCategory.columns.get(strToInt(grade[10]) - 1); - color = gradeCategory.color; - } - - Grade gradeObject = new Grade( - profileId, - strToInt(grade[0]), - category, - color, - description, - grade[7], - Float.parseFloat(grade[11]), - weight, - strToInt(grade[5]), - strToInt(grade[2]), - strToInt(grade[3]) - ); - - - // fix for "0" value grades, so they're not counted in the average - if (gradeObject.value == 0.0f) { - gradeObject.weight = 0; - } - - switch (grade[8]) { - case "3": - // semester proposed - gradeObject.type = (gradeObject.semester == 1 ? TYPE_SEMESTER1_PROPOSED : TYPE_SEMESTER2_PROPOSED); - break; - case "1": - // semester final - gradeObject.type = (gradeObject.semester == 1 ? TYPE_SEMESTER1_FINAL : TYPE_SEMESTER2_FINAL); - break; - case "4": - // year proposed - gradeObject.type = TYPE_YEAR_PROPOSED; - break; - case "2": - // year final - gradeObject.type = TYPE_YEAR_FINAL; - break; - } - - Metadata metadata = new Metadata(profileId, Metadata.TYPE_GRADE, gradeObject.id, profile.getEmpty(), profile.getEmpty(), addedDate); - gradeList.add(gradeObject); - metadataList.add(metadata); - addedDate++; // increase the added date to sort grades as they are in the school profile - } - } - - private void processEvents(String table) - { - String[] events = table.split("\n"); - Date today = Date.getToday(); - for (String eventStr: events) - { - if (eventStr.isEmpty()) { - continue; - } - String[] event = eventStr.split("\\|", Integer.MAX_VALUE); - - Date eventDate = new Date().parseFromYmd(event[4]); - if (eventDate.getValue() < today.getValue()) - continue; - - String examType = ""; - Pattern pattern = Pattern.compile("\\(([0-9A-ząęóżźńśłć]*?)\\)$"); - Matcher matcher = pattern.matcher(event[5]); - if (matcher.find()) { - examType = matcher.group(1); - } - - long addedDate = 0; - - SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US); - try { - addedDate = simpleDateFormat.parse(event[7]).getTime(); - } catch (ParseException e) { - e.printStackTrace(); - } - - int eventType = examType.equals("sprawdzian") ? TYPE_EXAM : examType.equals("kartkówka") ? TYPE_SHORT_QUIZ : TYPE_DEFAULT; - Event eventObject = new Event( - profileId, - strToInt(event[0]), - eventDate, - new Time().parseFromYmdHm(event[6]), - event[5].replace("("+examType+")", ""), - -1, - eventType, - false, - strToInt(event[1]), - strToInt(event[3]), - strToInt(event[2]) - ); - - if (teamsMap.indexOfKey((int)eventObject.teamId) >= 0) { - eventList.add(eventObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_EVENT, eventObject.id, profile.getEmpty(), profile.getEmpty(), addedDate)); - } - } - } - - private void processHomework(String table) - { - String[] homeworkList = table.split("\n"); - Date today = Date.getToday(); - for (String homeworkStr: homeworkList) - { - if (homeworkStr.isEmpty()) { - continue; - } - String[] homework = homeworkStr.split("\\|", Integer.MAX_VALUE); - - Date eventDate = new Date().parseFromYmd(homework[2]); - if (eventDate.getValue() < today.getValue()) - continue; - - Event eventObject = new Event( - profileId, - strToInt(homework[0]), - new Date().parseFromYmd(homework[2]), - new Time().parseFromYmdHm(homework[3]), - homework[1], - -1, - Event.TYPE_HOMEWORK, - false, - strToInt(homework[7]), - strToInt(homework[6]), - strToInt(homework[5]) - ); - - if (teamsMap.indexOfKey((int)eventObject.teamId) >= 0) { - eventList.add(eventObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_HOMEWORK, eventObject.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - } - } - } - - private void processTimetable(String table) - { - String[] lessons = table.split("\n"); - List list = Arrays.asList(lessons); - //Collections.reverse(list); - - // searching for all planned lessons - for (String lessonStr: (String[])list.toArray()) - { - //Log.d(TAG, lessonStr); - if (!lessonStr.isEmpty()) - { - String[] lesson = lessonStr.split("\\|", Integer.MAX_VALUE); - - if (strToInt(lesson[0]) != studentId) - continue; - - if (lesson[1].equals("plan_lekcji") || lesson[1].equals("lekcja")) - { - Lesson lessonObject = new Lesson(profileId, lesson[2], lesson[3], lesson[4]); - - for(int i = 0; i < subjectsMap.size(); i++) { - int key = subjectsMap.keyAt(i); - String str = subjectsMap.valueAt(i); - if (lesson[5].equalsIgnoreCase(str)) { - lessonObject.subjectId = key; - } - } - for(int i = 0; i < teachersMap.size(); i++) { - int key = teachersMap.keyAt(i); - String str = teachersMap.valueAt(i); - if ((lesson[7].trim() + " " + lesson[6].trim()).equalsIgnoreCase(str)) { - lessonObject.teacherId = key; - } - } - for(int i = 0; i < teamsMap.size(); i++) { - int key = teamsMap.keyAt(i); - String str = teamsMap.valueAt(i); - if ((lesson[8] + lesson[9]).equalsIgnoreCase(str)) { - lessonObject.teamId = key; - } - } - lessonObject.classroomName = lesson[11]; - lessonList.add(lessonObject); - } - } - } - - // searching for all changes - for (String lessonStr: (String[])list.toArray()) - { - if (!lessonStr.isEmpty()) - { - String[] lesson = lessonStr.split("\\|", Integer.MAX_VALUE); - - if (strToInt(lesson[0]) != studentId) - continue; - - if (lesson[1].equals("zastepstwo") || lesson[1].equals("lekcja_odwolana")) - { - LessonChange lessonChange = new LessonChange(profileId, lesson[2], lesson[3], lesson[4]); - - //Log.d(TAG, "Lekcja "+lessonStr); - - for(int i = 0; i < subjectsMap.size(); i++) { - int key = subjectsMap.keyAt(i); - String str = subjectsMap.valueAt(i); - if (lesson[5].equalsIgnoreCase(str)) { - lessonChange.subjectId = key; - } - } - for(int i = 0; i < teachersMap.size(); i++) { - int key = teachersMap.keyAt(i); - String str = teachersMap.valueAt(i); - if ((lesson[7].trim() + " " + lesson[6].trim()).equalsIgnoreCase(str)) { - lessonChange.teacherId = key; - } - } - for(int i = 0; i < teamsMap.size(); i++) { - int key = teamsMap.keyAt(i); - String str = teamsMap.valueAt(i); - if ((lesson[8] + lesson[9]).equalsIgnoreCase(str)) { - lessonChange.teamId = key; - } - } - - if (lesson[1].equals("zastepstwo")) { - lessonChange.type = LessonChange.TYPE_CHANGE; - } - if (lesson[1].equals("lekcja_odwolana")) { - lessonChange.type = LessonChange.TYPE_CANCELLED; - } - if (lesson[1].equals("lekcja")) { - lessonChange.type = LessonChange.TYPE_ADDED; - } - lessonChange.classroomName = lesson[11]; - - Lesson originalLesson = lessonChange.getOriginalLesson(lessonList); - - if (lessonChange.type == LessonChange.TYPE_ADDED) { - if (originalLesson == null) { - // original lesson doesn't exist, save a new addition - // TODO - /*if (!RegisterLessonChange.existsAddition(app.profile, registerLessonChange)) { - app.profile.timetable.addLessonAddition(registerLessonChange); - }*/ - } - else { - // original lesson exists, so we need to compare them - if (!lessonChange.matches(originalLesson)) { - // the lessons are different, so it's probably a lesson change - // ahhh this damn API - lessonChange.type = LessonChange.TYPE_CHANGE; - } - } - - } - if (lessonChange.type != LessonChange.TYPE_ADDED) { - // it's not a lesson addition - lessonChangeList.add(lessonChange); - metadataList.add(new Metadata(profileId, Metadata.TYPE_LESSON_CHANGE, lessonChange.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - if (originalLesson == null) { - // there is no original lesson, so we have to add one in order to change it - lessonList.add(Lesson.fromLessonChange(lessonChange)); - } - } - } - } - } - } - - @Override - public Map getConfigurableEndpoints(Profile profile) { - return null; - } - - @Override - public boolean isEndpointEnabled(Profile profile, boolean defaultActive, String name) { - return defaultActive; - } - - @Override - public void syncMessages(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile) { - - } - - /* __ __ - | \/ | - | \ / | ___ ___ ___ __ _ __ _ ___ ___ - | |\/| |/ _ \/ __/ __|/ _` |/ _` |/ _ \/ __| - | | | | __/\__ \__ \ (_| | (_| | __/\__ \ - |_| |_|\___||___/___/\__,_|\__, |\___||___/ - __/ | - |__*/ - @Override - public void getMessage(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile, @NonNull MessageFull message, @NonNull MessageGetCallback messageCallback) { - if (message.body != null) { - boolean readByAll = true; - message.recipients = app.db.messageRecipientDao().getAllByMessageId(profile.getId(), message.id); - for (MessageRecipientFull recipient: message.recipients) { - if (recipient.id == -1) - recipient.fullName = profile.getStudentNameLong(); - if (message.type == TYPE_SENT && recipient.readDate < 1) - readByAll = false; - } - if (!message.seen) { - app.db.metadataDao().setSeen(profile.getId(), message, true); - } - if (readByAll) { - // if a sent msg is not read by everyone, download it again to check the read status - new Handler(activityContext.getMainLooper()).post(() -> { - messageCallback.onSuccess(message); - }); - return; - } - } - - if (!prepare(activityContext, errorCallback, profile.getId(), profile, LoginStore.fromProfileFull(profile))) - return; - - login(() -> Request.builder() - .url("https://" + loginServerName + ".mobidziennik.pl/dziennik/"+(message.type == TYPE_RECEIVED || message.type == TYPE_DELETED ? "wiadodebrana" : "wiadwyslana")+"/?id="+message.id) - .userAgent(System.getProperty("http.agent")) - .callback(new TextCallbackHandler() { - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 1720, CODE_OTHER, response, throwable)); - } - - @Override - public void onSuccess(String data, Response response) { - if (data == null || data.equals("")) { - finishWithError(new AppError(TAG, 1727, CODE_MAINTENANCE, response)); - return; - } - if (data.contains("nie-pamietam-hasla")) { - lastLoginTime = 0; - finishWithError(new AppError(TAG, 1732, CODE_INVALID_LOGIN, response, data)); - return; - } - - List messageRecipientList = new ArrayList<>(); - - try { - Document doc = Jsoup.parse(data); - - Element content = doc.select("#content").first(); - - Element body = content.select(".wiadomosc_tresc").first(); - - if (message.type == TYPE_RECEIVED) { - MessageRecipientFull recipient = new MessageRecipientFull(profileId, -1, message.id); - long readDate = System.currentTimeMillis(); - Matcher matcher = Pattern.compile("czas przeczytania:.+?,\\s([0-9]+)\\s(.+?)\\s([0-9]{4}),\\sgodzina\\s([0-9:]+)", Pattern.DOTALL).matcher(body.html()); - if (matcher.find()) { - Date date = new Date( - strToInt(matcher.group(3)), - monthFromName(matcher.group(2)), - strToInt(matcher.group(1)) - ); - Time time = Time.fromH_m_s( - matcher.group(4) - ); - readDate = date.combineWith(time); - } - recipient.readDate = readDate; - recipient.fullName = profile.getStudentNameLong(); - messageRecipientList.add(recipient); - } - else { - message.senderId = -1; - message.senderReplyId = -1; - - List teacherList = app.db.teacherDao().getAllNow(profileId); - - Elements recipients = content.select("table.spis tr:has(td)"); - for (Element recipientEl: recipients) { - - Element senderEl = recipientEl.select("td:eq(0)").first(); - Teacher teacher = null; - String senderName = senderEl.text(); - for (Teacher aTeacher: teacherList) { - if (aTeacher.getFullNameLastFirst().equals(senderName)) { - teacher = aTeacher; - break; - } - } - - long readDate = 0; - Element isReadEl = recipientEl.select("td:eq(2)").first(); - if (!isReadEl.ownText().equals("NIE")) { - Element readDateEl = recipientEl.select("td:eq(3) small").first(); - Matcher matcher = Pattern.compile(".+?,\\s([0-9]+)\\s(.+?)\\s([0-9]{4}),\\sgodzina\\s([0-9:]+)", Pattern.DOTALL).matcher(readDateEl.ownText()); - if (matcher.find()) { - Date date = new Date( - strToInt(matcher.group(3)), - monthFromName(matcher.group(2)), - strToInt(matcher.group(1)) - ); - Time time = Time.fromH_m_s( - matcher.group(4) - ); - readDate = date.combineWith(time); - } - } - - MessageRecipientFull recipient = new MessageRecipientFull(profileId, teacher == null ? -1 : teacher.id, message.id); - recipient.readDate = readDate; - recipient.fullName = teacher == null ? "?" : teacher.getFullName(); - messageRecipientList.add(recipient); - } - } - - body.select("div").remove(); - - message.body = body.html(); - - message.clearAttachments(); - Elements attachments = content.select("ul li"); - if (attachments != null) { - //d(TAG, "attachments "+attachments.outerHtml()); - for (Element attachment: attachments) { - attachment = attachment.select("a").first(); - //d(TAG, "attachment "+attachment.outerHtml()); - String attachmentName = attachment.ownText(); - long attachmentId = -1; - Matcher matcher = Pattern.compile("href=\"https://.+?\\.mobidziennik.pl/.+?&(?:amp;)?zalacznik=([0-9]+)\"(?:.+?)(List) messageRecipientList); - - message.recipients = messageRecipientList; - - new Handler(activityContext.getMainLooper()).post(() -> { - messageCallback.onSuccess(message); - }); - } - }) - .build() - .enqueue()); - } - - @Override - public void getAttachment(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile, @NonNull MessageFull message, long attachmentId, @NonNull AttachmentGetCallback attachmentCallback) { - if (!prepare(activityContext, errorCallback, profile.getId(), profile, LoginStore.fromProfileFull(profile))) - return; - - login(() -> { - Request.Builder builder = Request.builder() - .url("https://"+loginServerName+".mobidziennik.pl/dziennik/"+(message.type == TYPE_SENT ? "wiadwyslana" : "wiadodebrana")+"/?id="+message.id+"&zalacznik="+attachmentId); - new Handler(activityContext.getMainLooper()).post(() -> { - attachmentCallback.onSuccess(builder); - }); - }); - } - - @Override - public void getRecipientList(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile, @NonNull RecipientListGetCallback recipientListGetCallback) { - if (!prepare(activityContext, errorCallback, profile.getId(), profile, LoginStore.fromProfileFull(profile))) - return; - - if (System.currentTimeMillis() - profile.getLastReceiversSync() < 24 * 60 * 60 * 1000) { - AsyncTask.execute(() -> { - List teacherList = app.db.teacherDao().getAllNow(profileId); - new Handler(activityContext.getMainLooper()).post(() -> recipientListGetCallback.onSuccess(teacherList)); - }); - return; - } - - login(() -> { - Request.builder() - .url("https://" + loginServerName + ".mobidziennik.pl/mobile/dodajwiadomosc") - .userAgent(System.getProperty("http.agent")) - .callback(new TextCallbackHandler() { - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 2289, CODE_OTHER, response, throwable)); - } - - @Override - public void onSuccess(String data, Response response) { - if (data == null || data.equals("")) { - finishWithError(new AppError(TAG, 2295, CODE_MAINTENANCE, response)); - return; - } - if (data.contains("nie-pamietam-hasla")) { - lastLoginTime = 0; - finishWithError(new AppError(TAG, 2300, CODE_INVALID_LOGIN, response, data)); - return; - } - - teacherList = app.db.teacherDao().getAllNow(profileId); - - for (Teacher teacher: teacherList) { - teacher.typeDescription = null; // TODO: 2019-06-13 it better - } - - Matcher categoryMatcher = Pattern.compile("").matcher(data); - while (categoryMatcher.find()) { - String categoryId = categoryMatcher.group(1); - String categoryName = categoryMatcher.group(2); - String categoryHtml = getRecipientCategory(categoryId); - if (categoryHtml == null) - return; // the error callback is already executed - Matcher teacherMatcher = Pattern.compile("(.+?)|").matcher(categoryHtml); - while (teacherMatcher.find()) { - if (teacherMatcher.group(1) != null) { - String className = teacherMatcher.group(1); - String listHtml = teacherMatcher.group(2); - Matcher listMatcher = Pattern.compile("").matcher(listHtml); - while (listMatcher.find()) { - updateTeacher(categoryId, Long.parseLong(listMatcher.group(1)), listMatcher.group(2), categoryName, className); - } - } - else { - updateTeacher(categoryId, Long.parseLong(teacherMatcher.group(3)), teacherMatcher.group(4), categoryName, null); - } - } - } - app.db.teacherDao().addAll(teacherList); - - profile.setLastReceiversSync(System.currentTimeMillis()); - app.db.profileDao().add(profile); - - new Handler(activityContext.getMainLooper()).post(() -> recipientListGetCallback.onSuccess(new ArrayList<>(teacherList))); - } - }) - .build() - .enqueue(); - }); - } - private String getRecipientCategory(String categoryId) { - Response response = null; - try { - response = Request.builder() - .url("https://" + loginServerName + ".mobidziennik.pl/mobile/odbiorcyWiadomosci") - .userAgent(System.getProperty("http.agent")) - .addParameter("typ", categoryId) - .post() - .build().execute(); - if (response.code() != 200) { - finishWithError(new AppError(TAG, 2349, CODE_OTHER, response)); - return null; - } - String data = new TextCallbackHandler().backgroundParser(response); - if (data == null || data.equals("")) { - return ""; - } - if (data.contains("nie-pamietam-hasla")) { - lastLoginTime = 0; - finishWithError(new AppError(TAG, 2300, CODE_INVALID_LOGIN, response, data)); - return null; - } - return data; - } catch (Exception e) { - finishWithError(new AppError(TAG, 2355, CODE_OTHER, response, e)); - return null; - } - } - private void updateTeacher(String category, long id, String nameLastFirst, String typeDescription, String className) { - Teacher teacher = Teacher.getById(teacherList, id); - if (teacher == null) { - String[] nameParts = nameLastFirst.split(" ", Integer.MAX_VALUE); - teacher = new Teacher(profileId, id, nameParts[1], nameParts[0]); - teacherList.add(teacher); - } - teacher.loginId = String.valueOf(id); - teacher.type = 0; - if (className != null) { - teacher.typeDescription = bs("", teacher.typeDescription, ", ")+className; - } - switch (category) { - case "1": - teacher.setType(Teacher.TYPE_PRINCIPAL); - break; - case "2": - teacher.setType(Teacher.TYPE_TEACHER); - break; - case "8": - teacher.setType(Teacher.TYPE_EDUCATOR); - break; - case "9": - teacher.setType(Teacher.TYPE_PEDAGOGUE); - break; - case "10": - teacher.setType(Teacher.TYPE_OTHER); - teacher.typeDescription = "Specjaliści"; - break; - case "Administracja WizjaNet": - teacher.setType(Teacher.TYPE_SUPER_ADMIN); - break; - case "Administratorzy": - teacher.setType(Teacher.TYPE_SCHOOL_ADMIN); - break; - case "Sekretarka": - teacher.setType(Teacher.TYPE_SECRETARIAT); - break; - default: - teacher.setType(Teacher.TYPE_OTHER); - teacher.typeDescription = typeDescription+bs(" ", teacher.typeDescription); - break; - } - } - - @Override - public MessagesComposeInfo getComposeInfo(@NonNull ProfileFull profile) { - return new MessagesComposeInfo(-1, profile.getStudentData("attachmentSizeLimit", 6291456L), 100, -1); - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Regexes.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Regexes.kt new file mode 100644 index 00000000..b42de2c4 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Regexes.kt @@ -0,0 +1,288 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-6. + */ + +package pl.szczodrzynski.edziennik.data.api + +import kotlin.text.RegexOption.DOT_MATCHES_ALL +import kotlin.text.RegexOption.IGNORE_CASE + +object Regexes { + val STYLE_CSS_COLOR by lazy { + """color: (\w+);?""".toRegex() + } + + val NOT_DIGITS by lazy { + """[^0-9]""".toRegex() + } + + val HTML_BR by lazy { + """""".toRegex() + } + + + + val MOBIDZIENNIK_GRADES_SUBJECT_NAME by lazy { + """\n*\s*(.+?)\s*\n*(?:<.*?)??
    """.toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_GRADES_COLOR by lazy { + """background-color:([#A-Fa-f0-9]+);""".toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_GRADES_CATEGORY by lazy { + """> (.+?):
    """.toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_GRADES_CLASS_AVERAGE by lazy { + """Średnia ocen:.*([0-9]*\.?[0-9]*)""".toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_GRADES_ADDED_DATE by lazy { + """Wpisano:.*.+?,\s([0-9]+)\s(.+?)\s([0-9]{4}),\sgodzina\s([0-9:]+)""".toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_GRADES_COUNT_TO_AVG by lazy { + """Liczona do średniej:.*?nie
    """.toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_GRADES_DETAILS by lazy { + """(.+?).*?.+?.*?(?:\((.+?)\).*?)?.*?Wartość oceny:.*?([0-9.]+).*?Wpisał\(a\):.*?(.+?).*?(?:Komentarz:.*?(.+?))?""".toRegex(DOT_MATCHES_ALL) + } + + val MOBIDZIENNIK_EVENT_TYPE by lazy { + """\(([0-9A-ząęóżźńśłć]*?)\)$""".toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_LUCKY_NUMBER by lazy { + """class="szczesliwy_numerek".*?>0?([0-9]+)/?0?([0-9]+)?""".toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_CLASS_CALENDAR by lazy { + """events: (.+),$""".toRegex(RegexOption.MULTILINE) + } + + val MOBIDZIENNIK_WEB_ATTACHMENT by lazy { + """href="https://.+?\.mobidziennik.pl/.+?&(?:amp;)?zalacznik(_rozwiazania)?=([0-9]+)".+?>(.+?)(?: )?""".toRegex() + } + + val MOBIDZIENNIK_MESSAGE_READ_DATE by lazy { + """czas przeczytania:.+?,\s([0-9]+)\s(.+?)\s([0-9]{4}),\sgodzina\s([0-9:]+)""".toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_MESSAGE_SENT_READ_DATE by lazy { + """.+?,\s([0-9]+)\s(.+?)\s([0-9]{4}),\sgodzina\s([0-9:]+)""".toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_MESSAGE_SENT_READ_BY by lazy { + """([0-9]+)/([0-9]+)""".toRegex() + } + + val MOBIDZIENNIK_MESSAGE_RECIPIENTS_JSON by lazy { + """odbiorcy: (\[.+?]),${'$'}""".toRegex(RegexOption.MULTILINE) + } + + val MOBIDZIENNIK_ACCOUNT_EMAIL by lazy { + """name="email" value="(.+?@.+?\..+?)"""".toRegex(DOT_MATCHES_ALL) + } + + + val MOBIDZIENNIK_ATTENDANCE_TYPES by lazy { + """Legenda:.+?normal;">(.+?)""".toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_ATTENDANCE_TABLE by lazy { + """(.+?)
    """.toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_ATTENDANCE_LESSON_COUNT by lazy { + """rel="([0-9-]{10})" colspan="([0-9]+)"""".toRegex() + } + val MOBIDZIENNIK_ATTENDANCE_ENTRIES by lazy { + """font-size:.+?class=".*?">(.*?)""".toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_ATTENDANCE_COLUMNS by lazy { + """(.+?)""".toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_ATTENDANCE_COLUMN by lazy { + """()(.*?)""".toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_ATTENDANCE_COLUMN_SPAN by lazy { + """colspan="(\d+)"""".toRegex() + } + val MOBIDZIENNIK_ATTENDANCE_RANGE by lazy { + """([0-9:]+) - .+? (.+?)""".toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_ATTENDANCE_LESSON by lazy { + """(.+?)\s*\s*\((.+?),\s*(.+?)\)""".toRegex(DOT_MATCHES_ALL) + } + + val MOBIDZIENNIK_MOBILE_HOMEWORK_ROW by lazy { + """class="rowRolling">(.+?\s*)""".toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_MOBILE_HOMEWORK_ITEM by lazy { + """

    (.+?):\s*(.+?)\s*

    """.toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_MOBILE_HOMEWORK_BODY by lazy { + """Treść:(.+?)

    """.toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_MOBILE_HOMEWORK_ID by lazy { + """name="id_zadania" value="([0-9]+)"""".toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_MOBILE_HOMEWORK_ATTACHMENT by lazy { + """zalacznik(_zadania)?=([0-9]+)'.+?word-break">(.+?)""".toRegex(DOT_MATCHES_ALL) + } + + val MOBIDZIENNIK_WEB_HOMEWORK_ADDED_DATE by lazy { + """Wpisał\(a\):\s+\s+(.+?), (.+?), ([0-9]{1,2}) (.+?) ([0-9]{4}), godzina ([0-9:]+)""".toRegex() + } + + + val MOBIDZIENNIK_TIMETABLE_TOP by lazy { + """

    .+?
    """.toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_TIMETABLE_CELL by lazy { + """
    .+?style="(.+?)".+?title="(.+?)".+?>\s+(.+?)\s+
    """.toRegex(DOT_MATCHES_ALL) + } + val MOBIDZIENNIK_TIMETABLE_LEFT by lazy { + """
    .+?
    """.toRegex(DOT_MATCHES_ALL) + } + + + val MOBIDZIENNIK_EVENT_CONTENT by lazy { + """

    (.+?) \(wpisał\(a\) (.+?) w dniu ([0-9-]{10})\).+?(.+?)""".toRegex(DOT_MATCHES_ALL) + } + val IDZIENNIK_LOGIN_ERROR by lazy { + """id="spanErrorMessage">(.*?)(.+?)""".toRegex(DOT_MATCHES_ALL) + } + val IDZIENNIK_LOGIN_FIRST_IS_PARENT by lazy { + """id="ctl00_CzyRodzic" value="([01])" />""".toRegex() + } + val IDZIENNIK_LOGIN_FIRST_SCHOOL_YEAR by lazy { + """name="ctl00\${"$"}dxComboRokSzkolny".+?selected="selected".*?value="([0-9]+)">([0-9]+)/([0-9]+)<""".toRegex(DOT_MATCHES_ALL) + } + val IDZIENNIK_LOGIN_FIRST_STUDENT_SELECT by lazy { + """""".toRegex(DOT_MATCHES_ALL) + } + val IDZIENNIK_LOGIN_FIRST_STUDENT by lazy { + """(.+?)\s(.+?)\s*\((.+?),\s*(.+?)\)""".toRegex(DOT_MATCHES_ALL) + } + val IDZIENNIK_MESSAGES_RECIPIENT_PARENT by lazy { + """(.+?)\s\((.+)\)""".toRegex() + } + /*Szczęśliwy los na dzisiaj to 19. Los na jutro to 22*/ + val IDZIENNIK_WEB_LUCKY_NUMBER by lazy { + """dzisiaj to ([0-9]+)""".toRegex() + } + val IDZIENNIK_WEB_SELECTED_REGISTER by lazy { + """selected="selected" value="([0-9]+)" data-id-ucznia""".toRegex() + } + + + + val VULCAN_SHIFT_ANNOTATION by lazy { + """\(przeniesiona (z|na) lekcj[ię] ([0-9]+), (.+)\)""".toRegex() + } + val VULCAN_WEB_PERMISSIONS by lazy { + """permissions: '([A-z0-9/=+\-_|]+?)'""".toRegex() + } + val VULCAN_WEB_SYMBOL_VALIDATE by lazy { + """[A-z0-9]+""".toRegex(IGNORE_CASE) + } + + + + val LIBRUS_ATTACHMENT_KEY by lazy { + """singleUseKey=([0-9A-z_]+)""".toRegex() + } + val LIBRUS_MESSAGE_ID by lazy { + """/wiadomosci/[0-9]+/[0-9]+/([0-9]+?)/""".toRegex() + } + + + + val EDUDZIENNIK_STUDENTS_START by lazy { + """
  • (.*?)""".toRegex() + } + val EDUDZIENNIK_ACCOUNT_NAME_START by lazy { + """(.*?)""".toRegex() + } + val EDUDZIENNIK_SUBJECTS_START by lazy { + """(.+?)""".toRegex() + } + + val EDUDZIENNIK_ATTENDANCE_ENTRIES by lazy { + """(.+?)""".toRegex() + } + val EDUDZIENNIK_ATTENDANCE_TYPES by lazy { + """
    .*?

    (.*?)

    """.toRegex(DOT_MATCHES_ALL) + } + val EDUDZIENNIK_ATTENDANCE_TYPE by lazy { + """\((.+?)\) (.+)""".toRegex() + } + + val EDUDZIENNIK_ANNOUNCEMENT_DESCRIPTION by lazy { + """
    .*?

    (.*?)

    """.toRegex(DOT_MATCHES_ALL) + } + val EDUDZIENNIK_HOMEWORK_DESCRIPTION by lazy { + """
    (.*?)
    """.toRegex(DOT_MATCHES_ALL) + } + + val EDUDZIENNIK_SUBJECT_ID by lazy { + """/Courses/([\w-_]+?)/""".toRegex() + } + val EDUDZIENNIK_GRADE_ID by lazy { + """/Grades/([\w-_]+?)/""".toRegex() + } + val EDUDZIENNIK_EXAM_ID by lazy { + """/Evaluations/([\w-_]+?)/""".toRegex() + } + val EDUDZIENNIK_EVENT_TYPE_ID by lazy { + """/GradeLabels/([\w-_]+?)/""".toRegex() + } + val EDUDZIENNIK_ANNOUNCEMENT_ID by lazy { + """/Announcement/([\w-_]+?)/""".toRegex() + } + val EDUDZIENNIK_HOMEWORK_ID by lazy { + """/Homework/([\w-_]+?)/""".toRegex() + } + val EDUDZIENNIK_TEACHER_ID by lazy { + """/Teachers/([\w-_]+?)/""".toRegex() + } + val EDUDZIENNIK_EVENT_ID by lazy { + """/KlassEvent/([\w-_]+?)/""".toRegex() + } + val EDUDZIENNIK_NOTE_ID by lazy { + """/RegistryNotes/([\w-_]+?)/""".toRegex() + } + + val EDUDZIENNIK_SCHOOL_DETAIL_ID by lazy { + """.*?

    (.*?)

    .*?
  • """.toRegex(DOT_MATCHES_ALL) + } + val EDUDZIENNIK_CLASS_DETAIL_ID by lazy { + """(.*?)""".toRegex(DOT_MATCHES_ALL) + } + + val EDUDZIENNIK_TEACHERS by lazy { + """
    .*?

    (.+?) (.+?)

    """.toRegex(DOT_MATCHES_ALL) + } + + + + + val LINKIFY_DATE_YMD by lazy { + """(1\d{3}|20\d{2})[\-./](1[0-2]|0?\d)[\-./]([1-2]\d|3[0-1]|0?\d)""".toRegex() + } + val LINKIFY_DATE_DMY by lazy { + """(? targetEndpoints = new ArrayList<>(); - - // PROGRESS - private static final int PROGRESS_LOGIN = 10; - private int PROGRESS_COUNT = 1; - private int PROGRESS_STEP = (90/PROGRESS_COUNT); - - private int onlyFeature = FEATURE_ALL; - - private List teamList; - private List teacherList; - private List subjectList; - private List lessonList; - private List lessonChangeList; - private List gradeCategoryList; - private List gradeList; - private List eventList; - private List noticeList; - private List attendanceList; - private List messageList; - private List messageRecipientList; - private List messageRecipientIgnoreList; - private List metadataList; - private List messageMetadataList; - - private String apiUrl = null; - private String certificateKey = null; - private String certificatePfx = null; - private String deviceToken = null; - private String deviceSymbol = null; - private String devicePin = null; - /** - * deviceSymbol_JednostkaSprawozdawczaSymbol - */private String schoolName = null; - /** - * JednostkaSprawozdawczaSymbol - */private String schoolSymbol = null; - /** - * Id - */private int studentId = -1; - /** - * UzytkownikLoginId - */private int studentLoginId = -1; - /** - * IdOddzial - */private int studentClassId = -1; - /** - * IdOkresKlasyfikacyjny - */private int studentSemesterId = -1; - /** - * OkresNumer - */private int studentSemesterNumber = -1; - private boolean syncingSemester1 = false; - private OkHttpClient signingHttp = null; - private Date oneMonthBack = today.clone().stepForward(0, -1, 0); - - /* _____ - | __ \ - | |__) | __ ___ _ __ __ _ _ __ ___ - | ___/ '__/ _ \ '_ \ / _` | '__/ _ \ - | | | | | __/ |_) | (_| | | | __/ - |_| |_| \___| .__/ \__,_|_| \___| - | | - |*/ - private boolean prepare(@NonNull Context activityContext, @NonNull SyncCallback callback, int profileId, @Nullable Profile profile, @NonNull LoginStore loginStore) { - this.activityContext = activityContext; - this.callback = callback; - this.profileId = profileId; - // here we must have a login store: either with a correct ID or -1 - // there may be no profile and that's when onLoginFirst happens - this.profile = profile; - this.loginStore = loginStore; - this.fullSync = profile == null || profile.getEmpty() || profile.shouldFullSync(activityContext); - this.today = Date.getToday(); - - if (this.signingHttp == null) { - this.signingHttp = this.app.http.newBuilder().addInterceptor(chain -> { - okhttp3.Request request = chain.request(); - Buffer buffer = new Buffer(); - assert request.body() != null; - request.body().writeTo(buffer); - String signature = ""; - // cannot use Utils.exception, because we are not in the main thread here! - // Utils.exception would show the dialog which has to be shown in the UI thread - try { - signature = Utils.VulcanRequestEncryptionUtils.signContent(buffer.readByteArray(), new ByteArrayInputStream(Base64.decode(this.certificatePfx, Base64.DEFAULT))); - } catch (IOException e) { - e.printStackTrace(); - } catch (GeneralSecurityException e) { - e.printStackTrace(); - } - request = request.newBuilder().addHeader("RequestSignatureValue", signature).addHeader("RequestCertificateKey", this.certificateKey).build(); - return chain.proceed(request); - }).build(); - } - - - if (certificateKey == null || certificatePfx == null || apiUrl == null) { - c(TAG, "first login, use TOKEN, SYMBOL, PIN"); - - } - - teamList = profileId == -1 ? new ArrayList<>() : app.db.teamDao().getAllNow(profileId); - teacherList = profileId == -1 ? new ArrayList<>() : app.db.teacherDao().getAllNow(profileId); - subjectList = new ArrayList<>(); - lessonList = new ArrayList<>(); - lessonChangeList = new ArrayList<>(); - gradeCategoryList = new ArrayList<>(); - gradeList = new ArrayList<>(); - eventList = new ArrayList<>(); - noticeList = new ArrayList<>(); - attendanceList = new ArrayList<>(); - messageList = new ArrayList<>(); - messageRecipientList = new ArrayList<>(); - messageRecipientIgnoreList = new ArrayList<>(); - metadataList = new ArrayList<>(); - messageMetadataList = new ArrayList<>(); - - return true; - } - - @Override - public void sync(@NonNull Context activityContext, @NonNull SyncCallback callback, int profileId, @Nullable Profile profile, @NonNull LoginStore loginStore) { - if (!prepare(activityContext, callback, profileId, profile, loginStore)) - return; - - login(() -> { - targetEndpoints = new ArrayList<>(); - targetEndpoints.add("SetPushToken"); - targetEndpoints.add("Dictionaries"); - targetEndpoints.add("Timetable"); - targetEndpoints.add("Grades"); - targetEndpoints.add("ProposedGrades"); - targetEndpoints.add("Events"); - targetEndpoints.add("Homework"); - targetEndpoints.add("Notices"); - targetEndpoints.add("Attendance"); - targetEndpoints.add("MessagesInbox"); - targetEndpoints.add("MessagesOutbox"); - targetEndpoints.add("Finish"); - PROGRESS_COUNT = targetEndpoints.size()-1; - PROGRESS_STEP = (90/PROGRESS_COUNT); - begin(); - }); - } - @Override - public void syncFeature(@NonNull Context activityContext, @NonNull SyncCallback callback, @NonNull ProfileFull profile, int ... featureList) { - if (featureList == null) { - sync(activityContext, callback, profile.getId(), profile, LoginStore.fromProfileFull(profile)); - return; - } - if (!prepare(activityContext, callback, profile.getId(), profile, LoginStore.fromProfileFull(profile))) - return; - - login(() -> { - targetEndpoints = new ArrayList<>(); - if (featureList.length == 1) - onlyFeature = featureList[0]; - targetEndpoints.add("SetPushToken"); - targetEndpoints.add("Dictionaries"); - for (int feature: featureList) { - switch (feature) { - case FEATURE_TIMETABLE: - targetEndpoints.add("Timetable"); - break; - case FEATURE_AGENDA: - targetEndpoints.add("Events"); - break; - case FEATURE_GRADES: - targetEndpoints.add("Grades"); - targetEndpoints.add("ProposedGrades"); - break; - case FEATURE_HOMEWORK: - targetEndpoints.add("Homework"); - break; - case FEATURE_NOTICES: - targetEndpoints.add("Notices"); - break; - case FEATURE_ATTENDANCE: - targetEndpoints.add("Attendance"); - break; - case FEATURE_MESSAGES_INBOX: - targetEndpoints.add("MessagesInbox"); - break; - case FEATURE_MESSAGES_OUTBOX: - targetEndpoints.add("MessagesOutbox"); - break; - } - } - targetEndpoints.add("Finish"); - PROGRESS_COUNT = targetEndpoints.size()-1; - PROGRESS_STEP = (90/PROGRESS_COUNT); - begin(); - }); - } - - private void begin() { - schoolName = profile.getStudentData("schoolName", null); - schoolSymbol = profile.getStudentData("schoolSymbol", null); - studentId = profile.getStudentData("studentId", -1); - studentLoginId = profile.getStudentData("studentLoginId", -1); - studentClassId = profile.getStudentData("studentClassId", -1); - studentSemesterId = profile.getStudentData("studentSemesterId", -1); - studentSemesterNumber = profile.getStudentData("studentSemesterNumber", profile.getCurrentSemester()); - if (profile.getEmpty() && studentSemesterNumber == 2) { - syncingSemester1 = true; - studentSemesterId -= 1; - studentSemesterNumber -= 1; - } - else { - syncingSemester1 = false; - } - d(TAG, "Syncing student "+studentId+", class "+studentClassId+", semester "+studentSemesterId); - - callback.onProgress(PROGRESS_LOGIN); - - r("get", null); - } - - private void r(String type, String endpoint) { - // endpoint == null when beginning - if (endpoint == null) - endpoint = targetEndpoints.get(0); - int index = -1; - for (String request: targetEndpoints) { - index++; - if (request.equals(endpoint)) { - break; - } - } - if (type.equals("finish")) { - // called when finishing the action - callback.onProgress(PROGRESS_STEP); - index++; - } - d(TAG, "Called r("+type+", "+endpoint+"). Getting "+targetEndpoints.get(index)); - switch (targetEndpoints.get(index)) { - case "SetPushToken": - setPushToken(); - break; - case "Dictionaries": - getDictionaries(); - break; - case "Timetable": - getTimetable(); - break; - case "Grades": - getGrades(); - break; - case "ProposedGrades": - getProposedGrades(); - break; - case "Events": - getEvents(); - break; - case "Homework": - getHomework(); - break; - case "Notices": - getNotices(); - break; - case "Attendance": - getAttendance(); - break; - case "MessagesInbox": - getMessagesInbox(); - break; - case "MessagesOutbox": - getMessagesOutbox(); - break; - case "Finish": - finish(); - break; - } - } - private void saveData() { - if (teamList.size() > 0) { - app.db.teamDao().addAll(teamList); - } - if (teacherList.size() > 0) - app.db.teacherDao().addAll(teacherList); - if (subjectList.size() > 0) - app.db.subjectDao().addAll(subjectList); - if (lessonList.size() > 0) { - app.db.lessonDao().clear(profileId); - app.db.lessonDao().addAll(lessonList); - } - if (lessonChangeList.size() > 0) - app.db.lessonChangeDao().addAll(lessonChangeList); - if (gradeCategoryList.size() > 0) - app.db.gradeCategoryDao().addAll(gradeCategoryList); - if (gradeList.size() > 0) { - app.db.gradeDao().clearForSemester(profileId, studentSemesterNumber); - app.db.gradeDao().addAll(gradeList); - } - if (eventList.size() > 0) { - app.db.eventDao().removeFuture(profileId, Date.getToday()); - app.db.eventDao().addAll(eventList); - } - if (noticeList.size() > 0) { - app.db.noticeDao().clearForSemester(profileId, studentSemesterNumber); - app.db.noticeDao().addAll(noticeList); - } - if (attendanceList.size() > 0) { - app.db.attendanceDao().clearAfterDate(profileId, getCurrentSemesterStartDate()); - app.db.attendanceDao().addAll(attendanceList); - } - if (messageList.size() > 0) - app.db.messageDao().addAllIgnore(messageList); - if (messageRecipientList.size() > 0) - app.db.messageRecipientDao().addAll(messageRecipientList); - if (messageRecipientIgnoreList.size() > 0) - app.db.messageRecipientDao().addAllIgnore(messageRecipientIgnoreList); - if (metadataList.size() > 0) - app.db.metadataDao().addAllIgnore(metadataList); - if (messageMetadataList.size() > 0) - app.db.metadataDao().setSeen(messageMetadataList); - } - private void finish() { - if (syncingSemester1) { - syncingSemester1 = false; - studentSemesterId += 1; - studentSemesterNumber += 1; - // no need to download dictionaries again - r("get", null);// TODO: 2019-06-04 start with Timetables or first element (if partial sync) - return; - } - try { - saveData(); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 425, CODE_OTHER, app.getString(R.string.sync_error_saving_data), null, null, e, null)); - } - if (fullSync) { - profile.setLastFullSync(System.currentTimeMillis()); - fullSync = false; - } - profile.setEmpty(false); - callback.onSuccess(activityContext, new ProfileFull(profile, loginStore)); - } - private void finishWithError(AppError error) { - try { - saveData(); - } - catch (Exception e) { - Crashlytics.logException(e); - } - callback.onError(activityContext, error); - } - - /* _ _ - | | (_) - | | ___ __ _ _ _ __ - | | / _ \ / _` | | '_ \ - | |___| (_) | (_| | | | | | - |______\___/ \__, |_|_| |_| - __/ | - |__*/ - private void login(@NonNull LoginCallback loginCallback) { - if (profile == null) { - // FIRST LOGIN - this.deviceToken = loginStore.getLoginData("deviceToken", null); - this.deviceSymbol = loginStore.getLoginData("deviceSymbol", null); - this.devicePin = loginStore.getLoginData("devicePin", null); - if (deviceToken == null || deviceSymbol == null || devicePin == null) { - finishWithError(new AppError(TAG, 443, AppError.CODE_INVALID_LOGIN, "Login field is empty")); - return; - } - - setApiUrl(deviceToken, deviceSymbol); - getCertificate(deviceToken, devicePin, ((certificateKey, certificatePfx, apiUrl, userLogin, userName) -> { - loginStore.removeLoginData("deviceToken"); - loginStore.removeLoginData("devicePin"); - loginStore.putLoginData("certificateKey", certificateKey); - loginStore.putLoginData("certificatePfx", certificatePfx); - loginStore.putLoginData("apiUrl", apiUrl); - loginStore.putLoginData("userLogin", userLogin); - this.apiUrl = apiUrl; - this.certificateKey = certificateKey; - this.certificatePfx = certificatePfx; - this.deviceToken = null; - this.devicePin = null; - - c(TAG, "first login. get the list of students"); - getStudentList(usersMap -> { - List profileList = new ArrayList<>(); - for (int index = 0; index < usersMap.size(); index++) { - JsonObject account = new ArrayList<>(usersMap.values()).get(index); - - Profile newProfile = new Profile(); - newProfile.setEmpty(true); - newProfile.setLoggedIn(true); - saveStudentData(newProfile, account); - - profileList.add(newProfile); - } - callback.onLoginFirst(profileList, loginStore); - }, false); - - })); - } - else { - this.apiUrl = loginStore.getLoginData("apiUrl", null); - this.certificateKey = loginStore.getLoginData("certificateKey", null); - this.certificatePfx = loginStore.getLoginData("certificatePfx", null); - if (apiUrl == null || certificateKey == null || certificatePfx == null) { - finishWithError(new AppError(TAG, 489, AppError.CODE_INVALID_LOGIN, "Login field is empty")); - return; - } - if (profile.getStudentData("currentSemesterEndDate", System.currentTimeMillis()/*default always larger*/) < System.currentTimeMillis()/1000 - || (studentLoginId = profile.getStudentData("studentLoginId", -1)) == -1) { - // current semester is over, we need to get student data again - callback.onActionStarted(R.string.sync_action_getting_account); - getStudentList(usersMap -> { - studentId = profile.getStudentData("studentId", -1); - d(TAG, "Searching the student ID "+studentId); - JsonObject foundUser = null; - for (JsonObject user: usersMap.values()) { - if (user.get("Id").getAsInt() == studentId) { - foundUser = user; - } - } - if (foundUser == null || foundUser.get("IdOkresKlasyfikacyjny").getAsInt() == 0) { - d(TAG, "Not found"); - finishWithError(new AppError(TAG, 507, AppError.CODE_OTHER, app.getString(R.string.error_register_student_no_term), usersMap.toString())); - } - else { - d(TAG, "Saving updated student data"); - saveStudentData(profile, foundUser); - loginCallback.onSuccess(); - } - }, true); - } - else { - loginCallback.onSuccess(); - } - } - } - - /* _ _ _ _ _ _ _ - | | | | | | ___ | | | | | | - | |__| | ___| |_ __ ___ _ __ ___ ( _ ) ___ __ _| | | |__ __ _ ___| | _____ - | __ |/ _ \ | '_ \ / _ \ '__/ __| / _ \/\ / __/ _` | | | '_ \ / _` |/ __| |/ / __| - | | | | __/ | |_) | __/ | \__ \ | (_> < | (_| (_| | | | |_) | (_| | (__| <\__ \ - |_| |_|\___|_| .__/ \___|_| |___/ \___/\/ \___\__,_|_|_|_.__/ \__,_|\___|_|\_\___/ - | | - |*/ - private void getCertificate(String token, String pin, CertificateCallback certificateCallback) { - callback.onActionStarted(R.string.sync_action_getting_certificate); - d(TAG, "Post JSON "+apiUrl + ENDPOINT_CERTIFICATE); - if (apiUrl == null) { - finishWithError(new AppError(TAG, 1215, AppError.CODE_INVALID_TOKEN, "Empty apiUrl(1)")); - return; - } - Request.builder() - .url(apiUrl + ENDPOINT_CERTIFICATE) - .userAgent(userAgent) - .addParameter("PIN", pin) - .addParameter("TokenKey", token) - .addParameter("AppVersion", MOBILE_APP_VERSION) - .addParameter("DeviceId", UUID.randomUUID().toString()) - .addParameter("DeviceName", "Szkolny.eu "+Build.MODEL) - .addParameter("DeviceNameUser", "") - .addParameter("DeviceDescription", "") - .addParameter("DeviceSystemType", "Android") - .addParameter("DeviceSystemVersion", Build.VERSION.RELEASE) - .addParameter("RemoteMobileTimeKey", getUnixTime()) - .addParameter("TimeKey", getUnixTime() - 1) - .addParameter("RequestId", UUID.randomUUID().toString()) - .addParameter("RemoteMobileAppVersion", MOBILE_APP_VERSION) - .addParameter("RemoteMobileAppName", MOBILE_APP_NAME) - .postJson() - .addHeader("RequestMobileType", "RegisterDevice") - .callback(new JsonCallbackHandler() { - @Override - public void onSuccess(JsonObject data, Response response) { - if (data == null) { - finishWithError(new AppError(TAG, 1241, AppError.CODE_MAINTENANCE, response)); - return; - } - d(TAG, "Certificate data "+data.toString()); - boolean isError = data.get("IsError").getAsBoolean(); - if (isError) { - JsonElement message = data.get("Message"); - JsonElement tokenStatus = data.get("TokenStatus"); - String msg = null; - String tokenStatusStr = null; - if (message != null) { - msg = message.getAsString(); - } - if (tokenStatus != null) { - tokenStatusStr = tokenStatus.getAsString(); - } - if ("TokenNotFound".equals(msg)) { - finishWithError(new AppError(TAG, 1258, AppError.CODE_INVALID_TOKEN, response, data)); - return; - } - if ("TokenDead".equals(msg)) { - finishWithError(new AppError(TAG, 1262, AppError.CODE_EXPIRED_TOKEN, response, data)); - return; - } - if ("WrongPIN".equals(tokenStatusStr)) { - Matcher matcher = Pattern.compile("Liczba pozostałych prób: ([0-9])", Pattern.DOTALL).matcher(tokenStatusStr); - finishWithError(new AppError(TAG, 1267, AppError.CODE_INVALID_PIN, matcher.matches() ? matcher.group(1) : "?", response, data)); - return; - } - if ("Broken".equals(tokenStatusStr)) { - finishWithError(new AppError(TAG, 1262, AppError.CODE_INVALID_PIN, "0", response, data)); - return; - } - finishWithError(new AppError(TAG, 1274, AppError.CODE_OTHER, "Sprawdź wprowadzone dane.\n\nBłąd certyfikatu "+(message == null ? "" : message.getAsString()), response, data)); - return; - } - JsonElement tokenCert = data.get("TokenCert"); - if (tokenCert == null || tokenCert instanceof JsonNull) { - finishWithError(new AppError(TAG, 1279, AppError.CODE_OTHER, "Sprawdź wprowadzone dane.\n\nCertificate error. TokenCert null", response, data)); - return; - } - data = tokenCert.getAsJsonObject(); - try { - certificateCallback.onSuccess( - data.get("CertyfikatKlucz").getAsString(), - data.get("CertyfikatPfx").getAsString(), - data.get("AdresBazowyRestApi").getAsString(), - data.get("UzytkownikLogin").getAsString(), - data.get("UzytkownikNazwa").getAsString() - ); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 1293, AppError.CODE_OTHER, response, e, data)); - } - } - - @Override - public void onFailure(Response response, Throwable throwable) { - if (response.code() == 400) { - finishWithError(new AppError(TAG, 1300, AppError.CODE_INVALID_SYMBOL, response, throwable)); - return; - } - finishWithError(new AppError(TAG, 1303, AppError.CODE_OTHER, response, throwable)); - } - }) - .build() - .enqueue(); - } - - private void apiRequest(String endpoint, JsonObject payload, ApiRequestCallback apiRequestCallback) { - d(TAG, "API request "+apiUrl + endpoint); - if (apiUrl == null) { - finishWithError(new AppError(TAG, 1313, AppError.CODE_OTHER, app.getString(R.string.sync_error_no_api_url), "Empty apiUrl(2)")); - return; - } - if (payload == null) - payload = new JsonObject(); - payload.addProperty("RemoteMobileTimeKey", getUnixTime()); - payload.addProperty("TimeKey", getUnixTime() - 1); - payload.addProperty("RequestId", UUID.randomUUID().toString()); - payload.addProperty("RemoteMobileAppVersion", MOBILE_APP_VERSION); - payload.addProperty("RemoteMobileAppName", MOBILE_APP_NAME); - Request.builder() - .url(apiUrl + endpoint) - .userAgent(userAgent) - .withClient(signingHttp) - .setJsonBody(payload) - .callback(new JsonCallbackHandler() { - @Override - public void onSuccess(JsonObject data, Response response) { - if (data == null) { - finishWithError(new AppError(TAG, 1332, AppError.CODE_MAINTENANCE, response)); - return; - } - try { - apiRequestCallback.onSuccess(data); - } - catch (Exception e) { - finishWithError(new AppError(TAG, 1339, AppError.CODE_OTHER, response, e, data)); - } - } - - @Override - public void onFailure(Response response, Throwable throwable) { - finishWithError(new AppError(TAG, 1345, AppError.CODE_OTHER, response, throwable)); - } - }) - .build() - .enqueue(); - } - - private void getStudentList(StudentListCallback studentListCallback, boolean reportStudentsWithNoSemester) { - apiRequest(ENDPOINT_STUDENT_LIST, null, data -> { - d(TAG, "Got: " + data.toString()); - JsonElement listEl = data.get("Data"); - JsonArray accountList; - if (listEl == null || listEl instanceof JsonNull || (accountList = listEl.getAsJsonArray()).size() == 0) { - finishWithError(new AppError(TAG, 1369, AppError.CODE_OTHER, app.getString(R.string.sync_error_register_no_students), data)); - return; - } - LinkedHashMap usersMap = new LinkedHashMap<>(); - for (JsonElement userEl : accountList) { - JsonObject user = userEl.getAsJsonObject(); - if (reportStudentsWithNoSemester || (user != null && user.get("IdOkresKlasyfikacyjny").getAsInt() != 0)) { - usersMap.put(user.get("Imie").getAsString() + " " + user.get("Nazwisko").getAsString() + " " + (user.get("OddzialKod") instanceof JsonNull ? "" : user.get("OddzialKod").getAsString()), user); - } else if (accountList.size() == 1) { - finishWithError(new AppError(TAG, 1377, AppError.CODE_OTHER, app.getString(R.string.error_register_student_no_term), data)); - return; - } - } - studentListCallback.onSuccess(usersMap); - }); - } - - private void saveStudentData(Profile targetProfile, JsonObject account) { - String firstName = account.get("Imie").getAsString(); - String lastName = account.get("Nazwisko").getAsString(); - schoolName = loginStore.getLoginData("deviceSymbol", getSymbolFromApiUrl())+"_"+account.get("JednostkaSprawozdawczaSymbol").getAsString(); - schoolSymbol = account.get("JednostkaSprawozdawczaSymbol").getAsString(); - studentId = account.get("Id").getAsInt(); - studentLoginId = account.get("UzytkownikLoginId").getAsInt(); - studentClassId = account.get("IdOddzial").getAsInt(); - studentSemesterId = account.get("IdOkresKlasyfikacyjny").getAsInt(); - String studentClassName = account.get("OkresPoziom").getAsInt()+account.get("OddzialSymbol").getAsString(); - targetProfile.putStudentData("userName", account.get("UzytkownikNazwa").getAsString()); - targetProfile.putStudentData("schoolName", schoolName); - targetProfile.putStudentData("schoolSymbol", schoolSymbol); - targetProfile.putStudentData("studentId", studentId); - targetProfile.putStudentData("studentLoginId", studentLoginId); - targetProfile.putStudentData("studentClassId", studentClassId); - targetProfile.putStudentData("studentClassName", studentClassName); - targetProfile.putStudentData("studentSemesterId", studentSemesterId); - targetProfile.putStudentData("currentSemesterEndDate", account.get("OkresDataDo").getAsInt()+86400); - targetProfile.putStudentData("studentSemesterNumber", account.get("OkresNumer").getAsInt()); - targetProfile.setCurrentSemester(account.get("OkresNumer").getAsInt()); - if (targetProfile.getCurrentSemester() == 1) { - targetProfile.setDateSemester1Start(Date.fromMillis((long) account.get("OkresDataOd").getAsInt() * 1000)); - targetProfile.setDateSemester2Start(Date.fromMillis(((long) account.get("OkresDataDo").getAsInt() + 86400) * 1000)); - } - else if (targetProfile.getCurrentSemester() == 2) { - targetProfile.setDateSemester2Start(Date.fromMillis((long) account.get("OkresDataOd").getAsInt() * 1000)); - targetProfile.setDateYearEnd(Date.fromMillis(((long) account.get("OkresDataDo").getAsInt() + 86400) * 1000)); - } - //db.teamDao().add(new Team(profileId, studentClassId, account.get("OddzialKod").getAsString(), 1, -1)); - targetProfile.setStudentNameLong(firstName + " " + lastName); - targetProfile.setStudentNameShort(firstName + " " + lastName.charAt(0) + "."); - if (targetProfile.getName() == null || targetProfile.getName().equals("")) { - targetProfile.setName(targetProfile.getStudentNameLong()); - } - targetProfile.setSubname(account.get("UzytkownikLogin").getAsString()); - } - - private Team searchTeam(String name, String code, long teacherId) { - Team team; - team = Team.getByName(teamList, name); - - if (team == null) { - team = new Team(profileId, crc16(name.getBytes()), name, 2, code, teacherId); - teamList.add(team); - } - else { - team.teacherId = teacherId; - } - return team; - } - - public interface CertificateCallback { - void onSuccess(String certificateKey, String certificatePfx, String apiUrl, String userLogin, String userName); - } - private interface StudentListCallback { - void onSuccess(LinkedHashMap usersMap); - } - private interface ApiRequestCallback { - void onSuccess(JsonObject data); - } - - private String getSymbolFromApiUrl() { - String[] parts = apiUrl.split("/"); - return parts[parts.length - 2]; - } - - private String getClassTeamName() { - if (teamList.size() == 0) - return ""; - if (teamList.get(0).type != 1) - return ""; - return teamList.get(0).name; - } - - private long getClassTeamId() { - if (teamList.size() == 0) - return -1; - if (teamList.get(0).type != 1) - return -1; - return teamList.get(0).id; - } - - private Date getCurrentSemesterStartDate() { - return profile.getSemesterStart(studentSemesterNumber); - } - - private Date getCurrentSemesterEndDate() { - return profile.getSemesterEnd(studentSemesterNumber); - } - - private long getUnixTime() { - return System.currentTimeMillis() / 1000; - } - - private void setApiUrl(String token, String symbol) { - String rule = token.substring(0, 3); - switch (rule) { - case "3S1": - if (!App.devMode) - apiUrl = "https://lekcjaplus.vulcan.net.pl/"+symbol+"/"; - else - apiUrl = "http://hack.szkolny.eu/"+symbol+"/"; - break; - case "TA1": - apiUrl = "https://uonetplus-komunikacja.umt.tarnow.pl/"+symbol+"/"; - break; - case "OP1": - apiUrl = "https://uonetplus-komunikacja.eszkola.opolskie.pl/"+symbol+"/"; - break; - case "RZ1": - apiUrl = "https://uonetplus-komunikacja.resman.pl/"+symbol+"/"; - break; - case "GD1": - apiUrl = "https://uonetplus-komunikacja.edu.gdansk.pl/"+symbol+"/"; - break; - case "KA1": - apiUrl = "https://uonetplus-komunikacja.mcuw.katowice.eu/"+symbol+"/"; - break; - case "KA2": - apiUrl = "https://uonetplus-komunikacja-test.mcuw.katowice.eu/"+symbol+"/"; - break; - case "LU1": - apiUrl = "https://uonetplus-komunikacja.edu.lublin.eu/"+symbol+"/"; - break; - case "LU2": - apiUrl = "https://test-uonetplus-komunikacja.edu.lublin.eu/"+symbol+"/"; - break; - case "P03": - apiUrl = "https://efeb-komunikacja-pro-efebmobile.pro.vulcan.pl/"+symbol+"/"; - break; - case "P01": - apiUrl = "http://efeb-komunikacja.pro-hudson.win.vulcan.pl/"+symbol+"/"; - break; - case "P02": - apiUrl = "http://efeb-komunikacja.pro-hudsonrc.win.vulcan.pl/"+symbol+"/"; - break; - case "P90": - apiUrl = "http://efeb-komunikacja-pro-mwujakowska.neo.win.vulcan.pl/"+symbol+"/"; - break; - case "FK1": - apiUrl = "http://api.fakelog.cf/"+symbol+"/"; - break; - case "SZ9": - //apiUrl = "http://vulcan.szkolny.eu/"+symbol+"/"; - break; - default: - apiUrl = null; - break; - } - } - - /* _____ _ _____ _ - | __ \ | | | __ \ | | - | | | | __ _| |_ __ _ | |__) |___ __ _ _ _ ___ ___| |_ ___ - | | | |/ _` | __/ _` | | _ // _ \/ _` | | | |/ _ \/ __| __/ __| - | |__| | (_| | || (_| | | | \ \ __/ (_| | |_| | __/\__ \ |_\__ \ - |_____/ \__,_|\__\__,_| |_| \_\___|\__, |\__,_|\___||___/\__|___/ - | | - |*/ - private void setPushToken() { - String token; - Pair> pair = app.appConfig.fcmTokens.get(LOGIN_TYPE_VULCAN); - if (pair == null || (token = pair.first) == null || (pair.second != null && pair.second.contains(profileId))) { - r("finish", "SetPushToken"); - return; - } - callback.onActionStarted(R.string.sync_action_setting_push_token); - JsonObject json = new JsonObject(); - json.addProperty("IdUczen", studentId); - json.addProperty("Token", token); - json.addProperty("PushOcena", true); - json.addProperty("PushFrekwencja", true); - json.addProperty("PushUwaga", true); - json.addProperty("PushWiadomosc", true); - apiRequest(schoolSymbol+"/"+ENDPOINT_PUSH, json, result -> { - if (pair.second == null) { - List list = new ArrayList<>(); - list.add(profileId); - app.appConfig.fcmTokens.put(LOGIN_TYPE_VULCAN, new Pair<>(token, list)); - } - else { - pair.second.add(profileId); - app.appConfig.fcmTokens.put(LOGIN_TYPE_VULCAN, new Pair<>(token, pair.second)); - } - r("finish", "SetPushToken"); - }); - } - - private SparseArray> lessonRanges = new SparseArray<>(); - private SparseArray noticeCategories = new SparseArray<>(); - private SparseArray> attendanceCategories = new SparseArray<>(); - private void getDictionaries() { - callback.onActionStarted(R.string.sync_action_syncing_dictionaries); - if (teamList.size() == 0 || teamList.get(0).type != 1) { - String name = profile.getStudentData("studentClassName", null); - if (name != null) { - long id = crc16(name.getBytes()); - teamList.add(new Team(profileId, id, name, 1, schoolName + ":" + name, -1)); - } - } - apiRequest(schoolSymbol+"/"+ENDPOINT_DICTIONARIES, null, result -> { - JsonObject data = result.getAsJsonObject("Data"); - JsonArray teachers = data.getAsJsonArray("Nauczyciele"); - JsonArray subjects = data.getAsJsonArray("Przedmioty"); - JsonArray lessonRanges = data.getAsJsonArray("PoryLekcji"); - JsonArray gradeCategories = data.getAsJsonArray("KategorieOcen"); - JsonArray noticeCategories = data.getAsJsonArray("KategorieUwag"); - JsonArray attendanceCategories = data.getAsJsonArray("KategorieFrekwencji"); - - for (JsonElement teacherEl : teachers) { - JsonObject teacher = teacherEl.getAsJsonObject(); - JsonElement loginId = teacher.get("LoginId"); - teacherList.add( - new Teacher( - profileId, - teacher.get("Id").getAsInt(), - teacher.get("Imie").getAsString(), - teacher.get("Nazwisko").getAsString(), - loginId == null || loginId instanceof JsonNull ? "-1" : loginId.getAsString() - ) - ); - } - - for (JsonElement subjectEl : subjects) { - JsonObject subject = subjectEl.getAsJsonObject(); - subjectList.add( - new Subject( - profileId, - subject.get("Id").getAsInt(), - subject.get("Nazwa").getAsString(), - subject.get("Kod").getAsString() - ) - ); - } - - this.lessonRanges.clear(); - for (JsonElement lessonRangeEl : lessonRanges) { - JsonObject lessonRange = lessonRangeEl.getAsJsonObject(); - this.lessonRanges.put( - lessonRange.get("Id").getAsInt(), - new Pair<>( - Time.fromH_m(lessonRange.get("PoczatekTekst").getAsString()), - Time.fromH_m(lessonRange.get("KoniecTekst").getAsString()) - ) - ); - } - - for (JsonElement gradeCategoryEl : gradeCategories) { - JsonObject gradeCategory = gradeCategoryEl.getAsJsonObject(); - gradeCategoryList.add( - new GradeCategory( - profileId, - gradeCategory.get("Id").getAsInt(), - -1, - -1, - gradeCategory.get("Nazwa").getAsString() - ) - ); - } - - this.noticeCategories.clear(); - for (JsonElement noticeCategoryEl : noticeCategories) { - JsonObject noticeCategory = noticeCategoryEl.getAsJsonObject(); - this.noticeCategories.put( - noticeCategory.get("Id").getAsInt(), - noticeCategory.get("Nazwa").getAsString() - ); - } - - this.attendanceCategories.clear(); - for (JsonElement attendanceCategoryEl : attendanceCategories) { - JsonObject attendanceCategory = attendanceCategoryEl.getAsJsonObject(); - int type = -1; - boolean absent = attendanceCategory.get("Nieobecnosc").getAsBoolean(); - boolean excused = attendanceCategory.get("Usprawiedliwione").getAsBoolean(); - if (absent) { - type = excused ? TYPE_ABSENT_EXCUSED : TYPE_ABSENT; - } - else { - if (attendanceCategory.get("Spoznienie").getAsBoolean()) { - type = excused ? TYPE_BELATED_EXCUSED : TYPE_BELATED; - } - else if (attendanceCategory.get("Zwolnienie").getAsBoolean()) { - type = TYPE_RELEASED; - } - else if (attendanceCategory.get("Obecnosc").getAsBoolean()) { - type = TYPE_PRESENT; - } - } - this.attendanceCategories.put( - attendanceCategory.get("Id").getAsInt(), - new Pair<>( - type, - attendanceCategory.get("Nazwa").getAsString() - ) - ); - } - r("finish", "Dictionaries"); - }); - } - - private void getTimetable() { - if (syncingSemester1) { - // we are in semester 2. we're syncing semester 1 to show old data. skip the timetable. - r("finish", "Timetable"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_timetable); - JsonObject json = new JsonObject(); - json.addProperty("IdUczen", studentId); - - Date weekStart = Week.getWeekStart(); - if (Date.getToday().getWeekDay() > 4) { - weekStart.stepForward(0, 0, 7); - } - Date weekEnd = weekStart.clone().stepForward(0, 0, 6); - - json.addProperty("DataPoczatkowa", weekStart.getStringY_m_d()); - json.addProperty("DataKoncowa", weekEnd.getStringY_m_d()); - json.addProperty("IdOddzial", studentClassId); - json.addProperty("IdOkresKlasyfikacyjny", studentSemesterId); - apiRequest(schoolSymbol+"/"+ENDPOINT_TIMETABLE, json, result -> { - JsonArray lessons = result.getAsJsonArray("Data"); - - for (JsonElement lessonEl: lessons) { - JsonObject lesson = lessonEl.getAsJsonObject(); - - if (!lesson.get("PlanUcznia").getAsBoolean()) { - continue; - } - - Date lessonDate = Date.fromY_m_d(lesson.get("DzienTekst").getAsString()); - Pair lessonRange = lessonRanges.get(lesson.get("IdPoraLekcji").getAsInt()); - Lesson lessonObject = new Lesson( - profileId, - lessonDate.getWeekDay(), - lessonRange.first, - lessonRange.second - ); - - JsonElement subject = lesson.get("IdPrzedmiot"); - if (!(subject instanceof JsonNull)) { - lessonObject.subjectId = subject.getAsInt(); - } - JsonElement teacher = lesson.get("IdPracownik"); - if (!(teacher instanceof JsonNull)) { - lessonObject.teacherId = teacher.getAsInt(); - } - - lessonObject.teamId = getClassTeamId(); - JsonElement team = lesson.get("PodzialSkrot"); - if (team != null && !(team instanceof JsonNull)) { - String name = getClassTeamName()+" "+team.getAsString(); - Team teamObject = searchTeam(name, schoolName+":"+name, lessonObject.teacherId); - lessonObject.teamId = teamObject.id; - } - JsonElement classroom = lesson.get("Sala"); - if (classroom != null && !(classroom instanceof JsonNull)) { - lessonObject.classroomName = classroom.getAsString(); - } - - JsonElement isCancelled = lesson.get("PrzekreslonaNazwa"); - JsonElement oldTeacherId = lesson.get("IdPracownikOld"); - if (isCancelled != null && isCancelled.getAsBoolean()) { - LessonChange lessonChangeObject = new LessonChange( - profileId, - lessonDate, lessonObject.startTime, lessonObject.endTime - ); - lessonChangeObject.type = TYPE_CANCELLED; - lessonChangeObject.teacherId = lessonObject.teacherId; - lessonChangeObject.subjectId = lessonObject.subjectId; - lessonChangeObject.teamId = lessonObject.teamId; - lessonChangeObject.classroomName = lessonObject.classroomName; - - lessonChangeList.add(lessonChangeObject); - metadataList.add(new Metadata(profileId,Metadata.TYPE_LESSON_CHANGE, lessonChangeObject.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - } - else if (!(oldTeacherId instanceof JsonNull)) { - LessonChange lessonChangeObject = new LessonChange( - profileId, - lessonDate, lessonObject.startTime, lessonObject.endTime - ); - lessonChangeObject.type = TYPE_CHANGE; - lessonChangeObject.teacherId = lessonObject.teacherId; - lessonChangeObject.subjectId = lessonObject.subjectId; - lessonChangeObject.teamId = lessonObject.teamId; - lessonChangeObject.classroomName = lessonObject.classroomName; - lessonObject.teacherId = oldTeacherId.getAsInt(); - - lessonChangeList.add(lessonChangeObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_LESSON_CHANGE, lessonChangeObject.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - } - lessonList.add(lessonObject); - } - r("finish", "Timetable"); - }); - } - - private void getGrades() { - callback.onActionStarted(R.string.sync_action_syncing_grades); - JsonObject json = new JsonObject(); - json.addProperty("IdUczen", studentId); - json.addProperty("IdOkresKlasyfikacyjny", studentSemesterId); - apiRequest(schoolSymbol+"/"+ENDPOINT_GRADES, json, result -> { - JsonArray grades = result.getAsJsonArray("Data"); - - for (JsonElement gradeEl: grades) { - JsonObject grade = gradeEl.getAsJsonObject(); - JsonElement name = grade.get("Wpis"); - JsonElement description = grade.get("Opis"); - JsonElement comment = grade.get("Komentarz"); - JsonElement value = grade.get("Wartosc"); - JsonElement modificatorValue = grade.get("WagaModyfikatora"); - JsonElement numerator = grade.get("Licznik"); - JsonElement denominator = grade.get("Mianownik"); - - int id = grade.get("Id").getAsInt(); - int weight = grade.get("WagaOceny").getAsInt(); - int subjectId = grade.get("IdPrzedmiot").getAsInt(); - int teacherId = grade.get("IdPracownikD").getAsInt(); - int categoryId = grade.get("IdKategoria").getAsInt(); - long addedDate = grade.get("DataModyfikacji").getAsLong() * 1000; - - float finalValue = 0.0f; - String finalName; - String finalDescription = ""; - - if (!(numerator instanceof JsonNull) && !(denominator instanceof JsonNull)) { - // calculate the grade's value and name: divide - float numeratorF = numerator.getAsFloat(); - float denominatorF = denominator.getAsFloat(); - finalValue = numeratorF / denominatorF; - weight = 0; - finalName = intToStr(Math.round(finalValue*100))+"%"; - finalDescription += new DecimalFormat("#.##").format(numeratorF)+"/"+new DecimalFormat("#.##").format(denominatorF); - } - else { - // "normal" grade. Get the name and value if set. Otherwise zero the weight. - finalName = name.getAsString(); - if (!(value instanceof JsonNull)) { - finalValue = value.getAsFloat(); - if (!(modificatorValue instanceof JsonNull)) { - finalValue += modificatorValue.getAsFloat(); - } - } - else { - weight = 0; - } - } - - if (!(comment instanceof JsonNull)) { - if (finalName.equals("")) { - finalName = comment.getAsString(); - } - else { - finalDescription += (finalDescription.equals("") ? "" : " ")+comment.getAsString(); - } - } - if (!(description instanceof JsonNull)) { - finalDescription += (finalDescription.equals("") ? "" : " - ")+description.getAsString(); - } - - int semester = studentSemesterNumber; - /*Date addedDateObj = Date.fromMillis(addedDate); - if (app.register.dateSemester2Start != null && addedDateObj.compareTo(app.register.dateSemester2Start) > 0) { - semester = 2; - }*/ - - String category = ""; - for (GradeCategory gradeCategory: gradeCategoryList) { - if (gradeCategory.categoryId == categoryId) { - category = gradeCategory.text; - } - } - - int color = 0xff3D5F9C; - switch (finalName) { - case "1-": - case "1": - case "1+": - color = 0xffd65757; - break; - case "2-": - case "2": - case "2+": - color = 0xff9071b3; - break; - case "3-": - case "3": - case "3+": - color = 0xffd2ab24; - break; - case "4-": - case "4": - case "4+": - color = 0xff50b6d6; - break; - case "5-": - case "5": - case "5+": - color = 0xff2cbd92; - break; - case "6-": - case "6": - case "6+": - color = 0xff91b43c; - break; - } - - Grade gradeObject = new Grade( - profileId, - id, - category, - color, - finalDescription, - finalName, - finalValue, - weight, - semester, - teacherId, - subjectId - ); - - gradeList.add(gradeObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_GRADE, gradeObject.id, profile.getEmpty(), profile.getEmpty(), addedDate)); - } - r("finish", "Grades"); - }); - } - - private void processGradeList(JsonArray jsonGrades, List gradeList, List metadataList, boolean isFinal) { - for (JsonElement gradeEl: jsonGrades) { - JsonObject grade = gradeEl.getAsJsonObject(); - - String name = grade.get("Wpis").getAsString(); - float value = getGradeValue(name); - long subjectId = grade.get("IdPrzedmiot").getAsLong(); - - long id = subjectId * -100 - studentSemesterNumber; - - int color = getVulcanGradeColor(name); - - Grade gradeObject = new Grade( - profileId, - id, - "", - color, - "", - name, - value, - 0, - studentSemesterNumber, - -1, - subjectId - ); - if (studentSemesterNumber == 1) { - gradeObject.type = isFinal ? TYPE_SEMESTER1_FINAL : TYPE_SEMESTER1_PROPOSED; - } - else { - gradeObject.type = isFinal ? TYPE_SEMESTER2_FINAL : TYPE_SEMESTER2_PROPOSED; - } - gradeList.add(gradeObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_GRADE, gradeObject.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - } - } - private void getProposedGrades() { - callback.onActionStarted(R.string.sync_action_syncing_proposition_grades); - JsonObject json = new JsonObject(); - json.addProperty("IdUczen", studentId); - json.addProperty("IdOkresKlasyfikacyjny", studentSemesterId); - apiRequest(schoolSymbol+"/"+ENDPOINT_GRADES_PROPOSITIONS, json, result -> { - JsonObject grades = result.getAsJsonObject("Data"); - JsonArray gradesProposed = grades.getAsJsonArray("OcenyPrzewidywane"); - JsonArray gradesFinal = grades.getAsJsonArray("OcenyKlasyfikacyjne"); - - processGradeList(gradesProposed, gradeList, metadataList, false); - processGradeList(gradesFinal, gradeList, metadataList, true); - r("finish", "ProposedGrades"); - }); - } - - private void getEvents() { - callback.onActionStarted(R.string.sync_action_syncing_exams); - JsonObject json = new JsonObject(); - // from today to the end of the current semester - // or if empty: from the beginning of the semester - json.addProperty("DataPoczatkowa", profile.getEmpty() ? getCurrentSemesterStartDate().getStringY_m_d() : oneMonthBack.getStringY_m_d()); - json.addProperty("DataKoncowa", getCurrentSemesterEndDate().getStringY_m_d()); - json.addProperty("IdOddzial", studentClassId); - json.addProperty("IdUczen", studentId); - json.addProperty("IdOkresKlasyfikacyjny", studentSemesterId); - apiRequest(schoolSymbol+"/"+ENDPOINT_EVENTS, json, result -> { - JsonArray events = result.getAsJsonArray("Data"); - - for (JsonElement eventEl: events) { - JsonObject event = eventEl.getAsJsonObject(); - - int id = event.get("Id").getAsInt(); - - int eventType = event.get("Rodzaj").getAsBoolean() ? TYPE_EXAM : TYPE_SHORT_QUIZ; - - int subjectId = event.get("IdPrzedmiot").getAsInt(); - - Date lessonDate = Date.fromY_m_d(event.get("DataTekst").getAsString()); - Time startTime = null; - - int weekDay = lessonDate.getWeekDay(); - for (Lesson lesson: lessonList) { - if (lesson.weekDay == weekDay && lesson.subjectId == subjectId) { - startTime = lesson.startTime; - } - } - - long teacherId = event.get("IdPracownik").getAsInt(); - - Event eventObject = new Event( - profileId, - id, - lessonDate, - startTime, - event.get("Opis").getAsString(), - -1, - eventType, - false, - teacherId, - subjectId, - getClassTeamId() - ); - - JsonElement team = event.get("PodzialSkrot"); - if (team != null && !(team instanceof JsonNull)) { - String name = getClassTeamName()+" "+team.getAsString(); - Team teamObject = searchTeam(name, schoolName+":"+name, teacherId); - eventObject.teamId = teamObject.id; - } - - eventList.add(eventObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_EVENT, eventObject.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - } - r("finish", "Events"); - }); - } - - private void getHomework() { - callback.onActionStarted(R.string.sync_action_syncing_homework); - JsonObject json = new JsonObject(); - json.addProperty("DataPoczatkowa", profile.getEmpty() ? getCurrentSemesterStartDate().getStringY_m_d() : oneMonthBack.getStringY_m_d()); - json.addProperty("DataKoncowa", getCurrentSemesterEndDate().getStringY_m_d()); - json.addProperty("IdOddzial", studentClassId); - json.addProperty("IdUczen", studentId); - json.addProperty("IdOkresKlasyfikacyjny", studentSemesterId); - apiRequest(schoolSymbol+"/"+ ENDPOINT_HOMEWORK, json, result -> { - JsonArray homeworkList = result.getAsJsonArray("Data"); - - for (JsonElement homeworkEl: homeworkList) { - JsonObject homework = homeworkEl.getAsJsonObject(); - - int id = homework.get("Id").getAsInt(); - - int subjectId = homework.get("IdPrzedmiot").getAsInt(); - - Date lessonDate = Date.fromY_m_d(homework.get("DataTekst").getAsString()); - Time startTime = null; - - int weekDay = lessonDate.getWeekDay(); - for (Lesson lesson: lessonList) { - if (lesson.weekDay == weekDay && lesson.subjectId == subjectId) { - startTime = lesson.startTime; - } - } - - Event eventObject = new Event( - profileId, - id, - lessonDate, - startTime, - homework.get("Opis").getAsString(), - -1, - Event.TYPE_HOMEWORK, - false, - homework.get("IdPracownik").getAsInt(), - subjectId, - getClassTeamId() - ); - - eventList.add(eventObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_HOMEWORK, eventObject.id, profile.getEmpty(), profile.getEmpty(), System.currentTimeMillis())); - } - r("finish", "Homework"); - }); - } - - private void getNotices() { - callback.onActionStarted(R.string.sync_action_syncing_notices); - JsonObject json = new JsonObject(); - json.addProperty("IdUczen", studentId); - json.addProperty("IdOkresKlasyfikacyjny", studentSemesterId); - apiRequest(schoolSymbol+"/"+ENDPOINT_NOTICES, json, result -> { - JsonArray notices = result.getAsJsonArray("Data"); - - for (JsonElement noticeEl: notices) { - JsonObject notice = noticeEl.getAsJsonObject(); - - int id = notice.get("Id").getAsInt(); - long addedDate = Date.fromY_m_d(notice.get("DataWpisuTekst").getAsString()).getInMillis(); - - int semester = studentSemesterNumber; - /*Date addedDateObj = Date.fromMillis(addedDate); - if (profile.dateSemester2Start != null && addedDateObj.compareTo(profile.dateSemester2Start) > 0) { - semester = 2; - }*/ - - Notice noticeObject = new Notice( - profileId, - id, - (notice.get("IdKategoriaUwag") instanceof JsonNull ? "" : noticeCategories.get(notice.get("IdKategoriaUwag").getAsInt())) +"\n"+notice.get("TrescUwagi").getAsString(), - semester, - TYPE_NEUTRAL, - notice.get("IdPracownik").getAsInt() - ); - - noticeList.add(noticeObject); - metadataList.add(new Metadata(profileId, Metadata.TYPE_NOTICE, noticeObject.id, profile.getEmpty(), profile.getEmpty(), addedDate)); - } - r("finish", "Notices"); - }); - } - - private void getAttendance() { - callback.onActionStarted(R.string.sync_action_syncing_attendance); - JsonObject json = new JsonObject(); - json.addProperty("DataPoczatkowa", true ? getCurrentSemesterStartDate().getStringY_m_d() : oneMonthBack.getStringY_m_d()); - json.addProperty("DataKoncowa", getCurrentSemesterEndDate().getStringY_m_d()); - json.addProperty("IdOddzial", studentClassId); - json.addProperty("IdUczen", studentId); - json.addProperty("IdOkresKlasyfikacyjny", studentSemesterId); - apiRequest(schoolSymbol+"/"+ ENDPOINT_ATTENDANCE, json, result -> { - JsonArray attendanceList = result.getAsJsonObject("Data").getAsJsonArray("Frekwencje"); - - for (JsonElement attendanceEl: attendanceList) { - JsonObject attendance = attendanceEl.getAsJsonObject(); - - Pair attendanceCategory = attendanceCategories.get(attendance.get("IdKategoria").getAsInt()); - if (attendanceCategory == null) - continue; - - int type = attendanceCategory.first; - - int id = attendance.get("Dzien").getAsInt() + attendance.get("Numer").getAsInt(); - - long lessonDateMillis = Date.fromY_m_d(attendance.get("DzienTekst").getAsString()).getInMillis(); - Date lessonDate = Date.fromMillis(lessonDateMillis); - - int lessonSemester = profile.dateToSemester(lessonDate); - - Attendance attendanceObject = new Attendance( - profileId, - id, - 0, - attendance.get("IdPrzedmiot").getAsInt(), - lessonSemester, - attendance.get("PrzedmiotNazwa").getAsString()+" - "+attendanceCategory.second, - lessonDate, - lessonRanges.get(attendance.get("IdPoraLekcji").getAsInt()).first, - type); - - this.attendanceList.add(attendanceObject); - if (attendanceObject.type != TYPE_PRESENT) { - metadataList.add(new Metadata(profileId, Metadata.TYPE_ATTENDANCE, attendanceObject.id, profile.getEmpty(), profile.getEmpty(), attendanceObject.lessonDate.combineWith(attendanceObject.startTime))); - } - } - r("finish", "Attendance"); - }); - } - - private void getMessagesInbox() { - callback.onActionStarted(R.string.sync_action_syncing_messages_inbox); - JsonObject json = new JsonObject(); - json.addProperty("DataPoczatkowa", true ? getCurrentSemesterStartDate().getInUnix() : oneMonthBack.getInUnix()); - json.addProperty("DataKoncowa", getCurrentSemesterEndDate().getInUnix()); - json.addProperty("LoginId", studentLoginId); - json.addProperty("IdUczen", studentId); - apiRequest(schoolSymbol+"/"+ENDPOINT_MESSAGES_RECEIVED, json, result -> { - JsonArray messages = result.getAsJsonArray("Data"); - - for (JsonElement messageEl: messages) { - JsonObject message = messageEl.getAsJsonObject(); - - long id = message.get("WiadomoscId").getAsLong(); - - long senderId = -1; - int senderLoginId = message.get("NadawcaId").getAsInt(); - String senderLoginIdStr = String.valueOf(senderLoginId); - - for (Teacher teacher: teacherList) { - if (senderLoginIdStr.equals(teacher.loginId)) { - senderId = teacher.id; - } - } - - String subject = message.get("Tytul").getAsString(); - String body = message.get("Tresc").getAsString(); - body = body.replaceAll("\n", "
    "); - - long addedDate = message.get("DataWyslaniaUnixEpoch").getAsLong() * 1000; - long readDate = 0; - JsonElement readDateUnix; - if (!((readDateUnix = message.get("DataPrzeczytaniaUnixEpoch")) instanceof JsonNull)) { - readDate = readDateUnix.getAsLong() * 1000L; - } - - Message messageObject = new Message(profileId, id, subject, body, TYPE_RECEIVED, senderId, -1); - MessageRecipient messageRecipientObject = new MessageRecipient(profileId, -1, -1, readDate, id); - - messageList.add(messageObject); - messageRecipientList.add(messageRecipientObject); - messageMetadataList.add(new Metadata(profileId, TYPE_MESSAGE, id, readDate > 0, readDate > 0 || profile.getEmpty(), addedDate)); - } - r("finish", "MessagesInbox"); - }); - } - - private void getMessagesOutbox() { - if (!fullSync && onlyFeature != FEATURE_MESSAGES_OUTBOX) { - r("finish", "MessagesOutbox"); - return; - } - callback.onActionStarted(R.string.sync_action_syncing_messages_outbox); - JsonObject json = new JsonObject(); - json.addProperty("DataPoczatkowa", true ? getCurrentSemesterStartDate().getInUnix() : oneMonthBack.getInUnix()); - json.addProperty("DataKoncowa", getCurrentSemesterEndDate().getInUnix()); - json.addProperty("LoginId", studentLoginId); - json.addProperty("IdUczen", studentId); - apiRequest(schoolSymbol+"/"+ENDPOINT_MESSAGES_SENT, json, result -> { - JsonArray messages = result.getAsJsonArray("Data"); - - for (JsonElement jMessageEl: messages) { - JsonObject jMessage = jMessageEl.getAsJsonObject(); - - long messageId = jMessage.get("WiadomoscId").getAsLong(); - - String subject = jMessage.get("Tytul").getAsString(); - - String body = jMessage.get("Tresc").getAsString(); - body = body.replaceAll("\n", "
    "); - - long sentDate = jMessage.get("DataWyslaniaUnixEpoch").getAsLong() * 1000; - - Message message = new Message( - profileId, - messageId, - subject, - body, - TYPE_SENT, - -1, - -1 - ); - - int readBy = jMessage.get("Przeczytane").getAsInt(); - int unreadBy = jMessage.get("Nieprzeczytane").getAsInt(); - for (JsonElement recipientEl: jMessage.getAsJsonArray("Adresaci")) { - JsonObject recipient = recipientEl.getAsJsonObject(); - long recipientId = -1; - int recipientLoginId = recipient.get("LoginId").getAsInt(); - String recipientLoginIdStr = String.valueOf(recipientLoginId); - for (Teacher teacher: teacherList) { - if (recipientLoginIdStr.equals(teacher.loginId)) { - recipientId = teacher.id; - } - } - MessageRecipient messageRecipient = new MessageRecipient( - profileId, - recipientId, - -1, - readBy == 0 ? 0 : unreadBy == 0 ? 1 : -1, - /*messageId*/ messageId - ); - messageRecipientIgnoreList.add(messageRecipient); - } - - messageList.add(message); - metadataList.add(new Metadata(profileId, Metadata.TYPE_MESSAGE, messageId, true, true, sentDate)); - } - r("finish", "MessagesOutbox"); - }); - } - - /* __ __ - | \/ | - | \ / | ___ ___ ___ __ _ __ _ ___ ___ - | |\/| |/ _ \/ __/ __|/ _` |/ _` |/ _ \/ __| - | | | | __/\__ \__ \ (_| | (_| | __/\__ \ - |_| |_|\___||___/___/\__,_|\__, |\___||___/ - __/ | - |__*/ - @Override - public void getMessage(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile, @NonNull MessageFull message, @NonNull MessageGetCallback messageCallback) { - if (message.body != null) { - message.recipients = app.db.messageRecipientDao().getAllByMessageId(profile.getId(), message.id); - for (MessageRecipientFull recipient: message.recipients) { - if (recipient.id == -1) - recipient.fullName = profile.getStudentNameLong(); - } - if (!message.seen) { - studentId = profile.getStudentData("studentId", -1); - studentLoginId = profile.getStudentData("studentLoginId", -1); - JsonObject json = new JsonObject(); - json.addProperty("WiadomoscId", message.id); - json.addProperty("FolderWiadomosci", "Odebrane"); - json.addProperty("Status", "Widoczna"); - json.addProperty("LoginId", studentLoginId); - json.addProperty("IdUczen", studentId); - apiRequest(schoolSymbol+"/"+ENDPOINT_MESSAGES_CHANGE_STATUS, json, result -> { }); - app.db.metadataDao().setSeen(profile.getId(), message, true); - if (message.type != TYPE_SENT) { - app.db.messageRecipientDao().add(new MessageRecipient(profile.getId(), -1, -1, System.currentTimeMillis(), message.id)); - } - } - new Handler(activityContext.getMainLooper()).post(() -> { - messageCallback.onSuccess(message); - }); - return; - } - } - - @Override - public void getAttachment(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile, @NonNull MessageFull message, long attachmentId, @NonNull AttachmentGetCallback attachmentCallback) { - - } - - @Override - public void getRecipientList(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile, @NonNull RecipientListGetCallback recipientListGetCallback) { - - } - - @Override - public MessagesComposeInfo getComposeInfo(@NonNull ProfileFull profile) { - return new MessagesComposeInfo(0, 0, -1, -1); - } - - @Override - public void syncMessages(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile) { - - } - - @Override - public Map getConfigurableEndpoints(Profile profile) { - return null; - } - - @Override - public boolean isEndpointEnabled(Profile profile, boolean defaultActive, String name) { - return defaultActive; - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/EdziennikTask.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/EdziennikTask.kt new file mode 100644 index 00000000..ab27dda9 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/EdziennikTask.kt @@ -0,0 +1,162 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-1-16. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik + +import com.google.gson.JsonObject +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.Edudziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.Librus +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.Mobidziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.Podlasie +import pl.szczodrzynski.edziennik.data.api.edziennik.template.Template +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.Vulcan +import pl.szczodrzynski.edziennik.data.api.events.RegisterAvailabilityEvent +import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikCallback +import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.api.task.IApiTask +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.data.db.full.AnnouncementFull +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.data.db.full.MessageFull +import pl.szczodrzynski.edziennik.utils.Utils.d +import pl.szczodrzynski.edziennik.utils.managers.AvailabilityManager.Error.Type + +open class EdziennikTask(override val profileId: Int, val request: Any) : IApiTask(profileId) { + companion object { + private const val TAG = "EdziennikTask" + + var profile: Profile? = null + var loginStore: LoginStore? = null + + fun firstLogin(loginStore: LoginStore) = EdziennikTask(-1, FirstLoginRequest(loginStore)) + fun sync() = EdziennikTask(-1, SyncRequest()) + fun syncProfile(profileId: Int, viewIds: List>? = null, onlyEndpoints: List? = null, arguments: JsonObject? = null) = EdziennikTask(profileId, SyncProfileRequest(viewIds, onlyEndpoints, arguments)) + fun syncProfileList(profileList: List) = EdziennikTask(-1, SyncProfileListRequest(profileList)) + fun messageGet(profileId: Int, message: MessageFull) = EdziennikTask(profileId, MessageGetRequest(message)) + fun messageSend(profileId: Int, recipients: List, subject: String, text: String) = EdziennikTask(profileId, MessageSendRequest(recipients, subject, text)) + fun announcementsRead(profileId: Int) = EdziennikTask(profileId, AnnouncementsReadRequest()) + fun announcementGet(profileId: Int, announcement: AnnouncementFull) = EdziennikTask(profileId, AnnouncementGetRequest(announcement)) + fun attachmentGet(profileId: Int, owner: Any, attachmentId: Long, attachmentName: String) = EdziennikTask(profileId, AttachmentGetRequest(owner, attachmentId, attachmentName)) + fun recipientListGet(profileId: Int) = EdziennikTask(profileId, RecipientListGetRequest()) + fun eventGet(profileId: Int, event: EventFull) = EdziennikTask(profileId, EventGetRequest(event)) + } + + private lateinit var loginStore: LoginStore + + override fun prepare(app: App) { + if (request is FirstLoginRequest) { + // get the requested profile and login store + this.profile = null + loginStore = request.loginStore + // save the profile ID and name as the current task's + taskName = app.getString(R.string.edziennik_notification_api_first_login_title) + } else { + // get the requested profile and login store + val profile = app.db.profileDao().getByIdNow(profileId) ?: return + this.profile = profile + val loginStore = app.db.loginStoreDao().getByIdNow(profile.loginStoreId) ?: return + this.loginStore = loginStore + // save the profile ID and name as the current task's + taskName = app.getString(R.string.edziennik_notification_api_sync_title_format, profile.name) + } + EdziennikTask.profile = this.profile + EdziennikTask.loginStore = this.loginStore + } + + private var edziennikInterface: EdziennikInterface? = null + + internal fun run(app: App, taskCallback: EdziennikCallback) { + profile?.let { profile -> + if (profile.archived) { + d(TAG, "The profile $profileId is archived") + taskCallback.onError(ApiError(TAG, ERROR_PROFILE_ARCHIVED)) + return + } + else if (profile.shouldArchive()) { + d(TAG, "The profile $profileId's year ended on ${profile.dateYearEnd}, archiving") + ProfileArchiver(app, profile) + } + if (profile.isBeforeYear()) { + d(TAG, "The profile $profileId's school year has not started yet; aborting sync") + cancel() + taskCallback.onCompleted() + return + } + + val error = app.availabilityManager.check(profile) + when (error?.type) { + Type.NOT_AVAILABLE -> { + if (EventBus.getDefault().hasSubscriberForEvent(RegisterAvailabilityEvent::class.java)) { + EventBus.getDefault().postSticky(RegisterAvailabilityEvent()) + } + cancel() + taskCallback.onCompleted() + return + } + Type.API_ERROR -> { + taskCallback.onError(error.apiError!!) + return + } + else -> return@let + } + } + + edziennikInterface = when (loginStore.type) { + LOGIN_TYPE_LIBRUS -> Librus(app, profile, loginStore, taskCallback) + LOGIN_TYPE_MOBIDZIENNIK -> Mobidziennik(app, profile, loginStore, taskCallback) + LOGIN_TYPE_VULCAN -> Vulcan(app, profile, loginStore, taskCallback) + LOGIN_TYPE_EDUDZIENNIK -> Edudziennik(app, profile, loginStore, taskCallback) + LOGIN_TYPE_PODLASIE -> Podlasie(app, profile, loginStore, taskCallback) + LOGIN_TYPE_TEMPLATE -> Template(app, profile, loginStore, taskCallback) + else -> null + } + if (edziennikInterface == null) { + return + } + + when (request) { + is SyncProfileRequest -> edziennikInterface?.sync( + featureIds = request.viewIds?.flatMap { Features.getIdsByView(it.first, it.second) } + ?: Features.getAllIds(), + viewId = request.viewIds?.get(0)?.first, + onlyEndpoints = request.onlyEndpoints, + arguments = request.arguments) + is MessageGetRequest -> edziennikInterface?.getMessage(request.message) + is MessageSendRequest -> edziennikInterface?.sendMessage(request.recipients, request.subject, request.text) + is FirstLoginRequest -> edziennikInterface?.firstLogin() + is AnnouncementsReadRequest -> edziennikInterface?.markAllAnnouncementsAsRead() + is AnnouncementGetRequest -> edziennikInterface?.getAnnouncement(request.announcement) + is AttachmentGetRequest -> edziennikInterface?.getAttachment(request.owner, request.attachmentId, request.attachmentName) + is RecipientListGetRequest -> edziennikInterface?.getRecipientList() + is EventGetRequest -> edziennikInterface?.getEvent(request.event) + } + } + + override fun cancel() { + d(TAG, "Task ${toString()} cancelling...") + edziennikInterface?.cancel() + } + + override fun toString(): String { + return "EdziennikTask(profileId=$profileId, request=$request, edziennikInterface=$edziennikInterface)" + } + + data class FirstLoginRequest(val loginStore: LoginStore) + class SyncRequest + data class SyncProfileRequest(val viewIds: List>? = null, val onlyEndpoints: List? = null, val arguments: JsonObject? = null) + data class SyncProfileListRequest(val profileList: List) + data class MessageGetRequest(val message: MessageFull) + data class MessageSendRequest(val recipients: List, val subject: String, val text: String) + class AnnouncementsReadRequest + data class AnnouncementGetRequest(val announcement: AnnouncementFull) + data class AttachmentGetRequest(val owner: Any, val attachmentId: Long, val attachmentName: String) + class RecipientListGetRequest + data class EventGetRequest(val event: EventFull) +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/ProfileArchiver.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/ProfileArchiver.kt new file mode 100644 index 00000000..27c61abc --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/ProfileArchiver.kt @@ -0,0 +1,97 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-8-25. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik + +import android.content.Intent +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.Intent +import pl.szczodrzynski.edziennik.utils.Utils.d +import pl.szczodrzynski.edziennik.utils.models.Date + +class ProfileArchiver(val app: App, val profile: Profile) { + companion object { + private const val TAG = "ProfileArchiver" + } + + init { + if (profile.archiveId == null) + profile.archiveId = profile.id + d(TAG, "Processing ${profile.name}#${profile.id}, archiveId = ${profile.archiveId}") + + profile.archived = true + app.db.profileDao().add(profile) + //app.db.metadataDao().setAllSeen(profile.id, true) + app.db.notificationDao().clear(profile.id) + app.db.endpointTimerDao().clear(profile.id) + d(TAG, "Archived profile ${profile.id} saved") + profile.archived = false + + // guess the nearest school year + val today = Date.getToday() + profile.studentSchoolYearStart = when { + today.month <= profile.dateYearEnd.month -> today.year - 1 + else -> today.year + } + + // set default semester dates + profile.dateSemester1Start = Date(profile.studentSchoolYearStart, 9, 1) + profile.dateSemester2Start = Date(profile.studentSchoolYearStart + 1, 2, 1) + profile.dateYearEnd = Date(profile.studentSchoolYearStart + 1, 6, 30) + + val oldId = profile.id + val newId = (app.db.profileDao().lastId ?: profile.id) + 1 + profile.id = newId + profile.subname = "Nowy rok szkolny - ${profile.studentSchoolYearStart}" + profile.studentClassName = null + + d(TAG, "New profile ID for ${profile.name}: ${profile.id}") + + when (profile.loginStoreType) { + LOGIN_TYPE_LIBRUS -> { + profile.removeStudentData("isPremium") + profile.removeStudentData("pushDeviceId") + profile.removeStudentData("startPointsSemester1") + profile.removeStudentData("startPointsSemester2") + profile.removeStudentData("enablePointGrades") + profile.removeStudentData("enableDescriptiveGrades") + } + LOGIN_TYPE_MOBIDZIENNIK -> { + + } + LOGIN_TYPE_VULCAN -> { + // DataVulcan.isApiLoginValid() returns false so it will update the semester + profile.removeStudentData("currentSemesterEndDate") + profile.removeStudentData("studentSemesterId") + profile.removeStudentData("studentSemesterNumber") + profile.removeStudentData("semester1Id") + profile.removeStudentData("semester2Id") + profile.removeStudentData("studentClassId") + } + LOGIN_TYPE_IDZIENNIK -> { + profile.removeStudentData("schoolYearId") + } + LOGIN_TYPE_EDUDZIENNIK -> { + + } + LOGIN_TYPE_PODLASIE -> { + + } + } + + d(TAG, "Processed student data: ${profile.studentData}") + + app.db.profileDao().add(profile) + + if (app.profileId == oldId) { + val intent = Intent( + Intent.ACTION_MAIN, + "profileId" to newId + ) + app.sendBroadcast(intent) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/DataEdudziennik.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/DataEdudziennik.kt new file mode 100644 index 00000000..76b0e9fd --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/DataEdudziennik.kt @@ -0,0 +1,125 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-22 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik + +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_EDUDZIENNIK_WEB +import pl.szczodrzynski.edziennik.data.api.models.Data +import pl.szczodrzynski.edziennik.data.db.entity.EventType +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.* + +/** + * Use http://patorjk.com/software/taag/#p=display&f=Big for the ascii art + * + * Use https://codepen.io/kubasz/pen/RwwwbGN to easily generate the student data getters/setters + */ +class DataEdudziennik(app: App, profile: Profile?, loginStore: LoginStore) : Data(app, profile, loginStore) { + + fun isWebLoginValid() = webSessionIdExpiryTime-30 > currentTimeUnix() && webSessionId.isNotNullNorEmpty() + + override fun satisfyLoginMethods() { + loginMethods.clear() + if (isWebLoginValid()) { + loginMethods += LOGIN_METHOD_EDUDZIENNIK_WEB + } + } + + override fun generateUserCode() = "$schoolName:$loginEmail:${studentId?.crc32()}" + + private var mLoginEmail: String? = null + var loginEmail: String? + get() { mLoginEmail = mLoginEmail ?: loginStore.getLoginData("email", null); return mLoginEmail } + set(value) { loginStore.putLoginData("email", value); mLoginEmail = value } + + private var mLoginPassword: String? = null + var loginPassword: String? + get() { mLoginPassword = mLoginPassword ?: loginStore.getLoginData("password", null); return mLoginPassword } + set(value) { loginStore.putLoginData("password", value); mLoginPassword = value } + + private var mStudentId: String? = null + var studentId: String? + get() { mStudentId = mStudentId ?: profile?.getStudentData("studentId", null); return mStudentId } + set(value) { profile?.putStudentData("studentId", value) ?: return; mStudentId = value } + + private var mSchoolId: String? = null + var schoolId: String? + get() { mSchoolId = mSchoolId ?: profile?.getStudentData("schoolId", null); return mSchoolId } + set(value) { profile?.putStudentData("schoolId", value) ?: return; mSchoolId = value } + + private var mClassId: String? = null + var classId: String? + get() { mClassId = mClassId ?: profile?.getStudentData("classId", null); return mClassId } + set(value) { profile?.putStudentData("classId", value) ?: return; mClassId = value } + + /* __ __ _ + \ \ / / | | + \ \ /\ / /__| |__ + \ \/ \/ / _ \ '_ \ + \ /\ / __/ |_) | + \/ \/ \___|_._*/ + private var mWebSessionId: String? = null + var webSessionId: String? + get() { mWebSessionId = mWebSessionId ?: loginStore.getLoginData("webSessionId", null); return mWebSessionId } + set(value) { loginStore.putLoginData("webSessionId", value); mWebSessionId = value } + + private var mWebSessionIdExpiryTime: Long? = null + var webSessionIdExpiryTime: Long + get() { mWebSessionIdExpiryTime = mWebSessionIdExpiryTime ?: loginStore.getLoginData("webSessionIdExpiryTime", 0L); return mWebSessionIdExpiryTime ?: 0L } + set(value) { loginStore.putLoginData("webSessionIdExpiryTime", value); mWebSessionIdExpiryTime = value } + + /* ____ _ _ + / __ \| | | | + | | | | |_| |__ ___ _ __ + | | | | __| '_ \ / _ \ '__| + | |__| | |_| | | | __/ | + \____/ \__|_| |_|\___|*/ + private var mCurrentSemester: Int? = null + var currentSemester: Int + get() { mCurrentSemester = mCurrentSemester ?: profile?.getStudentData("currentSemester", 1); return mCurrentSemester ?: 1 } + set(value) { profile?.putStudentData("currentSemester", value) ?: return; mCurrentSemester = value } + + private var mSchoolName: String? = null + var schoolName: String? + get() { mSchoolName = mSchoolName ?: profile?.getStudentData("schoolName", null); return mSchoolName } + set(value) { profile?.putStudentData("schoolName", value) ?: return; mSchoolName = value } + + val studentEndpoint: String + get() = "Students/$studentId/" + + val schoolEndpoint: String + get() = "Schools/$schoolId/" + + val classStudentEndpoint: String + get() = "Class/$studentId/" + + val schoolClassEndpoint: String + get() = "Schools/$classId/" + + val studentAndClassEndpoint: String + get() = "Students/$studentId/Klass/$classId/" + + val studentAndClassesEndpoint: String + get() = "Students/$studentId/Classes/$classId/" + + val timetableEndpoint: String + get() = "Plan/$studentId/" + + val studentAndTeacherClassEndpoint: String + get() = "Students/$studentId/Teachers/$classId/" + + val courseStudentEndpoint: String + get() = "Course/$studentId/" + + fun getEventType(longId: String, name: String): EventType { + val id = longId.crc16().toLong() + return eventTypes.singleOrNull { it.id == id } ?: run { + val eventType = EventType(profileId, id, name, colorFromName(name)) + eventTypes.put(id, eventType) + eventType + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/Edudziennik.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/Edudziennik.kt new file mode 100644 index 00000000..23d9d3b1 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/Edudziennik.kt @@ -0,0 +1,142 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-22 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.EdudziennikData +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web.EdudziennikWebGetAnnouncement +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web.EdudziennikWebGetHomework +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.firstlogin.EdudziennikFirstLogin +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.login.EdudziennikLogin +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.login.EdudziennikLoginWeb +import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikCallback +import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.data.db.full.AnnouncementFull +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.data.db.full.MessageFull +import pl.szczodrzynski.edziennik.utils.Utils.d + +class Edudziennik(val app: App, val profile: Profile?, val loginStore: LoginStore, val callback: EdziennikCallback) : EdziennikInterface { + companion object { + private const val TAG = "Edudziennik" + } + + val internalErrorList = mutableListOf() + val data: DataEdudziennik + private var afterLogin: (() -> Unit)? = null + + init { + data = DataEdudziennik(app, profile, loginStore).apply { + callback = wrapCallback(this@Edudziennik.callback) + satisfyLoginMethods() + } + } + + private fun completed() { + data.saveData() + callback.onCompleted() + } + + /* _______ _ _ _ _ _ + |__ __| | /\ | | (_) | | | + | | | |__ ___ / \ | | __ _ ___ _ __ _| |_| |__ _ __ ___ + | | | '_ \ / _ \ / /\ \ | |/ _` |/ _ \| '__| | __| '_ \| '_ ` _ \ + | | | | | | __/ / ____ \| | (_| | (_) | | | | |_| | | | | | | | | + |_| |_| |_|\___| /_/ \_\_|\__, |\___/|_| |_|\__|_| |_|_| |_| |_| + __/ | + |__*/ + override fun sync(featureIds: List, viewId: Int?, onlyEndpoints: List?, arguments: JsonObject?) { + data.arguments = arguments + data.prepare(edudziennikLoginMethods, EdudziennikFeatures, featureIds, viewId, onlyEndpoints) + login() + } + + private fun login(loginMethodId: Int? = null, afterLogin: (() -> Unit)? = null) { + d(TAG, "Trying to login with ${data.targetLoginMethodIds}") + if (internalErrorList.isNotEmpty()) { + d(TAG, " - Internal errors:") + internalErrorList.forEach { d(TAG, " - code $it") } + } + loginMethodId?.let { data.prepareFor(edudziennikLoginMethods, it) } + afterLogin?.let { this.afterLogin = it } + EdudziennikLogin(data) { + data() + } + } + + private fun data() { + d(TAG, "Endpoint IDs: ${data.targetEndpointIds}") + if (internalErrorList.isNotEmpty()) { + d(TAG, " - Internal errors:") + internalErrorList.forEach { d(TAG, " - code $it") } + } + afterLogin?.invoke() ?: EdudziennikData(data) { + completed() + } + } + + override fun getMessage(message: MessageFull) {} + override fun sendMessage(recipients: List, subject: String, text: String) {} + override fun markAllAnnouncementsAsRead() {} + + override fun getAnnouncement(announcement: AnnouncementFull) { + EdudziennikLoginWeb(data) { + EdudziennikWebGetAnnouncement(data, announcement) { + completed() + } + } + } + + override fun getAttachment(owner: Any, attachmentId: Long, attachmentName: String) {} + override fun getRecipientList() {} + + override fun getEvent(eventFull: EventFull) { + EdudziennikLoginWeb(data) { + EdudziennikWebGetHomework(data, eventFull) { + completed() + } + } + } + + override fun firstLogin() { EdudziennikFirstLogin(data) { completed() } } + override fun cancel() { + d(TAG, "Cancelled") + data.cancel() + } + + private fun wrapCallback(callback: EdziennikCallback): EdziennikCallback { + return object : EdziennikCallback { + override fun onCompleted() { callback.onCompleted() } + override fun onProgress(step: Float) { callback.onProgress(step) } + override fun onStartProgress(stringRes: Int) { callback.onStartProgress(stringRes) } + override fun onError(apiError: ApiError) { + if (apiError.errorCode in internalErrorList) { + // finish immediately if the same error occurs twice during the same sync + callback.onError(apiError) + return + } + internalErrorList.add(apiError.errorCode) + when (apiError.errorCode) { + ERROR_EDUDZIENNIK_WEB_SESSION_EXPIRED -> { + login() + } + ERROR_LOGIN_EDUDZIENNIK_WEB_NO_SESSION_ID -> { + login() + } + ERROR_EDUDZIENNIK_WEB_LIMITED_ACCESS -> { + data() + } + else -> callback.onError(apiError) + } + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/EdudziennikFeatures.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/EdudziennikFeatures.kt new file mode 100644 index 00000000..c3fd17ed --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/EdudziennikFeatures.kt @@ -0,0 +1,74 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-23 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik + +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.models.Feature + +const val ENDPOINT_EDUDZIENNIK_WEB_START = 1000 +const val ENDPOINT_EDUDZIENNIK_WEB_TEACHERS = 1001 +const val ENDPOINT_EDUDZIENNIK_WEB_GRADES = 1011 +const val ENDPOINT_EDUDZIENNIK_WEB_TIMETABLE = 1012 +const val ENDPOINT_EDUDZIENNIK_WEB_EXAMS = 1013 +const val ENDPOINT_EDUDZIENNIK_WEB_ATTENDANCE = 1014 +const val ENDPOINT_EDUDZIENNIK_WEB_ANNOUNCEMENTS = 1015 +const val ENDPOINT_EDUDZIENNIK_WEB_HOMEWORK = 1016 +const val ENDPOINT_EDUDZIENNIK_WEB_EVENTS = 1017 +const val ENDPOINT_EDUDZIENNIK_WEB_NOTES = 1018 +const val ENDPOINT_EDUDZIENNIK_WEB_LUCKY_NUMBER = 1030 + +val EdudziennikFeatures = listOf( + /* School and team info and subjects */ + Feature(LOGIN_TYPE_EDUDZIENNIK, FEATURE_STUDENT_INFO, listOf( + ENDPOINT_EDUDZIENNIK_WEB_START to LOGIN_METHOD_EDUDZIENNIK_WEB + ), listOf(LOGIN_METHOD_EDUDZIENNIK_WEB)), + + /* Teachers */ + Feature(LOGIN_TYPE_EDUDZIENNIK, FEATURE_TEACHERS, listOf( + ENDPOINT_EDUDZIENNIK_WEB_TEACHERS to LOGIN_METHOD_EDUDZIENNIK_WEB + ), listOf(LOGIN_METHOD_EDUDZIENNIK_WEB)), + + /* Timetable */ + Feature(LOGIN_TYPE_EDUDZIENNIK, FEATURE_TIMETABLE, listOf( + ENDPOINT_EDUDZIENNIK_WEB_TIMETABLE to LOGIN_METHOD_EDUDZIENNIK_WEB + ), listOf(LOGIN_METHOD_EDUDZIENNIK_WEB)), + + /* Grades */ + Feature(LOGIN_TYPE_EDUDZIENNIK, FEATURE_GRADES, listOf( + ENDPOINT_EDUDZIENNIK_WEB_GRADES to LOGIN_METHOD_EDUDZIENNIK_WEB + ), listOf(LOGIN_METHOD_EDUDZIENNIK_WEB)), + + /* Agenda */ + Feature(LOGIN_TYPE_EDUDZIENNIK, FEATURE_AGENDA, listOf( + ENDPOINT_EDUDZIENNIK_WEB_EXAMS to LOGIN_METHOD_EDUDZIENNIK_WEB, + ENDPOINT_EDUDZIENNIK_WEB_HOMEWORK to LOGIN_METHOD_EDUDZIENNIK_WEB, + ENDPOINT_EDUDZIENNIK_WEB_EVENTS to LOGIN_METHOD_EDUDZIENNIK_WEB + ), listOf(LOGIN_METHOD_EDUDZIENNIK_WEB)), + + /* Homework */ + Feature(LOGIN_TYPE_EDUDZIENNIK, FEATURE_HOMEWORK, listOf( + ENDPOINT_EDUDZIENNIK_WEB_HOMEWORK to LOGIN_METHOD_EDUDZIENNIK_WEB + ), listOf(LOGIN_METHOD_EDUDZIENNIK_WEB)), + + /* Behaviour */ + Feature(LOGIN_TYPE_EDUDZIENNIK, FEATURE_BEHAVIOUR, listOf( + ENDPOINT_EDUDZIENNIK_WEB_NOTES to LOGIN_METHOD_EDUDZIENNIK_WEB + ), listOf(LOGIN_METHOD_EDUDZIENNIK_WEB)), + + /* Attendance */ + Feature(LOGIN_TYPE_EDUDZIENNIK, FEATURE_ATTENDANCE, listOf( + ENDPOINT_EDUDZIENNIK_WEB_ATTENDANCE to LOGIN_METHOD_EDUDZIENNIK_WEB + ), listOf(LOGIN_METHOD_EDUDZIENNIK_WEB)), + + /* Announcements */ + Feature(LOGIN_TYPE_EDUDZIENNIK, FEATURE_ANNOUNCEMENTS, listOf( + ENDPOINT_EDUDZIENNIK_WEB_ANNOUNCEMENTS to LOGIN_METHOD_EDUDZIENNIK_WEB + ), listOf(LOGIN_METHOD_EDUDZIENNIK_WEB)), + + /* Lucky number */ + Feature(LOGIN_TYPE_EDUDZIENNIK, FEATURE_LUCKY_NUMBER, listOf( + ENDPOINT_EDUDZIENNIK_WEB_LUCKY_NUMBER to LOGIN_METHOD_EDUDZIENNIK_WEB + ), listOf(LOGIN_METHOD_EDUDZIENNIK_WEB)) +) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/EdudziennikData.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/EdudziennikData.kt new file mode 100644 index 00000000..7eb58d1c --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/EdudziennikData.kt @@ -0,0 +1,88 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-22 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data + +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web.* +import pl.szczodrzynski.edziennik.utils.Utils + +class EdudziennikData(val data: DataEdudziennik, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "EdudziennikData" + } + + init { + nextEndpoint(onSuccess) + } + + private fun nextEndpoint(onSuccess: () -> Unit) { + if (data.targetEndpointIds.isEmpty()) { + onSuccess() + return + } + if (data.cancelled) { + onSuccess() + return + } + val id = data.targetEndpointIds.firstKey() + val lastSync = data.targetEndpointIds.remove(id) + useEndpoint(id, lastSync) { endpointId -> + data.progress(data.progressStep) + nextEndpoint(onSuccess) + } + } + + private fun useEndpoint(endpointId: Int, lastSync: Long?, onSuccess: (endpointId: Int) -> Unit) { + Utils.d(TAG, "Using endpoint $endpointId. Last sync time = $lastSync") + when (endpointId) { + ENDPOINT_EDUDZIENNIK_WEB_START -> { + data.startProgress(R.string.edziennik_progress_endpoint_data) + EdudziennikWebStart(data, lastSync, onSuccess) + } + ENDPOINT_EDUDZIENNIK_WEB_TEACHERS -> { + data.startProgress(R.string.edziennik_progress_endpoint_teachers) + EdudziennikWebTeachers(data, lastSync, onSuccess) + } + ENDPOINT_EDUDZIENNIK_WEB_GRADES -> { + data.startProgress(R.string.edziennik_progress_endpoint_grades) + EdudziennikWebGrades(data, lastSync, onSuccess) + } + ENDPOINT_EDUDZIENNIK_WEB_TIMETABLE -> { + data.startProgress(R.string.edziennik_progress_endpoint_timetable) + EdudziennikWebTimetable(data, lastSync, onSuccess) + } + ENDPOINT_EDUDZIENNIK_WEB_EXAMS -> { + data.startProgress(R.string.edziennik_progress_endpoint_exams) + EdudziennikWebExams(data, lastSync, onSuccess) + } + ENDPOINT_EDUDZIENNIK_WEB_ATTENDANCE -> { + data.startProgress(R.string.edziennik_progress_endpoint_attendance) + EdudziennikWebAttendance(data, lastSync, onSuccess) + } + ENDPOINT_EDUDZIENNIK_WEB_ANNOUNCEMENTS -> { + data.startProgress(R.string.edziennik_progress_endpoint_announcements) + EdudziennikWebAnnouncements(data, lastSync, onSuccess) + } + ENDPOINT_EDUDZIENNIK_WEB_HOMEWORK -> { + data.startProgress(R.string.edziennik_progress_endpoint_homework) + EdudziennikWebHomework(data, lastSync, onSuccess) + } + ENDPOINT_EDUDZIENNIK_WEB_EVENTS -> { + data.startProgress(R.string.edziennik_progress_endpoint_events) + EdudziennikWebEvents(data, lastSync, onSuccess) + } + ENDPOINT_EDUDZIENNIK_WEB_NOTES -> { + data.startProgress(R.string.edziennik_progress_endpoint_notices) + EdudziennikWebNotes(data, lastSync, onSuccess) + } + ENDPOINT_EDUDZIENNIK_WEB_LUCKY_NUMBER -> { + data.startProgress(R.string.edziennik_progress_endpoint_lucky_number) + EdudziennikWebLuckyNumber(data, lastSync, onSuccess) + } + else -> onSuccess(endpointId) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/EdudziennikWeb.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/EdudziennikWeb.kt new file mode 100644 index 00000000..f5adfc5d --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/EdudziennikWeb.kt @@ -0,0 +1,90 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-22 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data + +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.callback.TextCallbackHandler +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.utils.Utils.d +import pl.szczodrzynski.edziennik.utils.models.Date + +open class EdudziennikWeb(open val data: DataEdudziennik, open val lastSync: Long?) { + companion object { + private const val TAG = "EdudziennikWeb" + } + + val profileId + get() = data.profile?.id ?: -1 + + val profile + get() = data.profile + + fun webGet(tag: String, endpoint: String, xhr: Boolean = false, semester: Int? = null, onSuccess: (text: String) -> Unit) { + val url = "https://dziennikel.appspot.com/" + when (endpoint.endsWith('/') || endpoint.contains('?') || endpoint.isEmpty()) { + true -> endpoint + else -> "$endpoint/" + } + (semester?.let { "?semester=" + if(it == -1) "all" else it } ?: "") + + d(tag, "Request: Edudziennik/Web - $url") + + val callback = object : TextCallbackHandler() { + override fun onSuccess(text: String?, response: Response?) { + if (text == null || response == null) { + data.error(ApiError(tag, ERROR_RESPONSE_EMPTY) + .withResponse(response)) + return + } + + if (semester == null && url.contains("start")) { + profile?.also { profile -> + val cookies = data.app.cookieJar.getAll("dziennikel.appspot.com") + val semesterCookie = cookies["semester"]?.toIntOrNull() + + semesterCookie?.let { data.currentSemester = it } + + if (semesterCookie == 2 && profile.dateSemester2Start > Date.getToday()) + profile.dateSemester2Start = Date.getToday().stepForward(0, 0, -1) + } + } + + try { + onSuccess(text) + } catch (e: Exception) { + data.error(ApiError(tag, EXCEPTION_EDUDZIENNIK_WEB_REQUEST) + .withThrowable(e) + .withResponse(response) + .withApiResponse(text)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + val error = when (response?.code()) { + 402 -> ERROR_EDUDZIENNIK_WEB_LIMITED_ACCESS + 403 -> ERROR_EDUDZIENNIK_WEB_SESSION_EXPIRED + else -> ERROR_REQUEST_FAILURE + } + data.error(ApiError(tag, error) + .withResponse(response) + .withThrowable(throwable)) + } + } + + data.app.cookieJar.set("dziennikel.appspot.com", "sessionid", data.webSessionId) + + Request.builder() + .url(url) + .userAgent(EDUDZIENNIK_USER_AGENT) + .apply { + if (xhr) header("X-Requested-With", "XMLHttpRequest") + } + .get() + .callback(callback) + .build() + .enqueue() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebAnnouncements.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebAnnouncements.kt new file mode 100644 index 00000000..a577a123 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebAnnouncements.kt @@ -0,0 +1,75 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-26 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web + +import org.jsoup.Jsoup +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_ANNOUNCEMENT_ID +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.ENDPOINT_EDUDZIENNIK_WEB_ANNOUNCEMENTS +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.EdudziennikWeb +import pl.szczodrzynski.edziennik.data.db.entity.Announcement +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.crc32 +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.utils.models.Date + +class EdudziennikWebAnnouncements(override val data: DataEdudziennik, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : EdudziennikWeb(data, lastSync) { + companion object { + const val TAG = "EdudziennikWebAnnouncements" + } + + init { data.profile?.also { profile -> + webGet(TAG, data.schoolClassEndpoint + "Announcements") { text -> + val doc = Jsoup.parse(text) + + if (doc.getElementsByClass("message").text().trim() != "Brak ogłoszeń.") { + doc.select("table.list tbody tr").forEach { announcementElement -> + val titleElement = announcementElement.child(0).child(0) + + val longId = EDUDZIENNIK_ANNOUNCEMENT_ID.find(titleElement.attr("href"))?.get(1) + ?: return@forEach + val id = longId.crc32() + val subject = titleElement.text() + + val teacherName = announcementElement.child(1).text() + val teacher = data.getTeacherByFirstLast(teacherName) + + val dateString = announcementElement.getElementsByClass("datetime").first()?.text() + val startDate = Date.fromY_m_d(dateString) + val addedDate = Date.fromIsoHm(dateString) + + val announcementObject = Announcement( + profileId = profileId, + id = id, + subject = subject, + text = null, + startDate = startDate, + endDate = null, + teacherId = teacher.id, + addedDate = addedDate + ).also { + it.idString = longId + } + + data.announcementList.add(announcementObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_ANNOUNCEMENT, + id, + profile.empty, + profile.empty + )) + } + } + + data.setSyncNext(ENDPOINT_EDUDZIENNIK_WEB_ANNOUNCEMENTS, SYNC_ALWAYS) + onSuccess(ENDPOINT_EDUDZIENNIK_WEB_ANNOUNCEMENTS) + } + } ?: onSuccess(ENDPOINT_EDUDZIENNIK_WEB_ANNOUNCEMENTS) } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebAttendance.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebAttendance.kt new file mode 100644 index 00000000..02ba0c85 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebAttendance.kt @@ -0,0 +1,114 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-24 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web + +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_ATTENDANCE_ENTRIES +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_ATTENDANCE_TYPE +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_ATTENDANCE_TYPES +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.ENDPOINT_EDUDZIENNIK_WEB_ATTENDANCE +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.EdudziennikWeb +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.crc32 +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.ext.singleOrNull +import pl.szczodrzynski.edziennik.utils.models.Date +import java.util.* + +class EdudziennikWebAttendance(override val data: DataEdudziennik, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : EdudziennikWeb(data, lastSync) { + companion object { + private const val TAG = "EdudziennikWebAttendance" + } + + private var requestSemester: Int? = null + + init { + if (profile?.empty == true && data.currentSemester == 2) requestSemester = 1 + getAttendances() + } + + private fun getAttendances() { data.profile?.also { profile -> + webGet(TAG, data.studentEndpoint + "Presence", semester = requestSemester) { text -> + + val attendanceTypes = EDUDZIENNIK_ATTENDANCE_TYPES.find(text)?.get(1)?.split(',')?.map { + val type = EDUDZIENNIK_ATTENDANCE_TYPE.find(it.trim()) + val symbol = type?.get(1)?.trim() ?: "?" + val name = type?.get(2)?.trim() ?: "nieznany rodzaj" + return@map Triple( + symbol, + name, + when (name.lowercase()) { + "obecność" -> Attendance.TYPE_PRESENT + "nieobecność" -> Attendance.TYPE_ABSENT + "spóźnienie" -> Attendance.TYPE_BELATED + "nieobecność usprawiedliwiona" -> Attendance.TYPE_ABSENT_EXCUSED + "dzień wolny" -> Attendance.TYPE_DAY_FREE + "brak zajęć" -> Attendance.TYPE_DAY_FREE + "oddelegowany" -> Attendance.TYPE_RELEASED + else -> Attendance.TYPE_UNKNOWN + } + ) + } ?: emptyList() + + EDUDZIENNIK_ATTENDANCE_ENTRIES.findAll(text).forEach { attendanceElement -> + val date = Date.fromY_m_d(attendanceElement[1]) + val lessonNumber = attendanceElement[2].toInt() + val attendanceSymbol = attendanceElement[3] + + val lessons = data.app.db.timetableDao().getAllForDateNow(profileId, date) + val lesson = lessons.firstOrNull { it.lessonNumber == lessonNumber } + + val id = "${date.stringY_m_d}:$lessonNumber:$attendanceSymbol".crc32() + + val (typeSymbol, typeName, baseType) = attendanceTypes.firstOrNull { (symbol, _, _) -> symbol == attendanceSymbol } + ?: return@forEach + + val startTime = data.lessonRanges.singleOrNull { it.lessonNumber == lessonNumber }?.startTime + ?: return@forEach + + val attendanceObject = Attendance( + profileId = profileId, + id = id, + baseType = baseType, + typeName = typeName, + typeShort = data.app.attendanceManager.getTypeShort(baseType), + typeSymbol = typeSymbol, + typeColor = null, + date = date, + startTime = lesson?.displayStartTime ?: startTime, + semester = profile.currentSemester, + teacherId = lesson?.displayTeacherId ?: -1, + subjectId = lesson?.displaySubjectId ?: -1 + ).also { + it.lessonNumber = lessonNumber + } + + data.attendanceList.add(attendanceObject) + if (baseType != Attendance.TYPE_PRESENT) { + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_ATTENDANCE, + id, + profile.empty || baseType == Attendance.TYPE_PRESENT_CUSTOM || baseType == Attendance.TYPE_UNKNOWN, + profile.empty || baseType == Attendance.TYPE_PRESENT_CUSTOM || baseType == Attendance.TYPE_UNKNOWN + )) + } + } + + if (profile.empty && requestSemester == 1 && data.currentSemester == 2) { + requestSemester = null + getAttendances() + } else { + data.setSyncNext(ENDPOINT_EDUDZIENNIK_WEB_ATTENDANCE, SYNC_ALWAYS) + onSuccess(ENDPOINT_EDUDZIENNIK_WEB_ATTENDANCE) + } + } + } ?: onSuccess(ENDPOINT_EDUDZIENNIK_WEB_ATTENDANCE) } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebEvents.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebEvents.kt new file mode 100644 index 00000000..a296723c --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebEvents.kt @@ -0,0 +1,70 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-1-1 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web + +import org.jsoup.Jsoup +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_EVENT_ID +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.ENDPOINT_EDUDZIENNIK_WEB_EVENTS +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.EdudziennikWeb +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.crc32 +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.utils.models.Date + +class EdudziennikWebEvents(override val data: DataEdudziennik, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : EdudziennikWeb(data, lastSync) { + companion object { + const val TAG = "EdudziennikWebEvents" + } + + init { data.profile?.also { profile -> + webGet(TAG, data.studentAndClassesEndpoint + "KlassEvent", xhr = true) { text -> + val doc = Jsoup.parseBodyFragment("" + text.trim() + "
    ") + + doc.getElementsByTag("tr").forEach { eventElement -> + val date = Date.fromY_m_d(eventElement.child(1).text()) + + val titleElement = eventElement.child(2).child(0) + val title = titleElement.text().trim() + + val id = EDUDZIENNIK_EVENT_ID.find(titleElement.attr("href"))?.get(1)?.crc32() + ?: return@forEach + + val eventObject = Event( + profileId = profileId, + id = id, + date = date, + time = null, + topic = title, + color = null, + type = Event.TYPE_CLASS_EVENT, + teacherId = -1, + subjectId = -1, + teamId = data.teamClass?.id ?: -1 + ) + + data.eventList.add(eventObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_EVENT, + id, + profile.empty, + profile.empty + )) + } + + data.toRemove.add(DataRemoveModel.Events.futureWithType(Event.TYPE_CLASS_EVENT)) + + data.setSyncNext(ENDPOINT_EDUDZIENNIK_WEB_EVENTS, SYNC_ALWAYS) + onSuccess(ENDPOINT_EDUDZIENNIK_WEB_EVENTS) + } + } ?: onSuccess(ENDPOINT_EDUDZIENNIK_WEB_EVENTS) } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebExams.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebExams.kt new file mode 100644 index 00000000..a30cb421 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebExams.kt @@ -0,0 +1,90 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-24 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web + +import org.jsoup.Jsoup +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_EVENT_TYPE_ID +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_EXAM_ID +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_SUBJECT_ID +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.ENDPOINT_EDUDZIENNIK_WEB_EXAMS +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.EdudziennikWeb +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.crc32 +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.utils.models.Date + +class EdudziennikWebExams(override val data: DataEdudziennik, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : EdudziennikWeb(data, lastSync) { + companion object { + const val TAG = "EdudziennikWebExams" + } + + init { profile?.also { profile -> + webGet(TAG, data.studentAndClassEndpoint + "Evaluations", xhr = true) { text -> + val doc = Jsoup.parseBodyFragment("" + text.trim() + "
    ") + + doc.select("tr").forEach { examElement -> + val id = EDUDZIENNIK_EXAM_ID.find(examElement.child(0).child(0).attr("href")) + ?.get(1)?.crc32() ?: return@forEach + val topic = examElement.child(0).text().trim() + + val subjectElement = examElement.child(1).child(0) + val subjectId = EDUDZIENNIK_SUBJECT_ID.find(subjectElement.attr("href"))?.get(1) + ?: return@forEach + val subjectName = subjectElement.text().trim() + val subject = data.getSubject(subjectId.crc32(), subjectName) + + val dateString = examElement.child(2).text().trim() + if (dateString.isBlank()) return@forEach + val date = Date.fromY_m_d(dateString) + + val lessons = data.app.db.timetableDao().getAllForDateNow(profileId, date) + val startTime = lessons.firstOrNull { it.displaySubjectId == subject.id }?.displayStartTime + + val eventTypeElement = examElement.child(3).child(0) + val eventTypeId = EDUDZIENNIK_EVENT_TYPE_ID.find(eventTypeElement.attr("href"))?.get(1) + ?: return@forEach + val eventTypeName = eventTypeElement.text() + val eventType = data.getEventType(eventTypeId, eventTypeName) + + val eventObject = Event( + profileId = profileId, + id = id, + date = date, + time = startTime, + topic = topic, + color = null, + type = eventType.id, + teacherId = -1, + subjectId = subject.id, + teamId = data.teamClass?.id ?: -1 + ) + + data.eventList.add(eventObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_EVENT, + id, + profile.empty, + profile.empty + )) + } + + data.toRemove.add(DataRemoveModel.Events.futureExceptTypes(listOf( + Event.TYPE_HOMEWORK, + Event.TYPE_CLASS_EVENT + ))) + + data.setSyncNext(ENDPOINT_EDUDZIENNIK_WEB_EXAMS, SYNC_ALWAYS) + onSuccess(ENDPOINT_EDUDZIENNIK_WEB_EXAMS) + } + }} +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebGetAnnouncement.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebGetAnnouncement.kt new file mode 100644 index 00000000..5584b555 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebGetAnnouncement.kt @@ -0,0 +1,35 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-26 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web + +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.data.api.Regexes +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.EdudziennikWeb +import pl.szczodrzynski.edziennik.data.api.events.AnnouncementGetEvent +import pl.szczodrzynski.edziennik.data.db.full.AnnouncementFull +import pl.szczodrzynski.edziennik.ext.get + +class EdudziennikWebGetAnnouncement(override val data: DataEdudziennik, + private val announcement: AnnouncementFull, + val onSuccess: () -> Unit +) : EdudziennikWeb(data, null) { + companion object { + const val TAG = "EdudziennikWebGetAnnouncement" + } + + init { + webGet(TAG, "Announcement/${announcement.idString}") { text -> + val description = Regexes.EDUDZIENNIK_ANNOUNCEMENT_DESCRIPTION.find(text)?.get(1)?.trim() ?: "" + + announcement.text = description + + EventBus.getDefault().postSticky(AnnouncementGetEvent(announcement)) + + data.announcementList.add(announcement) + onSuccess() + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebGetHomework.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebGetHomework.kt new file mode 100644 index 00000000..d6c568ab --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebGetHomework.kt @@ -0,0 +1,47 @@ +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web + +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.data.api.Regexes +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.EdudziennikWeb +import pl.szczodrzynski.edziennik.data.api.events.EventGetEvent +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty +import pl.szczodrzynski.edziennik.utils.html.BetterHtml + +class EdudziennikWebGetHomework( + override val data: DataEdudziennik, + val event: EventFull, + val onSuccess: () -> Unit +) : EdudziennikWeb(data, null) { + companion object { + const val TAG = "EdudziennikWebGetHomework" + } + + init { + if (event.attachmentNames.isNotNullNorEmpty()) { + val id = event.attachmentNames!![0] + + webGet(TAG, "Homework/$id") { text -> + val description = Regexes.EDUDZIENNIK_HOMEWORK_DESCRIPTION.find(text)?.get(1)?.trim() + + if (description != null) + event.topic = BetterHtml.fromHtml(context = null, description).toString() + + event.homeworkBody = "" + event.isDownloaded = true + event.attachmentNames = null + + data.eventList += event + data.eventListReplace = true + + EventBus.getDefault().postSticky(EventGetEvent(event)) + onSuccess() + } + } else { + EventBus.getDefault().postSticky(EventGetEvent(event)) + onSuccess() + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebGrades.kt new file mode 100644 index 00000000..3ffba09b --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebGrades.kt @@ -0,0 +1,230 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-25 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web + +import android.graphics.Color +import org.jsoup.Jsoup +import pl.szczodrzynski.edziennik.data.api.Regexes +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.ENDPOINT_EDUDZIENNIK_WEB_GRADES +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.EdudziennikWeb +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Grade +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_NORMAL +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_POINT_SUM +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_SEMESTER1_FINAL +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_SEMESTER1_PROPOSED +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_SEMESTER2_FINAL +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_SEMESTER2_PROPOSED +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.colorFromCssName +import pl.szczodrzynski.edziennik.ext.crc32 +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.utils.Utils +import pl.szczodrzynski.edziennik.utils.models.Date + +class EdudziennikWebGrades(override val data: DataEdudziennik, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : EdudziennikWeb(data, lastSync) { + companion object { + private const val TAG = "EdudziennikWebGrades" + } + + private var requestSemester: Int? = null + + init { + if (profile?.empty == true && data.currentSemester == 2) requestSemester = 1 + getGrades() + } + + private fun getGrades() { data.profile?.also { profile -> + webGet(TAG, data.studentEndpoint + "start", semester = requestSemester) { text -> + val semester = requestSemester ?: data.currentSemester + + val doc = Jsoup.parse(text) + val subjects = doc.select("#student_grades tbody").firstOrNull()?.children() + + subjects?.forEach { subjectElement -> + if (subjectElement.id().isBlank()) return@forEach + + val subjectId = subjectElement.id().trim() + val subjectName = subjectElement.child(0).text().trim() + val subject = data.getSubject(subjectId.crc32(), subjectName) + + val gradeType = when { + subjectElement.select("#sum").text().isNotBlank() -> TYPE_POINT_SUM + else -> TYPE_NORMAL + } + + val gradeCountToAverage = subjectElement.select("#avg").text().isNotBlank() + + val grades = subjectElement.select(".grade[data-edited]") + val gradesInfo = subjectElement.select(".grade-tip") + + val gradeValues = if (grades.isNotEmpty()) { + subjects.select(".avg-$subjectId .grade-tip > p").first() + ?.text()?.split('+')?.map { + val split = it.split('*') + val value = split[1].trim().toFloatOrNull() + val weight = value?.let { split[0].trim().toFloatOrNull() } ?: 0f + + Pair(value ?: 0f, weight) + } ?: emptyList() + } else emptyList() + + grades.forEachIndexed { index, gradeElement -> + val id = Regexes.EDUDZIENNIK_GRADE_ID.find(gradeElement.attr("href"))?.get(1)?.crc32() + ?: return@forEachIndexed + val (value, weight) = gradeValues[index] + val name = gradeElement.text().trim().let { + if (it.contains(',') || it.contains('.')) { + val replaced = it.replace(',', '.') + val float = replaced.toFloatOrNull() + + if (float != null && float % 1 == 0f) float.toInt().toString() + else it + } else it + } + + val info = gradesInfo[index] + val fullName = info.child(0).text().trim() + val columnName = info.child(4).text().trim() + val comment = info.ownText() + + val description = columnName + if (comment.isNotBlank()) " - $comment" else null + + val teacherName = info.child(1).text() + val teacher = data.getTeacherByLastFirst(teacherName) + + val addedDate = info.child(2).text().split(' ').let { + val day = it[0].toInt() + val month = Utils.monthFromName(it[1]) + val year = it[2].toInt() + + Date(year, month, day).inMillis + } + + val color = Regexes.STYLE_CSS_COLOR.find(gradeElement.attr("style"))?.get(1)?.let { + if (it.startsWith('#')) Color.parseColor(it) + else colorFromCssName(it) + } ?: -1 + + val gradeObject = Grade( + profileId = profileId, + id = id, + name = name, + type = gradeType, + value = value, + weight = if (gradeCountToAverage) weight else 0f, + color = color, + category = fullName, + description = description, + comment = null, + semester = semester, + teacherId = teacher.id, + subjectId = subject.id, + addedDate = addedDate + ) + + data.gradeList.add(gradeObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_GRADE, + id, + profile.empty, + profile.empty + )) + } + + val proposed = subjectElement.select(".proposal").firstOrNull()?.text()?.trim() + + if (proposed != null && proposed.isNotBlank()) { + val proposedGradeObject = Grade( + profileId = profileId, + id = (-1 * subject.id) - 1, + name = proposed, + type = when (semester) { + 1 -> TYPE_SEMESTER1_PROPOSED + else -> TYPE_SEMESTER2_PROPOSED + }, + value = proposed.toFloatOrNull() ?: 0f, + weight = 0f, + color = -1, + category = null, + description = null, + comment = null, + semester = semester, + teacherId = -1, + subjectId = subject.id + ) + + data.gradeList.add(proposedGradeObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_GRADE, + proposedGradeObject.id, + profile.empty, + profile.empty + )) + } + + val final = subjectElement.select(".final").firstOrNull()?.text()?.trim() + + if (final != null && final.isNotBlank()) { + val finalGradeObject = Grade( + profileId = profileId, + id = (-1 * subject.id) - 2, + name = final, + type = when (semester) { + 1 -> TYPE_SEMESTER1_FINAL + else -> TYPE_SEMESTER2_FINAL + }, + value = final.toFloatOrNull() ?: 0f, + weight = 0f, + color = -1, + category = null, + description = null, + comment = null, + semester = semester, + teacherId = -1, + subjectId = subject.id + ) + + data.gradeList.add(finalGradeObject) + data.metadataList.add(Metadata( + data.profileId, + Metadata.TYPE_GRADE, + finalGradeObject.id, + profile.empty, + profile.empty + )) + } + } + + if (!subjects.isNullOrEmpty()) { + data.toRemove.addAll(listOf( + TYPE_NORMAL, + TYPE_POINT_SUM, + TYPE_SEMESTER1_PROPOSED, + TYPE_SEMESTER2_PROPOSED, + TYPE_SEMESTER1_FINAL, + TYPE_SEMESTER2_FINAL + ).map { + DataRemoveModel.Grades.semesterWithType(semester, it) + }) + } + + if (profile.empty && requestSemester == 1 && data.currentSemester == 2) { + requestSemester = null + getGrades() + } else { + data.setSyncNext(ENDPOINT_EDUDZIENNIK_WEB_GRADES, SYNC_ALWAYS) + onSuccess(ENDPOINT_EDUDZIENNIK_WEB_GRADES) + } + } + } ?: onSuccess(ENDPOINT_EDUDZIENNIK_WEB_GRADES) } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebHomework.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebHomework.kt new file mode 100644 index 00000000..176c6d3d --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebHomework.kt @@ -0,0 +1,86 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-29 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web + +import org.jsoup.Jsoup +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_HOMEWORK_ID +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_SUBJECT_ID +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.ENDPOINT_EDUDZIENNIK_WEB_HOMEWORK +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.EdudziennikWeb +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.crc32 +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.utils.models.Date + +class EdudziennikWebHomework(override val data: DataEdudziennik, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : EdudziennikWeb(data, lastSync) { + companion object { + const val TAG = "EdudziennikWebHomework" + } + + init { data.profile?.also { profile -> + webGet(TAG, data.courseStudentEndpoint + "Homework", xhr = true) { text -> + val doc = Jsoup.parseBodyFragment("" + text.trim() + "
    ") + + if (doc.getElementsByClass("message").text().trim() != "Brak prac domowych") { + doc.getElementsByTag("tr").forEach { homeworkElement -> + val dateElement = homeworkElement.getElementsByClass("date").first()?.child(0) ?: return@forEach + val idStr = EDUDZIENNIK_HOMEWORK_ID.find(dateElement.attr("href"))?.get(1) ?: return@forEach + val id = idStr.crc32() + val date = Date.fromY_m_d(dateElement.text()) + + val subjectElement = homeworkElement.child(1).child(0) + val subjectId = EDUDZIENNIK_SUBJECT_ID.find(subjectElement.attr("href"))?.get(1) + ?: return@forEach + val subjectName = subjectElement.text() + val subject = data.getSubject(subjectId.crc32(), subjectName) + + val lessons = data.app.db.timetableDao().getAllForDateNow(profileId, date) + val startTime = lessons.firstOrNull { it.subjectId == subject.id }?.displayStartTime + + val teacherName = homeworkElement.child(2).text() + val teacher = data.getTeacherByFirstLast(teacherName) + + val topic = homeworkElement.child(4).text().trim() + + val eventObject = Event( + profileId = profileId, + id = id, + date = date, + time = startTime, + topic = topic ?: "", + color = null, + type = Event.TYPE_HOMEWORK, + teacherId = teacher.id, + subjectId = subject.id, + teamId = data.teamClass?.id ?: -1 + ) + + eventObject.attachmentNames = mutableListOf(idStr) + + data.eventList.add(eventObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_HOMEWORK, + id, + profile.empty, + profile.empty + )) + } + } + + data.toRemove.add(DataRemoveModel.Events.futureWithType(Event.TYPE_HOMEWORK)) + + data.setSyncNext(ENDPOINT_EDUDZIENNIK_WEB_HOMEWORK, SYNC_ALWAYS) + onSuccess(ENDPOINT_EDUDZIENNIK_WEB_HOMEWORK) + } + } ?: onSuccess(ENDPOINT_EDUDZIENNIK_WEB_HOMEWORK) } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebLuckyNumber.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebLuckyNumber.kt new file mode 100644 index 00000000..db8164c8 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebLuckyNumber.kt @@ -0,0 +1,46 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-23 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web + +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.ENDPOINT_EDUDZIENNIK_WEB_LUCKY_NUMBER +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.EdudziennikWeb +import pl.szczodrzynski.edziennik.data.db.entity.LuckyNumber +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.utils.models.Date + +class EdudziennikWebLuckyNumber(override val data: DataEdudziennik, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : EdudziennikWeb(data, lastSync) { + companion object { + private const val TAG = "EdudziennikWebLuckyNumber" + } + + init { data.profile?.also { profile -> + webGet(TAG, data.schoolEndpoint + "Lucky", xhr = true) { text -> + text.toIntOrNull()?.also { luckyNumber -> + val luckyNumberObject = LuckyNumber( + profileId = profileId, + date = Date.getToday(), + number = luckyNumber + ) + + data.luckyNumberList.add(luckyNumberObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_LUCKY_NUMBER, + luckyNumberObject.date.value.toLong(), + true, + profile.empty + )) + } + + data.setSyncNext(ENDPOINT_EDUDZIENNIK_WEB_LUCKY_NUMBER, SYNC_ALWAYS) + onSuccess(ENDPOINT_EDUDZIENNIK_WEB_LUCKY_NUMBER) + } + } ?: onSuccess(ENDPOINT_EDUDZIENNIK_WEB_LUCKY_NUMBER) } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebNotes.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebNotes.kt new file mode 100644 index 00000000..56457a91 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebNotes.kt @@ -0,0 +1,69 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-1-1 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web + +import org.jsoup.Jsoup +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_NOTE_ID +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.ENDPOINT_EDUDZIENNIK_WEB_NOTES +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.EdudziennikWeb +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.Notice +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.crc32 +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.utils.models.Date + +class EdudziennikWebNotes(override val data: DataEdudziennik, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : EdudziennikWeb(data, lastSync) { + companion object { + const val TAG = "EdudziennikWebNotes" + } + + init { data.profile?.also { profile -> + webGet(TAG, data.classStudentEndpoint + "RegistryNotesStudent", xhr = true) { text -> + val doc = Jsoup.parseBodyFragment("" + text.trim() + "
    ") + + doc.getElementsByTag("tr").forEach { noteElement -> + val dateElement = noteElement.getElementsByClass("date").first()?.child(0) ?: return@forEach + val addedDate = Date.fromY_m_d(dateElement.text()).inMillis + + val id = EDUDZIENNIK_NOTE_ID.find(dateElement.attr("href"))?.get(0)?.crc32() + ?: return@forEach + + val teacherName = noteElement.child(1).text() + val teacher = data.getTeacherByFirstLast(teacherName) + + val description = noteElement.child(3).text() + + val noticeObject = Notice( + profileId = profileId, + id = id, + type = Notice.TYPE_NEUTRAL, + semester = profile.currentSemester, + text = description, + category = null, + points = null, + teacherId = teacher.id, + addedDate = addedDate + ) + + data.noticeList.add(noticeObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_NOTICE, + id, + profile.empty, + profile.empty + )) + } + + data.setSyncNext(ENDPOINT_EDUDZIENNIK_WEB_NOTES, SYNC_ALWAYS) + onSuccess(ENDPOINT_EDUDZIENNIK_WEB_NOTES) + } + } ?: onSuccess(ENDPOINT_EDUDZIENNIK_WEB_NOTES) } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebStart.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebStart.kt new file mode 100644 index 00000000..e415986c --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebStart.kt @@ -0,0 +1,79 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-23 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web + +import pl.szczodrzynski.edziennik.data.api.ERROR_EDUDZIENNIK_WEB_TEAM_MISSING +import pl.szczodrzynski.edziennik.data.api.Regexes +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_SUBJECTS_START +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.ENDPOINT_EDUDZIENNIK_WEB_START +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.EdudziennikWeb +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.db.entity.Team +import pl.szczodrzynski.edziennik.ext.MONTH +import pl.szczodrzynski.edziennik.ext.crc32 +import pl.szczodrzynski.edziennik.ext.firstLettersName +import pl.szczodrzynski.edziennik.ext.get + +class EdudziennikWebStart(override val data: DataEdudziennik, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : EdudziennikWeb(data, lastSync) { + companion object { + private const val TAG = "EdudziennikWebStart" + } + + init { + webGet(TAG, data.studentEndpoint + "start") { text -> + getSchoolAndTeam(text) + getSubjects(text) + + data.setSyncNext(ENDPOINT_EDUDZIENNIK_WEB_START, MONTH) + onSuccess(ENDPOINT_EDUDZIENNIK_WEB_START) + } + } + + private fun getSchoolAndTeam(text: String) { + val schoolId = Regexes.EDUDZIENNIK_SCHOOL_DETAIL_ID.find(text)?.get(1)?.trim() + val schoolLongName = Regexes.EDUDZIENNIK_SCHOOL_DETAIL_NAME.find(text)?.get(1)?.trim() + data.schoolId = schoolId + + val classId = Regexes.EDUDZIENNIK_CLASS_DETAIL_ID.find(text)?.get(1)?.trim() + val className = Regexes.EDUDZIENNIK_CLASS_DETAIL_NAME.find(text)?.get(1)?.trim() + data.classId = classId + + if (classId == null || className == null || schoolId == null || schoolLongName == null) { + data.error(ApiError(TAG, ERROR_EDUDZIENNIK_WEB_TEAM_MISSING) + .withApiResponse(text)) + return + } + + val schoolName = schoolId.crc32().toString() + schoolLongName.firstLettersName + "_edu" + data.schoolName = schoolName + + val teamId = classId.crc32() + val teamCode = "$schoolName:$className" + + val teamObject = Team( + data.profileId, + teamId, + className, + Team.TYPE_CLASS, + teamCode, + -1 + ) + + data.teamClass = teamObject + data.teamList.put(teamObject.id, teamObject) + } + + private fun getSubjects(text: String) { + EDUDZIENNIK_SUBJECTS_START.findAll(text).forEach { + val id = it[1].trim() + val name = it[2].trim() + data.getSubject(id.crc32(), name) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebTeachers.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebTeachers.kt new file mode 100644 index 00000000..115f9919 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebTeachers.kt @@ -0,0 +1,34 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-25 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web + +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_TEACHERS +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.ENDPOINT_EDUDZIENNIK_WEB_TEACHERS +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.EdudziennikWeb +import pl.szczodrzynski.edziennik.ext.MONTH +import pl.szczodrzynski.edziennik.ext.get + +class EdudziennikWebTeachers(override val data: DataEdudziennik, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : EdudziennikWeb(data, lastSync) { + companion object { + private const val TAG = "EdudziennikWebTeachers" + } + + init { + webGet(TAG, data.studentAndTeacherClassEndpoint + "grid") { text -> + EDUDZIENNIK_TEACHERS.findAll(text).forEach { + val lastName = it[1].trim() + val firstName = it[2].trim() + data.getTeacher(firstName, lastName) + } + + data.setSyncNext(ENDPOINT_EDUDZIENNIK_WEB_TEACHERS, MONTH) + onSuccess(ENDPOINT_EDUDZIENNIK_WEB_TEACHERS) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebTimetable.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebTimetable.kt new file mode 100644 index 00000000..6cab6026 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebTimetable.kt @@ -0,0 +1,150 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-23 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web + +import org.jsoup.Jsoup +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_SUBJECT_ID +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_TEACHER_ID +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.ENDPOINT_EDUDZIENNIK_WEB_TIMETABLE +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.EdudziennikWeb +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Lesson +import pl.szczodrzynski.edziennik.data.db.entity.LessonRange +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.crc32 +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.ext.singleOrNull +import pl.szczodrzynski.edziennik.utils.Utils.d +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time +import pl.szczodrzynski.edziennik.utils.models.Week + +class EdudziennikWebTimetable(override val data: DataEdudziennik, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : EdudziennikWeb(data, lastSync) { + companion object { + private const val TAG = "EdudziennikWebTimetable" + } + + init { data.profile?.also { profile -> + + val currentWeekStart = Week.getWeekStart() + + if (Date.getToday().weekDay > 4) { + currentWeekStart.stepForward(0, 0, 7) + } + + val getDate = data.arguments?.getString("weekStart") ?: currentWeekStart.stringY_m_d + + val weekStart = Date.fromY_m_d(getDate) + val weekEnd = weekStart.clone().stepForward(0, 0, 6) + + webGet(TAG, data.timetableEndpoint + "print?date=$getDate") { text -> + val doc = Jsoup.parse(text) + + val dataDays = mutableListOf() + val dataStart = weekStart.clone() + while (dataStart <= weekEnd) { + dataDays += dataStart.value + dataStart.stepForward(0, 0, 1) + } + + val table = doc.select("#Schedule tbody").first() + + if (table?.text()?.contains("Brak planu lekcji.") == false) { + table.children().forEach { row -> + val rowElements = row.children() + + val lessonNumber = rowElements[0].text().toInt() + + val times = rowElements[1].text().split('-') + val startTime = Time.fromH_m(times[0].trim()) + val endTime = Time.fromH_m(times[1].trim()) + + data.lessonRanges.singleOrNull { + it.lessonNumber == lessonNumber && it.startTime == startTime && it.endTime == endTime + } ?: run { + data.lessonRanges.put(lessonNumber, LessonRange(profileId, lessonNumber, startTime, endTime)) + } + + rowElements.subList(2, rowElements.size).forEachIndexed { index, lesson -> + val course = lesson.select(".course").firstOrNull() ?: return@forEachIndexed + val info = course.select("span > span") + + if (info.isEmpty()) return@forEachIndexed + + val type = when (course.hasClass("substitute")) { + true -> Lesson.TYPE_CHANGE + else -> Lesson.TYPE_NORMAL + } + + /* Getting subject */ + + val subjectElement = info[0].child(0) + val subjectId = EDUDZIENNIK_SUBJECT_ID.find(subjectElement.attr("href"))?.get(1) + ?: return@forEachIndexed + val subjectName = subjectElement.text().trim() + val subject = data.getSubject(subjectId.crc32(), subjectName) + + /* Getting teacher */ + + val teacherId = if (info.size >= 2) { + val teacherElement = info[1].child(0) + val teacherLongId = EDUDZIENNIK_TEACHER_ID.find(teacherElement.attr("href"))?.get(1) + val teacherName = teacherElement.text().trim() + data.getTeacherByLastFirst(teacherName, teacherLongId).id + } else null + + val lessonObject = Lesson(profileId, -1).also { + it.type = type + it.date = weekStart.clone().stepForward(0, 0, index) + it.lessonNumber = lessonNumber + it.startTime = startTime + it.endTime = endTime + it.subjectId = subject.id + it.teacherId = teacherId + it.teamId = data.teamClass?.id + + it.id = it.buildId() + } + + data.lessonList.add(lessonObject) + dataDays.remove(lessonObject.date!!.value) + + if (type != Lesson.TYPE_NORMAL) { + val seen = profile.empty || lessonObject.date!! < Date.getToday() + + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_LESSON_CHANGE, + lessonObject.id, + seen, + seen + )) + } + } + } + } + + for (day in dataDays) { + val lessonDate = Date.fromValue(day) + data.lessonList += Lesson(profileId, lessonDate.value.toLong()).apply { + type = Lesson.TYPE_NO_LESSONS + date = lessonDate + } + } + + d(TAG, "Clearing lessons between ${weekStart.stringY_m_d} and ${weekEnd.stringY_m_d} - timetable downloaded for $getDate") + + data.toRemove.add(DataRemoveModel.Timetable.between(weekStart, weekEnd)) + data.setSyncNext(ENDPOINT_EDUDZIENNIK_WEB_TIMETABLE, SYNC_ALWAYS) + onSuccess(ENDPOINT_EDUDZIENNIK_WEB_TIMETABLE) + } + } ?: onSuccess(ENDPOINT_EDUDZIENNIK_WEB_TIMETABLE) } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/firstlogin/EdudziennikFirstLogin.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/firstlogin/EdudziennikFirstLogin.kt new file mode 100644 index 00000000..808435af --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/firstlogin/EdudziennikFirstLogin.kt @@ -0,0 +1,67 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-22 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.firstlogin + +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.data.api.LOGIN_TYPE_EDUDZIENNIK +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_ACCOUNT_NAME_START +import pl.szczodrzynski.edziennik.data.api.Regexes.EDUDZIENNIK_STUDENTS_START +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.EdudziennikWeb +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.login.EdudziennikLoginWeb +import pl.szczodrzynski.edziennik.data.api.events.FirstLoginFinishedEvent +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.fixName +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.ext.getShortName +import pl.szczodrzynski.edziennik.ext.set + +class EdudziennikFirstLogin(val data: DataEdudziennik, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "EdudziennikFirstLogin" + } + + private val web = EdudziennikWeb(data, null) + private val profileList = mutableListOf() + + init { + val loginStoreId = data.loginStore.id + val loginStoreType = LOGIN_TYPE_EDUDZIENNIK + var firstProfileId = loginStoreId + + EdudziennikLoginWeb(data) { + web.webGet(TAG, "") { text -> + val accountNameLong = EDUDZIENNIK_ACCOUNT_NAME_START.find(text)?.get(1)?.fixName() + + EDUDZIENNIK_STUDENTS_START.findAll(text).forEach { + val studentId = it[1] + val studentNameLong = it[2].fixName() + + if (studentId.isBlank() || studentNameLong.isBlank()) return@forEach + + val studentNameShort = studentNameLong.getShortName() + val accountName = if (accountNameLong == studentNameLong) null else accountNameLong + + val profile = Profile( + firstProfileId++, + loginStoreId, + loginStoreType, + studentNameLong, + data.loginEmail, + studentNameLong, + studentNameShort, + accountName + ).apply { + studentData["studentId"] = studentId + } + profileList.add(profile) + } + + EventBus.getDefault().postSticky(FirstLoginFinishedEvent(profileList, data.loginStore)) + onSuccess() + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/login/EdudziennikLogin.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/login/EdudziennikLogin.kt new file mode 100644 index 00000000..1cb2fd07 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/login/EdudziennikLogin.kt @@ -0,0 +1,54 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-22 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.login + +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_EDUDZIENNIK_WEB +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.utils.Utils + +class EdudziennikLogin(val data: DataEdudziennik, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "EdudziennikLogin" + } + + private var cancelled = false + + init { + nextLoginMethod(onSuccess) + } + + private fun nextLoginMethod(onSuccess: () -> Unit) { + if (data.targetLoginMethodIds.isEmpty()) { + onSuccess() + return + } + if (cancelled) { + onSuccess() + return + } + useLoginMethod(data.targetLoginMethodIds.removeAt(0)) { usedMethodId -> + data.progress(data.progressStep) + if (usedMethodId != -1) + data.loginMethods.add(usedMethodId) + nextLoginMethod(onSuccess) + } + } + + private fun useLoginMethod(loginMethodId: Int, onSuccess: (usedMethodId: Int) -> Unit) { + // this should never be true + if (data.loginMethods.contains(loginMethodId)) { + onSuccess(-1) + return + } + Utils.d(TAG, "Using login method $loginMethodId") + when (loginMethodId) { + LOGIN_METHOD_EDUDZIENNIK_WEB -> { + data.startProgress(R.string.edziennik_progress_login_edudziennik_web) + EdudziennikLoginWeb(data) { onSuccess(loginMethodId) } + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/login/EdudziennikLoginWeb.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/login/EdudziennikLoginWeb.kt new file mode 100644 index 00000000..d730fe91 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/login/EdudziennikLoginWeb.kt @@ -0,0 +1,97 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-22 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.login + +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.callback.TextCallbackHandler +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.DataEdudziennik +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.getUnixDate +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty +import pl.szczodrzynski.edziennik.utils.Utils.d + +class EdudziennikLoginWeb(val data: DataEdudziennik, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "EdudziennikLoginWeb" + } + + init { run { + if (data.isWebLoginValid()) { + onSuccess() + } + else { + data.app.cookieJar.clear("dziennikel.appspot.com") + if (data.loginEmail.isNotNullNorEmpty() && data.loginPassword.isNotNullNorEmpty()) { + loginWithCredentials() + } + else { + data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) + } + } + }} + + private fun loginWithCredentials() { + d(TAG, "Request: Edudziennik/Login/Web - https://dziennikel.appspot.com/login/?next=/") + + val callback = object : TextCallbackHandler() { + override fun onSuccess(text: String?, response: Response?) { + if (text == null || response == null) { + data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) + .withResponse(response)) + return + } + + val url = response.raw().request().url().toString() + + if (!url.contains("Student")) { + when { + text.contains("Wprowadzono nieprawidłową nazwę użytkownika lub hasło.") -> ERROR_LOGIN_EDUDZIENNIK_WEB_INVALID_LOGIN + else -> ERROR_LOGIN_EDUDZIENNIK_WEB_OTHER + }.let { errorCode -> + data.error(ApiError(TAG, errorCode) + .withApiResponse(text) + .withResponse(response)) + return + } + } + + val cookies = data.app.cookieJar.getAll("dziennikel.appspot.com") + val sessionId = cookies["sessionid"] + + if (sessionId == null) { + data.error(ApiError(TAG, ERROR_LOGIN_EDUDZIENNIK_WEB_NO_SESSION_ID) + .withResponse(response) + .withApiResponse(text)) + return + } + + data.webSessionId = sessionId + data.webSessionIdExpiryTime = response.getUnixDate() + 45 * 60 /* 45 min */ + onSuccess() + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(TAG, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + Request.builder() + .url("https://dziennikel.appspot.com/login/?next=/") + .userAgent(EDUDZIENNIK_USER_AGENT) + .contentType("application/x-www-form-urlencoded") + .addParameter("email", data.loginEmail) + .addParameter("password", data.loginPassword) + .addParameter("auth_method", "password") + .addParameter("next", "/") + .post() + .callback(callback) + .build() + .enqueue() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/helper/DownloadAttachment.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/helper/DownloadAttachment.kt new file mode 100644 index 00000000..a968818a --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/helper/DownloadAttachment.kt @@ -0,0 +1,70 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-14 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.helper + +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.callback.FileCallbackHandler +import pl.szczodrzynski.edziennik.data.api.ERROR_FILE_DOWNLOAD +import pl.szczodrzynski.edziennik.data.api.ERROR_REQUEST_FAILURE +import pl.szczodrzynski.edziennik.data.api.SYSTEM_USER_AGENT +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.utils.Utils +import java.io.File + +class DownloadAttachment( + fileUrl: String, + val onSuccess: (file: File) -> Unit, + val onProgress: (written: Long, total: Long) -> Unit, + val onError: (apiError: ApiError) -> Unit +) { + companion object { + private const val TAG = "DownloadAttachment" + } + + init { + val targetFile = Utils.getStorageDir() + + val callback = object : FileCallbackHandler(targetFile) { + override fun onSuccess(file: File?, response: Response?) { + if (file == null) { + onError(ApiError(TAG, ERROR_FILE_DOWNLOAD) + .withResponse(response)) + return + } + + try { + onSuccess(file) + } catch (e: Exception) { + onError(ApiError(TAG, ERROR_FILE_DOWNLOAD) + .withResponse(response) + .withThrowable(e)) + } + } + + override fun onProgress(bytesWritten: Long, bytesTotal: Long) { + try { + this@DownloadAttachment.onProgress(bytesWritten, bytesTotal) + } catch (e: Exception) { + onError(ApiError(TAG, ERROR_FILE_DOWNLOAD) + .withThrowable(e)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + onError(ApiError(TAG, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + Request.builder() + .url(fileUrl) + .userAgent(SYSTEM_USER_AGENT) + .callback(callback) + .build() + .enqueue() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/helper/OneDriveDownloadAttachment.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/helper/OneDriveDownloadAttachment.kt new file mode 100644 index 00000000..25b78527 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/helper/OneDriveDownloadAttachment.kt @@ -0,0 +1,105 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-7. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.helper + +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.callback.FileCallbackHandler +import im.wangchao.mhttp.callback.TextCallbackHandler +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.ERROR_ONEDRIVE_DOWNLOAD +import pl.szczodrzynski.edziennik.data.api.ERROR_REQUEST_FAILURE +import pl.szczodrzynski.edziennik.data.api.SYSTEM_USER_AGENT +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.utils.Utils +import java.io.File + +class OneDriveDownloadAttachment( + app: App, + fileUrl: String, + val onSuccess: (file: File) -> Unit, + val onProgress: (written: Long, total: Long) -> Unit, + val onError: (apiError: ApiError) -> Unit +) { + companion object { + private const val TAG = "OneDriveDownloadAttachment" + } + + init { + Request.builder() + .url(fileUrl) + .userAgent(SYSTEM_USER_AGENT) + .withClient(app.httpLazy) + .callback(object : TextCallbackHandler() { + override fun onSuccess(text: String, response: Response) { + val location = response.headers().get("Location") + // https://onedrive.live.com/redir?resid=D75496A2EB87531C!706&authkey=!ABjZeh3pHMqj11Q + if (location?.contains("onedrive.live.com/redir?resid=") != true) { + onError(ApiError(TAG, ERROR_ONEDRIVE_DOWNLOAD) + .withApiResponse(text) + .withResponse(response)) + return + } + val url = location + .replace("onedrive.live.com/redir?resid=", "storage.live.com/items/") + .replace("?", "&") + .replaceFirst("&", "?") + downloadFile(url) + } + + override fun onFailure(response: Response, throwable: Throwable) { + onError(ApiError(TAG, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + }) + .build() + .enqueue() + } + + private fun downloadFile(url: String) { + val targetFile = Utils.getStorageDir() + + val callback = object : FileCallbackHandler(targetFile) { + override fun onSuccess(file: File?, response: Response?) { + if (file == null) { + onError(ApiError(TAG, ERROR_ONEDRIVE_DOWNLOAD) + .withResponse(response)) + return + } + + try { + onSuccess(file) + } catch (e: Exception) { + onError(ApiError(TAG, ERROR_ONEDRIVE_DOWNLOAD) + .withResponse(response) + .withThrowable(e)) + } + } + + override fun onProgress(bytesWritten: Long, bytesTotal: Long) { + try { + this@OneDriveDownloadAttachment.onProgress(bytesWritten, bytesTotal) + } catch (e: Exception) { + onError(ApiError(TAG, ERROR_ONEDRIVE_DOWNLOAD) + .withThrowable(e)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + onError(ApiError(TAG, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + Request.builder() + .url(url) + .userAgent(SYSTEM_USER_AGENT) + .callback(callback) + .build() + .enqueue() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/DataLibrus.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/DataLibrus.kt new file mode 100644 index 00000000..5d82191d --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/DataLibrus.kt @@ -0,0 +1,284 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-21. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus + +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_LIBRUS_API +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_LIBRUS_MESSAGES +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_LIBRUS_PORTAL +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_LIBRUS_SYNERGIA +import pl.szczodrzynski.edziennik.data.api.models.Data +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.currentTimeUnix +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty + +class DataLibrus(app: App, profile: Profile?, loginStore: LoginStore) : Data(app, profile, loginStore) { + + fun isPortalLoginValid() = portalTokenExpiryTime-30 > currentTimeUnix() && portalRefreshToken.isNotNullNorEmpty() && portalAccessToken.isNotNullNorEmpty() + fun isApiLoginValid() = apiTokenExpiryTime-30 > currentTimeUnix() && apiAccessToken.isNotNullNorEmpty() + fun isSynergiaLoginValid() = synergiaSessionIdExpiryTime-30 > currentTimeUnix() && synergiaSessionId.isNotNullNorEmpty() + fun isMessagesLoginValid() = messagesSessionIdExpiryTime-30 > currentTimeUnix() && messagesSessionId.isNotNullNorEmpty() + + override fun satisfyLoginMethods() { + loginMethods.clear() + if (isPortalLoginValid()) + loginMethods += LOGIN_METHOD_LIBRUS_PORTAL + if (isApiLoginValid()) + loginMethods += LOGIN_METHOD_LIBRUS_API + if (isSynergiaLoginValid()) { + loginMethods += LOGIN_METHOD_LIBRUS_SYNERGIA + app.cookieJar.set("synergia.librus.pl", "DZIENNIKSID", synergiaSessionId) + } + if (isMessagesLoginValid()) { + loginMethods += LOGIN_METHOD_LIBRUS_MESSAGES + app.cookieJar.set("wiadomosci.librus.pl", "DZIENNIKSID", messagesSessionId) + } + } + + override fun generateUserCode() = "$schoolName:$apiLogin" + + fun getColor(id: Int?): Int { + return when (id) { + 1 -> 0xFFF0E68C + 2 -> 0xFF87CEFA + 3 -> 0xFFB0C4DE + 4 -> 0xFFF0F8FF + 5 -> 0xFFF0FFFF + 6 -> 0xFFF5F5DC + 7 -> 0xFFFFEBCD + 8 -> 0xFFFFF8DC + 9 -> 0xFFA9A9A9 + 10 -> 0xFFBDB76B + 11 -> 0xFF8FBC8F + 12 -> 0xFFDCDCDC + 13 -> 0xFFDAA520 + 14 -> 0xFFE6E6FA + 15 -> 0xFFFFA07A + 16 -> 0xFF32CD32 + 17 -> 0xFF66CDAA + 18 -> 0xFF66CDAA + 19 -> 0xFFC0C0C0 + 20 -> 0xFFD2B48C + 21 -> 0xFF3333FF + 22 -> 0xFF7B68EE + 23 -> 0xFFBA55D3 + 24 -> 0xFFFFB6C1 + 25 -> 0xFFFF1493 + 26 -> 0xFFDC143C + 27 -> 0xFFFF0000 + 28 -> 0xFFFF8C00 + 29 -> 0xFFFFD700 + 30 -> 0xFFADFF2F + 31 -> 0xFF7CFC00 + else -> 0xff2196f3 + }.toInt() + } + + /* _____ _ _ + | __ \ | | | | + | |__) |__ _ __| |_ __ _| | + | ___/ _ \| '__| __/ _` | | + | | | (_) | | | || (_| | | + |_| \___/|_| \__\__,_|*/ + private var mPortalEmail: String? = null + var portalEmail: String? + get() { mPortalEmail = mPortalEmail ?: loginStore.getLoginData("email", null); return mPortalEmail } + set(value) { loginStore.putLoginData("email", value); mPortalEmail = value } + private var mPortalPassword: String? = null + var portalPassword: String? + get() { mPortalPassword = mPortalPassword ?: loginStore.getLoginData("password", null); return mPortalPassword } + set(value) { loginStore.putLoginData("password", value); mPortalPassword = value } + + private var mPortalAccessToken: String? = null + var portalAccessToken: String? + get() { mPortalAccessToken = mPortalAccessToken ?: loginStore.getLoginData("accessToken", null); return mPortalAccessToken } + set(value) { loginStore.putLoginData("accessToken", value); mPortalAccessToken = value } + private var mPortalRefreshToken: String? = null + var portalRefreshToken: String? + get() { mPortalRefreshToken = mPortalRefreshToken ?: loginStore.getLoginData("refreshToken", null); return mPortalRefreshToken } + set(value) { loginStore.putLoginData("refreshToken", value); mPortalRefreshToken = value } + private var mPortalTokenExpiryTime: Long? = null + var portalTokenExpiryTime: Long + get() { mPortalTokenExpiryTime = mPortalTokenExpiryTime ?: loginStore.getLoginData("tokenExpiryTime", 0L); return mPortalTokenExpiryTime ?: 0L } + set(value) { loginStore.putLoginData("tokenExpiryTime", value); mPortalTokenExpiryTime = value } + + /* _____ _____ + /\ | __ \_ _| + / \ | |__) || | + / /\ \ | ___/ | | + / ____ \| | _| |_ + /_/ \_\_| |____*/ + /** + * A Synergia login, like 1234567u. + * Used: for login (API Login Method) in Synergia mode. + * Used: for login (Synergia Login Method) in Synergia mode. + * And also in various places in [pl.szczodrzynski.edziennik.api.v2.models.Feature]s + */ + private var mApiLogin: String? = null + var apiLogin: String? + get() { mApiLogin = mApiLogin ?: profile?.getStudentData("accountLogin", null); return mApiLogin } + set(value) { profile?.putStudentData("accountLogin", value); mApiLogin = value } + /** + * A Synergia password. + * Used: for login (API Login Method) in Synergia mode. + * Used: for login (Synergia Login Method) in Synergia mode. + */ + private var mApiPassword: String? = null + var apiPassword: String? + get() { mApiPassword = mApiPassword ?: profile?.getStudentData("accountPassword", null); return mApiPassword } + set(value) { profile?.putStudentData("accountPassword", value); mApiPassword = value } + + /** + * A JST login Code. + * Used only during first login in JST mode. + */ + private var mApiCode: String? = null + var apiCode: String? + get() { mApiCode = mApiCode ?: loginStore.getLoginData("accountCode", null); return mApiCode } + set(value) { profile?.putStudentData("accountCode", value); mApiCode = value } + /** + * A JST login PIN. + * Used only during first login in JST mode. + */ + private var mApiPin: String? = null + var apiPin: String? + get() { mApiPin = mApiPin ?: loginStore.getLoginData("accountPin", null); return mApiPin } + set(value) { profile?.putStudentData("accountPin", value); mApiPin = value } + + /** + * A Synergia API access token. + * Used in all Api Endpoints. + * Created in Login Method Api. + * Applicable for all login modes. + */ + private var mApiAccessToken: String? = null + var apiAccessToken: String? + get() { mApiAccessToken = mApiAccessToken ?: profile?.getStudentData("accountToken", null); return mApiAccessToken } + set(value) { mApiAccessToken = value; profile?.putStudentData("accountToken", value) ?: return; } + /** + * A Synergia API refresh token. + * Used when refreshing the [apiAccessToken] in JST, Synergia modes. + */ + private var mApiRefreshToken: String? = null + var apiRefreshToken: String? + get() { mApiRefreshToken = mApiRefreshToken ?: profile?.getStudentData("accountRefreshToken", null); return mApiRefreshToken } + set(value) { mApiRefreshToken = value; profile?.putStudentData("accountRefreshToken", value) ?: return; } + /** + * The expiry time for [apiAccessToken], as a UNIX timestamp. + * Used when refreshing the [apiAccessToken] in JST, Synergia modes. + * Used when refreshing the [apiAccessToken] in Portal mode ([pl.szczodrzynski.edziennik.api.v2.librus.login.SynergiaTokenExtractor]) + */ + private var mApiTokenExpiryTime: Long? = null + var apiTokenExpiryTime: Long + get() { mApiTokenExpiryTime = mApiTokenExpiryTime ?: profile?.getStudentData("accountTokenTime", 0L); return mApiTokenExpiryTime ?: 0L } + set(value) { mApiTokenExpiryTime = value; profile?.putStudentData("accountTokenTime", value) ?: return; } + + /** + * A push device ID, generated by Librus when registering + * a FCM token. I don't really know if this has any use, + * but it may be worthy to save that ID. + */ + private var mPushDeviceId: Int? = null + var pushDeviceId: Int + get() { mPushDeviceId = mPushDeviceId ?: profile?.getStudentData("pushDeviceId", 0); return mPushDeviceId ?: 0 } + set(value) { mPushDeviceId = value; profile?.putStudentData("pushDeviceId", value) ?: return; } + + /* _____ _ + / ____| (_) + | (___ _ _ _ __ ___ _ __ __ _ _ __ _ + \___ \| | | | '_ \ / _ \ '__/ _` | |/ _` | + ____) | |_| | | | | __/ | | (_| | | (_| | + |_____/ \__, |_| |_|\___|_| \__, |_|\__,_| + __/ | __/ | + |___/ |__*/ + /** + * A Synergia web Session ID (DZIENNIKSID). + * Used in endpoints with Synergia login method. + */ + private var mSynergiaSessionId: String? = null + var synergiaSessionId: String? + get() { mSynergiaSessionId = mSynergiaSessionId ?: profile?.getStudentData("accountSID", null); return mSynergiaSessionId } + set(value) { profile?.putStudentData("accountSID", value) ?: return; mSynergiaSessionId = value } + /** + * The expiry time for [synergiaSessionId], as a UNIX timestamp. + * Used in endpoints with Synergia login method. + * TODO verify how long is the session ID valid. + */ + private var mSynergiaSessionIdExpiryTime: Long? = null + var synergiaSessionIdExpiryTime: Long + get() { mSynergiaSessionIdExpiryTime = mSynergiaSessionIdExpiryTime ?: profile?.getStudentData("accountSIDTime", 0L); return mSynergiaSessionIdExpiryTime ?: 0L } + set(value) { profile?.putStudentData("accountSIDTime", value) ?: return; mSynergiaSessionIdExpiryTime = value } + + + /** + * A Messages web Session ID (DZIENNIKSID). + * Used in endpoints with Messages login method. + */ + private var mMessagesSessionId: String? = null + var messagesSessionId: String? + get() { mMessagesSessionId = mMessagesSessionId ?: profile?.getStudentData("messagesSID", null); return mMessagesSessionId } + set(value) { profile?.putStudentData("messagesSID", value) ?: return; mMessagesSessionId = value } + /** + * The expiry time for [messagesSessionId], as a UNIX timestamp. + * Used in endpoints with Messages login method. + * TODO verify how long is the session ID valid. + */ + private var mMessagesSessionIdExpiryTime: Long? = null + var messagesSessionIdExpiryTime: Long + get() { mMessagesSessionIdExpiryTime = mMessagesSessionIdExpiryTime ?: profile?.getStudentData("messagesSIDTime", 0L); return mMessagesSessionIdExpiryTime ?: 0L } + set(value) { profile?.putStudentData("messagesSIDTime", value) ?: return; mMessagesSessionIdExpiryTime = value } + + /* ____ _ _ + / __ \| | | | + | | | | |_| |__ ___ _ __ + | | | | __| '_ \ / _ \ '__| + | |__| | |_| | | | __/ | + \____/ \__|_| |_|\___|*/ + var isPremium + get() = profile?.getStudentData("isPremium", false) ?: false + set(value) { profile?.putStudentData("isPremium", value) } + + private var mSchoolName: String? = null + var schoolName: String? + get() { mSchoolName = mSchoolName ?: profile?.getStudentData("schoolName", null); return mSchoolName } + set(value) { profile?.putStudentData("schoolName", value) ?: return; mSchoolName = value } + + private var mUnitId: Long? = null + var unitId: Long + get() { mUnitId = mUnitId ?: profile?.getStudentData("unitId", 0L); return mUnitId ?: 0L } + set(value) { profile?.putStudentData("unitId", value) ?: return; mUnitId = value } + + private var mStartPointsSemester1: Int? = null + var startPointsSemester1: Int + get() { mStartPointsSemester1 = mStartPointsSemester1 ?: profile?.getStudentData("startPointsSemester1", 0); return mStartPointsSemester1 ?: 0 } + set(value) { profile?.putStudentData("startPointsSemester1", value) ?: return; mStartPointsSemester1 = value } + + private var mStartPointsSemester2: Int? = null + var startPointsSemester2: Int + get() { mStartPointsSemester2 = mStartPointsSemester2 ?: profile?.getStudentData("startPointsSemester2", 0); return mStartPointsSemester2 ?: 0 } + set(value) { profile?.putStudentData("startPointsSemester2", value) ?: return; mStartPointsSemester2 = value } + + private var mEnablePointGrades: Boolean? = null + var enablePointGrades: Boolean + get() { mEnablePointGrades = mEnablePointGrades ?: profile?.getStudentData("enablePointGrades", true); return mEnablePointGrades ?: true } + set(value) { profile?.putStudentData("enablePointGrades", value) ?: return; mEnablePointGrades = value } + + private var mEnableDescriptiveGrades: Boolean? = null + var enableDescriptiveGrades: Boolean + get() { mEnableDescriptiveGrades = mEnableDescriptiveGrades ?: profile?.getStudentData("enableDescriptiveGrades", true); return mEnableDescriptiveGrades ?: true } + set(value) { profile?.putStudentData("enableDescriptiveGrades", value) ?: return; mEnableDescriptiveGrades = value } + + private var mTimetableNotPublic: Boolean? = null + var timetableNotPublic: Boolean + get() { mTimetableNotPublic = mTimetableNotPublic ?: profile?.getStudentData("timetableNotPublic", false); return mTimetableNotPublic ?: false } + set(value) { profile?.putStudentData("timetableNotPublic", value) ?: return; mTimetableNotPublic = value } + + /** + * Set to false when Recaptcha helper doesn't provide a working token. + * When it's set to false uses Synergia for messages. + */ + var messagesLoginSuccessful: Boolean = true +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/Librus.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/Librus.kt new file mode 100644 index 00000000..abf3ac5f --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/Librus.kt @@ -0,0 +1,239 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-21. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusData +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api.LibrusApiAnnouncementMarkAsRead +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages.LibrusMessagesGetAttachment +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages.LibrusMessagesGetMessage +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages.LibrusMessagesGetRecipientList +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages.LibrusMessagesSendMessage +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.synergia.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.firstlogin.LibrusFirstLogin +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.login.LibrusLogin +import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikCallback +import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore +import pl.szczodrzynski.edziennik.data.db.entity.Message +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.data.db.full.AnnouncementFull +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.data.db.full.MessageFull +import pl.szczodrzynski.edziennik.utils.Utils.d + +class Librus(val app: App, val profile: Profile?, val loginStore: LoginStore, val callback: EdziennikCallback) : EdziennikInterface { + companion object { + private const val TAG = "Librus" + } + + val internalErrorList = mutableListOf() + val data: DataLibrus + private var afterLogin: (() -> Unit)? = null + + init { + data = DataLibrus(app, profile, loginStore).apply { + callback = wrapCallback(this@Librus.callback) + satisfyLoginMethods() + } + } + + private fun completed() { + data.saveData() + callback.onCompleted() + } + + /* _______ _ _ _ _ _ + |__ __| | /\ | | (_) | | | + | | | |__ ___ / \ | | __ _ ___ _ __ _| |_| |__ _ __ ___ + | | | '_ \ / _ \ / /\ \ | |/ _` |/ _ \| '__| | __| '_ \| '_ ` _ \ + | | | | | | __/ / ____ \| | (_| | (_) | | | | |_| | | | | | | | | + |_| |_| |_|\___| /_/ \_\_|\__, |\___/|_| |_|\__|_| |_|_| |_| |_| + __/ | + |__*/ + override fun sync(featureIds: List, viewId: Int?, onlyEndpoints: List?, arguments: JsonObject?) { + data.arguments = arguments + data.prepare(librusLoginMethods, LibrusFeatures, featureIds, viewId, onlyEndpoints) + login() + } + + private fun login(loginMethodId: Int? = null, afterLogin: (() -> Unit)? = null) { + d(TAG, "Trying to login with ${data.targetLoginMethodIds}") + if (internalErrorList.isNotEmpty()) { + d(TAG, " - Internal errors:") + internalErrorList.forEach { d(TAG, " - code $it") } + } + loginMethodId?.let { data.prepareFor(librusLoginMethods, it) } + afterLogin?.let { this.afterLogin = it } + LibrusLogin(data) { + data() + } + } + + private fun data() { + d(TAG, "Endpoint IDs: ${data.targetEndpointIds}") + if (internalErrorList.isNotEmpty()) { + d(TAG, " - Internal errors:") + internalErrorList.forEach { d(TAG, " - code $it") } + } + afterLogin?.invoke() ?: LibrusData(data) { + completed() + } + } + + override fun getMessage(message: MessageFull) { + login(LOGIN_METHOD_LIBRUS_MESSAGES) { + if (data.messagesLoginSuccessful) LibrusMessagesGetMessage(data, message) { completed() } + else LibrusSynergiaGetMessage(data, message) { completed() } + } + } + + override fun sendMessage(recipients: List, subject: String, text: String) { + login(LOGIN_METHOD_LIBRUS_MESSAGES) { + LibrusMessagesSendMessage(data, recipients, subject, text) { + completed() + } + } + } + + override fun markAllAnnouncementsAsRead() { + login(LOGIN_METHOD_LIBRUS_SYNERGIA) { + LibrusSynergiaMarkAllAnnouncementsAsRead(data) { + completed() + } + } + } + + override fun getAnnouncement(announcement: AnnouncementFull) { + login(LOGIN_METHOD_LIBRUS_API) { + LibrusApiAnnouncementMarkAsRead(data, announcement) { + completed() + } + } + } + + override fun getAttachment(owner: Any, attachmentId: Long, attachmentName: String) { + when (owner) { + is Message -> { + login(LOGIN_METHOD_LIBRUS_SYNERGIA) { + if (data.messagesLoginSuccessful) LibrusMessagesGetAttachment(data, owner, attachmentId, attachmentName) { completed() } + LibrusSynergiaGetAttachment(data, owner, attachmentId, attachmentName) { completed() } + } + } + is EventFull -> { + login(LOGIN_METHOD_LIBRUS_SYNERGIA) { + LibrusSynergiaHomeworkGetAttachment(data, owner, attachmentId, attachmentName) { + completed() + } + } + } + else -> completed() + } + } + + override fun getRecipientList() { + login(LOGIN_METHOD_LIBRUS_MESSAGES) { + LibrusMessagesGetRecipientList(data) { + completed() + } + } + } + + override fun getEvent(eventFull: EventFull) { + login(LOGIN_METHOD_LIBRUS_SYNERGIA) { + LibrusSynergiaGetHomework(data, eventFull) { + completed() + } + } + } + + override fun firstLogin() { LibrusFirstLogin(data) { completed() } } + override fun cancel() { + d(TAG, "Cancelled") + data.cancel() + } + + private fun wrapCallback(callback: EdziennikCallback): EdziennikCallback { + return object : EdziennikCallback { + override fun onCompleted() { callback.onCompleted() } + override fun onProgress(step: Float) { callback.onProgress(step) } + override fun onStartProgress(stringRes: Int) { callback.onStartProgress(stringRes) } + override fun onError(apiError: ApiError) { + if (apiError.errorCode in internalErrorList) { + // finish immediately if the same error occurs twice during the same sync + callback.onError(apiError) + return + } + internalErrorList.add(apiError.errorCode) + when (apiError.errorCode) { + ERROR_LIBRUS_PORTAL_ACCESS_DENIED -> { + data.loginMethods.remove(LOGIN_METHOD_LIBRUS_PORTAL) + data.prepareFor(librusLoginMethods, LOGIN_METHOD_LIBRUS_PORTAL) + data.portalTokenExpiryTime = 0 + login() + } + ERROR_LIBRUS_API_ACCESS_DENIED, + ERROR_LIBRUS_API_TOKEN_EXPIRED -> { + data.loginMethods.remove(LOGIN_METHOD_LIBRUS_API) + data.prepareFor(librusLoginMethods, LOGIN_METHOD_LIBRUS_API) + data.apiTokenExpiryTime = 0 + login() + } + ERROR_LIBRUS_SYNERGIA_ACCESS_DENIED -> { + data.loginMethods.remove(LOGIN_METHOD_LIBRUS_SYNERGIA) + data.prepareFor(librusLoginMethods, LOGIN_METHOD_LIBRUS_SYNERGIA) + data.synergiaSessionIdExpiryTime = 0 + login() + } + ERROR_LIBRUS_MESSAGES_ACCESS_DENIED -> { + data.loginMethods.remove(LOGIN_METHOD_LIBRUS_MESSAGES) + data.prepareFor(librusLoginMethods, LOGIN_METHOD_LIBRUS_MESSAGES) + data.messagesSessionIdExpiryTime = 0 + login() + } + ERROR_LOGIN_LIBRUS_PORTAL_NO_CODE, + ERROR_LOGIN_LIBRUS_PORTAL_CSRF_MISSING, + ERROR_LOGIN_LIBRUS_PORTAL_CSRF_EXPIRED, + ERROR_LOGIN_LIBRUS_PORTAL_CODE_REVOKED, + ERROR_LOGIN_LIBRUS_PORTAL_CODE_EXPIRED -> { + login() + } + ERROR_LOGIN_LIBRUS_PORTAL_NO_REFRESH, + ERROR_LOGIN_LIBRUS_PORTAL_REFRESH_REVOKED, + ERROR_LOGIN_LIBRUS_PORTAL_REFRESH_INVALID -> { + data.portalRefreshToken = null + login() + } + ERROR_LOGIN_LIBRUS_SYNERGIA_TOKEN_INVALID, + ERROR_LOGIN_LIBRUS_SYNERGIA_NO_TOKEN, + ERROR_LOGIN_LIBRUS_SYNERGIA_NO_SESSION_ID -> { + login() + } + ERROR_LOGIN_LIBRUS_MESSAGES_NO_SESSION_ID -> { + login() + } + ERROR_LIBRUS_API_TIMETABLE_NOT_PUBLIC -> { + data.timetableNotPublic = true + data() + } + ERROR_LIBRUS_API_LUCKY_NUMBER_NOT_ACTIVE, + ERROR_LIBRUS_API_NOTES_NOT_ACTIVE -> { + data() + } + ERROR_LIBRUS_API_DEVICE_REGISTERED -> { + data.app.config.sync.tokenLibrusList = + data.app.config.sync.tokenLibrusList + data.profileId + data() + } + else -> callback.onError(apiError) + } + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/LibrusFeatures.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/LibrusFeatures.kt new file mode 100644 index 00000000..c14a00df --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/LibrusFeatures.kt @@ -0,0 +1,248 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-11. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus + +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.models.Feature + +const val ENDPOINT_LIBRUS_API_ME = 1001 +const val ENDPOINT_LIBRUS_API_SCHOOLS = 1002 +const val ENDPOINT_LIBRUS_API_CLASSES = 1003 +const val ENDPOINT_LIBRUS_API_VIRTUAL_CLASSES = 1004 +const val ENDPOINT_LIBRUS_API_UNITS = 1005 +const val ENDPOINT_LIBRUS_API_USERS = 1006 +const val ENDPOINT_LIBRUS_API_SUBJECTS = 1007 +const val ENDPOINT_LIBRUS_API_CLASSROOMS = 1008 +const val ENDPOINT_LIBRUS_API_LESSONS = 1009 +const val ENDPOINT_LIBRUS_API_PUSH_CONFIG = 1010 +const val ENDPOINT_LIBRUS_API_TIMETABLES = 1015 +const val ENDPOINT_LIBRUS_API_SUBSTITUTIONS = 1016 +const val ENDPOINT_LIBRUS_API_NORMAL_GRADE_CATEGORIES = 1021 +const val ENDPOINT_LIBRUS_API_POINT_GRADE_CATEGORIES = 1022 +const val ENDPOINT_LIBRUS_API_DESCRIPTIVE_GRADE_CATEGORIES = 1023 +const val ENDPOINT_LIBRUS_API_TEXT_GRADE_CATEGORIES = 1024 +const val ENDPOINT_LIBRUS_API_DESCRIPTIVE_TEXT_GRADE_CATEGORIES = 1025 +const val ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADE_CATEGORIES = 1026 +const val ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADE_COMMENTS = 1027 +const val ENDPOINT_LIBRUS_API_NORMAL_GRADE_COMMENTS = 1030 +const val ENDPOINT_LIBRUS_API_NORMAL_GRADES = 1031 +const val ENDPOINT_LIBRUS_API_POINT_GRADES = 1032 +const val ENDPOINT_LIBRUS_API_DESCRIPTIVE_GRADES = 1033 +const val ENDPOINT_LIBRUS_API_TEXT_GRADES = 1034 +const val ENDPOINT_LIBRUS_API_DESCRIPTIVE_TEXT_GRADES = 1035 +const val ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADES = 1036 +const val ENDPOINT_LIBRUS_API_EVENT_TYPES = 1040 +const val ENDPOINT_LIBRUS_API_EVENTS = 1041 +const val ENDPOINT_LIBRUS_API_HOMEWORK = 1050 +const val ENDPOINT_LIBRUS_API_LUCKY_NUMBER = 1060 +const val ENDPOINT_LIBRUS_API_NOTICE_TYPES = 1070 +const val ENDPOINT_LIBRUS_API_NOTICES = 1071 +const val ENDPOINT_LIBRUS_API_ATTENDANCE_TYPES = 1080 +const val ENDPOINT_LIBRUS_API_ATTENDANCES = 1081 +const val ENDPOINT_LIBRUS_API_ANNOUNCEMENTS = 1090 +const val ENDPOINT_LIBRUS_API_PT_MEETINGS = 1100 +const val ENDPOINT_LIBRUS_API_TEACHER_FREE_DAY_TYPES = 1109 +const val ENDPOINT_LIBRUS_API_TEACHER_FREE_DAYS = 1110 +const val ENDPOINT_LIBRUS_API_SCHOOL_FREE_DAYS = 1120 +const val ENDPOINT_LIBRUS_API_CLASS_FREE_DAYS = 1130 +const val ENDPOINT_LIBRUS_SYNERGIA_INFO = 2010 +const val ENDPOINT_LIBRUS_SYNERGIA_GRADES = 2020 +const val ENDPOINT_LIBRUS_SYNERGIA_HOMEWORK = 2030 +const val ENDPOINT_LIBRUS_SYNERGIA_MESSAGES_RECEIVED = 2040 +const val ENDPOINT_LIBRUS_SYNERGIA_MESSAGES_SENT = 2050 +const val ENDPOINT_LIBRUS_MESSAGES_RECEIVED = 3010 +const val ENDPOINT_LIBRUS_MESSAGES_SENT = 3020 +const val ENDPOINT_LIBRUS_MESSAGES_TRASH = 3030 + +val LibrusFeatures = listOf( + + Feature(LOGIN_TYPE_LIBRUS, FEATURE_ALWAYS_NEEDED, listOf( + ENDPOINT_LIBRUS_API_LESSONS to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)), + + // push config + Feature(LOGIN_TYPE_LIBRUS, FEATURE_PUSH_CONFIG, listOf( + ENDPOINT_LIBRUS_API_PUSH_CONFIG to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)).withShouldSync { data -> + (data as DataLibrus).isPremium && !data.app.config.sync.tokenLibrusList.contains(data.profileId) + }, + + + + + + /** + * Timetable - using API. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_TIMETABLE, listOf( + ENDPOINT_LIBRUS_API_TIMETABLES to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_SUBSTITUTIONS to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)), + /** + * Agenda - using API. + * Events, Parent-teacher meetings, free days (teacher/school/class). + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_AGENDA, listOf( + ENDPOINT_LIBRUS_API_EVENTS to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_EVENT_TYPES to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_PT_MEETINGS to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_TEACHER_FREE_DAY_TYPES to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_TEACHER_FREE_DAYS to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_SCHOOL_FREE_DAYS to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_CLASS_FREE_DAYS to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)), + /** + * Grades - using API. + * All grades + categories. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_GRADES, listOf( + ENDPOINT_LIBRUS_API_NORMAL_GRADE_CATEGORIES to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_POINT_GRADE_CATEGORIES to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_DESCRIPTIVE_GRADE_CATEGORIES to LOGIN_METHOD_LIBRUS_API, + // Commented out, because TextGrades/Categories is the same as Grades/Categories + /* ENDPOINT_LIBRUS_API_TEXT_GRADE_CATEGORIES to LOGIN_METHOD_LIBRUS_API, */ + ENDPOINT_LIBRUS_API_DESCRIPTIVE_TEXT_GRADE_CATEGORIES to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADE_CATEGORIES to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_NORMAL_GRADE_COMMENTS to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADE_COMMENTS to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_NORMAL_GRADES to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_POINT_GRADES to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_DESCRIPTIVE_GRADES to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_TEXT_GRADES to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_DESCRIPTIVE_TEXT_GRADES to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADES to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)), + /** + * Homework - using API. + * Sync only if account has premium access. + */ + /*Feature(LOGIN_TYPE_LIBRUS, FEATURE_HOMEWORK, listOf( + ENDPOINT_LIBRUS_API_HOMEWORK to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)).withShouldSync { data -> + (data as DataLibrus).isPremium + },*/ + /** + * Behaviour - using API. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_BEHAVIOUR, listOf( + ENDPOINT_LIBRUS_API_NOTICES to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)), + /** + * Attendance - using API. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_ATTENDANCE, listOf( + ENDPOINT_LIBRUS_API_ATTENDANCE_TYPES to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_ATTENDANCES to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)), + /** + * Announcements - using API. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_ANNOUNCEMENTS, listOf( + ENDPOINT_LIBRUS_API_ANNOUNCEMENTS to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)), + + + + + + /** + * Student info - using API. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_STUDENT_INFO, listOf( + ENDPOINT_LIBRUS_API_ME to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)), + /** + * School info - using API. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_SCHOOL_INFO, listOf( + ENDPOINT_LIBRUS_API_SCHOOLS to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_UNITS to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)), + /** + * Class info - using API. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_CLASS_INFO, listOf( + ENDPOINT_LIBRUS_API_CLASSES to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)), + /** + * Team info - using API. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_TEAM_INFO, listOf( + ENDPOINT_LIBRUS_API_VIRTUAL_CLASSES to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)), + /** + * Lucky number - using API. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_LUCKY_NUMBER, listOf( + ENDPOINT_LIBRUS_API_LUCKY_NUMBER to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)).withShouldSync { data -> data.shouldSyncLuckyNumber() }, + /** + * Teacher list - using API. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_TEACHERS, listOf( + ENDPOINT_LIBRUS_API_USERS to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)), + /** + * Subject list - using API. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_SUBJECTS, listOf( + ENDPOINT_LIBRUS_API_SUBJECTS to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)), + /** + * Classroom list - using API. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_CLASSROOMS, listOf( + ENDPOINT_LIBRUS_API_CLASSROOMS to LOGIN_METHOD_LIBRUS_API + ), listOf(LOGIN_METHOD_LIBRUS_API)), + + /** + * Student info - using synergia scrapper. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_STUDENT_INFO, listOf( + ENDPOINT_LIBRUS_SYNERGIA_INFO to LOGIN_METHOD_LIBRUS_SYNERGIA + ), listOf(LOGIN_METHOD_LIBRUS_SYNERGIA)), + /** + * Student number - using synergia scrapper. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_STUDENT_NUMBER, listOf( + ENDPOINT_LIBRUS_SYNERGIA_INFO to LOGIN_METHOD_LIBRUS_SYNERGIA + ), listOf(LOGIN_METHOD_LIBRUS_SYNERGIA)), + + + /** + * Grades - using API + synergia scrapper. + */ + /*Feature(LOGIN_TYPE_LIBRUS, FEATURE_GRADES, listOf( + ENDPOINT_LIBRUS_API_NORMAL_GC to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_API_NORMAL_GRADES to LOGIN_METHOD_LIBRUS_API, + ENDPOINT_LIBRUS_SYNERGIA_GRADES to LOGIN_METHOD_LIBRUS_SYNERGIA + ), listOf(LOGIN_METHOD_LIBRUS_API, LOGIN_METHOD_LIBRUS_SYNERGIA)),*/ + /*Endpoint(LOGIN_TYPE_LIBRUS, FEATURE_GRADES, listOf( + ENDPOINT_LIBRUS_SYNERGIA_GRADES to LOGIN_METHOD_LIBRUS_SYNERGIA + ), listOf(LOGIN_METHOD_LIBRUS_SYNERGIA)),*/ + + /** + * Homework - using scrapper. + * Sync only if account has not premium access. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_HOMEWORK, listOf( + ENDPOINT_LIBRUS_SYNERGIA_HOMEWORK to LOGIN_METHOD_LIBRUS_SYNERGIA + ), listOf(LOGIN_METHOD_LIBRUS_SYNERGIA))/*.withShouldSync { data -> + !(data as DataLibrus).isPremium + }*/, + + /** + * Messages inbox - using messages website. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_MESSAGES_INBOX, listOf( + ENDPOINT_LIBRUS_MESSAGES_RECEIVED to LOGIN_METHOD_LIBRUS_MESSAGES + ), listOf(LOGIN_METHOD_LIBRUS_MESSAGES)), + /** + * Messages sent - using messages website. + */ + Feature(LOGIN_TYPE_LIBRUS, FEATURE_MESSAGES_SENT, listOf( + ENDPOINT_LIBRUS_MESSAGES_SENT to LOGIN_METHOD_LIBRUS_MESSAGES + ), listOf(LOGIN_METHOD_LIBRUS_MESSAGES)) +) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/LibrusRecaptchaHelper.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/LibrusRecaptchaHelper.kt new file mode 100644 index 00000000..a44076b4 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/LibrusRecaptchaHelper.kt @@ -0,0 +1,60 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-5-8. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus + +import android.content.Context +import android.webkit.WebView +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import pl.szczodrzynski.edziennik.ext.startCoroutineTimer +import kotlin.coroutines.CoroutineContext + +class LibrusRecaptchaHelper( + val context: Context, + url: String, + html: String, + val onSuccess: (url: String) -> Unit, + val onTimeout: () -> Unit +) : CoroutineScope { + companion object { + private const val TAG = "LibrusRecaptchaHelper" + } + + private val job: Job = Job() + override val coroutineContext: CoroutineContext + get() = job + Dispatchers.Default + + private val webView by lazy { + WebView(context).also { + it.settings.javaScriptEnabled = true + it.webViewClient = WebViewClient() + } + } + + private var timeout: Job? = null + private var timedOut = false + + inner class WebViewClient : android.webkit.WebViewClient() { + override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { + timeout?.cancel() + if (!timedOut) { + onSuccess(url) + } + return true + } + } + + init { + launch(Dispatchers.Main) { + webView.loadDataWithBaseURL(url, html, "text/html", "UTF-8", null) + } + timeout = startCoroutineTimer(delayMillis = 10000L) { + timedOut = true + onTimeout() + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/LibrusApi.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/LibrusApi.kt new file mode 100644 index 00000000..2b736a0f --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/LibrusApi.kt @@ -0,0 +1,129 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-21. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data + +import com.google.gson.JsonObject +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.callback.JsonCallbackHandler +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.utils.Utils.d +import java.net.HttpURLConnection.* + +open class LibrusApi(open val data: DataLibrus, open val lastSync: Long?) { + companion object { + private const val TAG = "LibrusApi" + } + + val profileId + get() = data.profile?.id ?: -1 + + val profile + get() = data.profile + + fun apiGet(tag: String, endpoint: String, method: Int = GET, payload: JsonObject? = null, ignoreErrors: List = emptyList(), onSuccess: (json: JsonObject) -> Unit) { + + d(tag, "Request: Librus/Api - ${if (data.fakeLogin) FAKE_LIBRUS_API else LIBRUS_API_URL}/$endpoint") + + val callback = object : JsonCallbackHandler() { + override fun onSuccess(json: JsonObject?, response: Response?) { + if (response?.code() == HTTP_UNAVAILABLE) { + data.error(ApiError(tag, ERROR_LIBRUS_API_MAINTENANCE) + .withApiResponse(json) + .withResponse(response)) + return + } + + if (json == null && response?.parserErrorBody == null) { + data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) + .withResponse(response)) + return + } + /* +{"Status":"Error","Code":"DeviceRegistered","Message":"This device is alerdy registered.","Resources":{"..":{"Url":"https:\/\/api.librus.pl\/2.0\/Root"}},"Url":"https:\/\/api.librus.pl\/2.0\/ChangeRegister"}*/ + val error = if (response?.code() == 200) null else + json.getString("Code") ?: + json.getString("Message") ?: + json.getString("Status") ?: + response?.parserErrorBody + error?.let { code -> + when (code) { + "TokenIsExpired" -> ERROR_LIBRUS_API_TOKEN_EXPIRED + "Insufficient scopes" -> ERROR_LIBRUS_API_INSUFFICIENT_SCOPES + "Request is denied" -> ERROR_LIBRUS_API_ACCESS_DENIED + "Resource not found" -> ERROR_LIBRUS_API_RESOURCE_NOT_FOUND + "NotFound" -> ERROR_LIBRUS_API_DATA_NOT_FOUND + "AccessDeny" -> when (json.getString("Message")) { + "Student timetable is not public" -> ERROR_LIBRUS_API_TIMETABLE_NOT_PUBLIC + else -> ERROR_LIBRUS_API_RESOURCE_ACCESS_DENIED + } + "LuckyNumberIsNotActive" -> ERROR_LIBRUS_API_LUCKY_NUMBER_NOT_ACTIVE + "NotesIsNotActive" -> ERROR_LIBRUS_API_NOTES_NOT_ACTIVE + "InvalidRequest" -> ERROR_LIBRUS_API_INVALID_REQUEST_PARAMS + "Nieprawidłowy węzeł." -> ERROR_LIBRUS_API_INCORRECT_ENDPOINT + "NoticeboardProblem" -> ERROR_LIBRUS_API_NOTICEBOARD_PROBLEM + "DeviceRegistered" -> ERROR_LIBRUS_API_DEVICE_REGISTERED + "Maintenance" -> ERROR_LIBRUS_API_MAINTENANCE + else -> ERROR_LIBRUS_API_OTHER + }.let { errorCode -> + if (errorCode !in ignoreErrors) { + data.error(ApiError(tag, errorCode) + .withApiResponse(json) + .withResponse(response)) + return + } + } + } + + if (json == null) { + data.error(ApiError(tag, ERROR_RESPONSE_EMPTY) + .withResponse(response)) + return + } + + try { + onSuccess(json) + } catch (e: Exception) { + data.error(ApiError(tag, EXCEPTION_LIBRUS_API_REQUEST) + .withResponse(response) + .withThrowable(e) + .withApiResponse(json)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + // TODO add hotfix for Classrooms 500 + data.error(ApiError(tag, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + Request.builder() + .url("${if (data.fakeLogin) FAKE_LIBRUS_API else LIBRUS_API_URL}/$endpoint") + .userAgent(LIBRUS_USER_AGENT) + .addHeader("Authorization", "Bearer ${data.apiAccessToken}") + .apply { + when (method) { + GET -> get() + POST -> post() + } + if (payload != null) + setJsonBody(payload) + } + .allowErrorCode(HTTP_BAD_REQUEST) + .allowErrorCode(HTTP_FORBIDDEN) + .allowErrorCode(HTTP_UNAUTHORIZED) + .allowErrorCode(HTTP_UNAVAILABLE) + .allowErrorCode(HTTP_NOT_FOUND) + .allowErrorCode(503) + .callback(callback) + .build() + .enqueue() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/LibrusData.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/LibrusData.kt new file mode 100644 index 00000000..db72ddcc --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/LibrusData.kt @@ -0,0 +1,227 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data + +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages.LibrusMessagesGetList +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.synergia.LibrusSynergiaGetMessages +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.synergia.LibrusSynergiaHomework +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.synergia.LibrusSynergiaInfo +import pl.szczodrzynski.edziennik.data.db.entity.Message +import pl.szczodrzynski.edziennik.utils.Utils + +class LibrusData(val data: DataLibrus, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "LibrusEndpoints" + } + + init { + nextEndpoint(onSuccess) + } + + private fun nextEndpoint(onSuccess: () -> Unit) { + if (data.targetEndpointIds.isEmpty()) { + onSuccess() + return + } + if (data.cancelled) { + onSuccess() + return + } + val id = data.targetEndpointIds.firstKey() + val lastSync = data.targetEndpointIds.remove(id) + useEndpoint(id, lastSync) { endpointId -> + data.progress(data.progressStep) + nextEndpoint(onSuccess) + } + } + + private fun useEndpoint(endpointId: Int, lastSync: Long?, onSuccess: (endpointId: Int) -> Unit) { + Utils.d(TAG, "Using endpoint $endpointId. Last sync time = $lastSync") + when (endpointId) { + /** + * API + */ + ENDPOINT_LIBRUS_API_ME -> { + data.startProgress(R.string.edziennik_progress_endpoint_student_info) + LibrusApiMe(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_SCHOOLS -> { + data.startProgress(R.string.edziennik_progress_endpoint_school_info) + LibrusApiSchools(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_CLASSES -> { + data.startProgress(R.string.edziennik_progress_endpoint_classes) + LibrusApiClasses(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_VIRTUAL_CLASSES -> { + data.startProgress(R.string.edziennik_progress_endpoint_teams) + LibrusApiVirtualClasses(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_UNITS -> { + data.startProgress(R.string.edziennik_progress_endpoint_units) + LibrusApiUnits(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_USERS -> { + data.startProgress(R.string.edziennik_progress_endpoint_teachers) + LibrusApiUsers(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_SUBJECTS -> { + data.startProgress(R.string.edziennik_progress_endpoint_subjects) + LibrusApiSubjects(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_CLASSROOMS -> { + data.startProgress(R.string.edziennik_progress_endpoint_classrooms) + LibrusApiClassrooms(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_LESSONS -> { + data.startProgress(R.string.edziennik_progress_endpoint_lessons) + LibrusApiLessons(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_PUSH_CONFIG -> { + data.startProgress(R.string.edziennik_progress_endpoint_push_config) + LibrusApiPushConfig(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_TIMETABLES -> { + data.startProgress(R.string.edziennik_progress_endpoint_timetable) + LibrusApiTimetables(data, lastSync, onSuccess) + } + + ENDPOINT_LIBRUS_API_NORMAL_GRADE_CATEGORIES -> { + data.startProgress(R.string.edziennik_progress_endpoint_grade_categories) + LibrusApiGradeCategories(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADE_CATEGORIES -> { + data.startProgress(R.string.edziennik_progress_endpoint_grade_categories) + LibrusApiBehaviourGradeCategories(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_DESCRIPTIVE_GRADE_CATEGORIES -> { + data.startProgress(R.string.edziennik_progress_endpoint_grade_categories) + LibrusApiDescriptiveGradeCategories(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_TEXT_GRADE_CATEGORIES -> { + data.startProgress(R.string.edziennik_progress_endpoint_grade_categories) + LibrusApiTextGradeCategories(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_POINT_GRADE_CATEGORIES -> { + data.startProgress(R.string.edziennik_progress_endpoint_grade_categories) + LibrusApiPointGradeCategories(data, lastSync, onSuccess) + } + + ENDPOINT_LIBRUS_API_NORMAL_GRADE_COMMENTS -> { + data.startProgress(R.string.edziennik_progress_endpoint_grade_comments) + LibrusApiGradeComments(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADE_COMMENTS -> { + data.startProgress(R.string.edziennik_progress_endpoint_grade_comments) + LibrusApiBehaviourGradeComments(data, lastSync, onSuccess) + } + + ENDPOINT_LIBRUS_API_NORMAL_GRADES -> { + data.startProgress(R.string.edziennik_progress_endpoint_grades) + LibrusApiGrades(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADES -> { + data.startProgress(R.string.edziennik_progress_endpoint_behaviour_grades) + LibrusApiBehaviourGrades(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_DESCRIPTIVE_GRADES -> { + data.startProgress(R.string.edziennik_progress_endpoint_descriptive_grades) + LibrusApiDescriptiveGrades(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_TEXT_GRADES -> { + data.startProgress(R.string.edziennik_progress_endpoint_descriptive_grades) + LibrusApiTextGrades(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_POINT_GRADES -> { + data.startProgress(R.string.edziennik_progress_endpoint_point_grades) + LibrusApiPointGrades(data, lastSync, onSuccess) + } + + ENDPOINT_LIBRUS_API_EVENT_TYPES -> { + data.startProgress(R.string.edziennik_progress_endpoint_event_types) + LibrusApiEventTypes(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_EVENTS -> { + data.startProgress(R.string.edziennik_progress_endpoint_events) + LibrusApiEvents(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_HOMEWORK -> { + data.startProgress(R.string.edziennik_progress_endpoint_homework) + LibrusApiHomework(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_LUCKY_NUMBER -> { + data.startProgress(R.string.edziennik_progress_endpoint_lucky_number) + LibrusApiLuckyNumber(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_NOTICE_TYPES -> { + data.startProgress(R.string.edziennik_progress_endpoint_notice_types) + LibrusApiNoticeTypes(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_NOTICES -> { + data.startProgress(R.string.edziennik_progress_endpoint_notices) + LibrusApiNotices(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_ATTENDANCE_TYPES -> { + data.startProgress(R.string.edziennik_progress_endpoint_attendance_types) + LibrusApiAttendanceTypes(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_ATTENDANCES -> { + data.startProgress(R.string.edziennik_progress_endpoint_attendance) + LibrusApiAttendances(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_ANNOUNCEMENTS -> { + data.startProgress(R.string.edziennik_progress_endpoint_announcements) + LibrusApiAnnouncements(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_PT_MEETINGS -> { + data.startProgress(R.string.edziennik_progress_endpoint_pt_meetings) + LibrusApiPtMeetings(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_API_TEACHER_FREE_DAYS -> { + data.startProgress(R.string.edziennik_progress_endpoint_teacher_free_days) + LibrusApiTeacherFreeDays(data, lastSync, onSuccess) + } + + /** + * SYNERGIA + */ + ENDPOINT_LIBRUS_SYNERGIA_HOMEWORK -> { + data.startProgress(R.string.edziennik_progress_endpoint_homework) + LibrusSynergiaHomework(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_SYNERGIA_INFO -> { + data.startProgress(R.string.edziennik_progress_endpoint_student_info) + LibrusSynergiaInfo(data, lastSync, onSuccess) + } + ENDPOINT_LIBRUS_SYNERGIA_MESSAGES_RECEIVED -> { + data.startProgress(R.string.edziennik_progress_endpoint_messages_inbox) + LibrusSynergiaGetMessages(data, type = Message.TYPE_RECEIVED, lastSync = lastSync, onSuccess = onSuccess) + } + ENDPOINT_LIBRUS_SYNERGIA_MESSAGES_SENT -> { + data.startProgress(R.string.edziennik_progress_endpoint_messages_outbox) + LibrusSynergiaGetMessages(data, type = Message.TYPE_SENT, lastSync = lastSync, onSuccess = onSuccess) + } + + /** + * MESSAGES + */ + ENDPOINT_LIBRUS_MESSAGES_RECEIVED -> { + data.startProgress(R.string.edziennik_progress_endpoint_messages_inbox) + if (data.messagesLoginSuccessful) LibrusMessagesGetList(data, type = Message.TYPE_RECEIVED, lastSync = lastSync, onSuccess = onSuccess) + else LibrusSynergiaGetMessages(data, type = Message.TYPE_RECEIVED, lastSync = lastSync, onSuccess = onSuccess) + } + ENDPOINT_LIBRUS_MESSAGES_SENT -> { + data.startProgress(R.string.edziennik_progress_endpoint_messages_outbox) + if (data.messagesLoginSuccessful) LibrusMessagesGetList(data, type = Message.TYPE_SENT, lastSync = lastSync, onSuccess = onSuccess) + else LibrusSynergiaGetMessages(data, type = Message.TYPE_SENT, lastSync = lastSync, onSuccess = onSuccess) + } + + else -> onSuccess(endpointId) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/LibrusMessages.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/LibrusMessages.kt new file mode 100644 index 00000000..dc8d8c47 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/LibrusMessages.kt @@ -0,0 +1,307 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-10-24 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data + +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.body.MediaTypeUtils +import im.wangchao.mhttp.callback.FileCallbackHandler +import im.wangchao.mhttp.callback.JsonCallbackHandler +import im.wangchao.mhttp.callback.TextCallbackHandler +import org.json.JSONObject +import org.json.XML +import org.jsoup.Jsoup +import org.jsoup.nodes.Document +import org.jsoup.parser.Parser +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.utils.Utils.d +import java.io.File +import java.io.StringWriter +import javax.xml.parsers.DocumentBuilderFactory +import javax.xml.transform.OutputKeys +import javax.xml.transform.TransformerFactory +import javax.xml.transform.dom.DOMSource +import javax.xml.transform.stream.StreamResult + +open class LibrusMessages(open val data: DataLibrus, open val lastSync: Long?) { + companion object { + private const val TAG = "LibrusMessages" + } + + val profileId + get() = data.profile?.id ?: -1 + + val profile + get() = data.profile + + fun messagesGet(tag: String, module: String, method: Int = POST, + parameters: Map? = null, onSuccess: (doc: Document) -> Unit) { + + d(tag, "Request: Librus/Messages - $LIBRUS_MESSAGES_URL/$module") + + val callback = object : TextCallbackHandler() { + override fun onSuccess(text: String?, response: Response?) { + if (text.isNullOrEmpty()) { + data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) + .withResponse(response)) + return + } + + when { + text.contains("Niepoprawny login i/lub hasło.") -> ERROR_LOGIN_LIBRUS_MESSAGES_INVALID_LOGIN + text.contains("Nie odnaleziono wiadomości.") -> ERROR_LIBRUS_MESSAGES_NOT_FOUND + text.contains("stop.png") -> ERROR_LIBRUS_SYNERGIA_ACCESS_DENIED + text.contains("eAccessDeny") -> ERROR_LIBRUS_MESSAGES_ACCESS_DENIED + text.contains("OffLine") -> ERROR_LIBRUS_MESSAGES_MAINTENANCE + text.contains("error") -> ERROR_LIBRUS_MESSAGES_ERROR + text.contains("eVarWhitThisNameNotExists") -> ERROR_LIBRUS_MESSAGES_ACCESS_DENIED + text.contains("") -> ERROR_LIBRUS_MESSAGES_OTHER + else -> null + }?.let { errorCode -> + data.error(ApiError(tag, errorCode) + .withApiResponse(text) + .withResponse(response)) + return + } + + try { + val doc = Jsoup.parse(text, "", Parser.xmlParser()) + onSuccess(doc) + } catch (e: Exception) { + data.error(ApiError(tag, EXCEPTION_LIBRUS_MESSAGES_REQUEST) + .withResponse(response) + .withThrowable(e) + .withApiResponse(text)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(tag, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + data.app.cookieJar.set("wiadomosci.librus.pl", "DZIENNIKSID", data.messagesSessionId) + + val docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder() + val doc = docBuilder.newDocument() + val serviceElement = doc.createElement("service") + val headerElement = doc.createElement("header") + val dataElement = doc.createElement("data") + for ((key, value) in parameters.orEmpty()) { + val element = doc.createElement(key) + element.appendChild(doc.createTextNode(value.toString())) + dataElement.appendChild(element) + } + serviceElement.appendChild(headerElement) + serviceElement.appendChild(dataElement) + doc.appendChild(serviceElement) + val transformer = TransformerFactory.newInstance().newTransformer() + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes") + val stringWriter = StringWriter() + transformer.transform(DOMSource(doc), StreamResult(stringWriter)) + val requestXml = stringWriter.toString() + + Request.builder() + .url("$LIBRUS_MESSAGES_URL/$module") + .userAgent(SYNERGIA_USER_AGENT) + .setTextBody(requestXml, MediaTypeUtils.APPLICATION_XML) + .apply { + when (method) { + GET -> get() + POST -> post() + } + } + .callback(callback) + .build() + .enqueue() + } + + fun messagesGetJson(tag: String, module: String, method: Int = POST, + parameters: Map? = null, onSuccess: (json: JsonObject?) -> Unit) { + + d(tag, "Request: Librus/Messages - $LIBRUS_MESSAGES_URL/$module") + + val callback = object : TextCallbackHandler() { + override fun onSuccess(text: String?, response: Response?) { + if (text.isNullOrEmpty()) { + data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) + .withResponse(response)) + return + } + + when { + text.contains("Niepoprawny login i/lub hasło.") -> ERROR_LOGIN_LIBRUS_MESSAGES_INVALID_LOGIN + text.contains("Nie odnaleziono wiadomości.") -> ERROR_LIBRUS_MESSAGES_NOT_FOUND + text.contains("stop.png") -> ERROR_LIBRUS_SYNERGIA_ACCESS_DENIED + text.contains("eAccessDeny") -> ERROR_LIBRUS_MESSAGES_ACCESS_DENIED + text.contains("OffLine") -> ERROR_LIBRUS_MESSAGES_MAINTENANCE + text.contains("error") -> ERROR_LIBRUS_MESSAGES_ERROR + text.contains("eVarWhitThisNameNotExists") -> ERROR_LIBRUS_MESSAGES_ACCESS_DENIED + text.contains("") -> ERROR_LIBRUS_MESSAGES_OTHER + else -> null + }?.let { errorCode -> + data.error(ApiError(tag, errorCode) + .withApiResponse(text) + .withResponse(response)) + return + } + + try { + val json: JSONObject? = XML.toJSONObject(text) + onSuccess(JsonParser().parse(json?.toString() ?: "{}")?.asJsonObject) + } catch (e: Exception) { + data.error(ApiError(tag, EXCEPTION_LIBRUS_MESSAGES_REQUEST) + .withResponse(response) + .withThrowable(e) + .withApiResponse(text)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(tag, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + data.app.cookieJar.set("wiadomosci.librus.pl", "DZIENNIKSID", data.messagesSessionId) + + val docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder() + val doc = docBuilder.newDocument() + val serviceElement = doc.createElement("service") + val headerElement = doc.createElement("header") + val dataElement = doc.createElement("data") + for ((key, value) in parameters.orEmpty()) { + val element = doc.createElement(key) + element.appendChild(doc.createTextNode(value.toString())) + dataElement.appendChild(element) + } + serviceElement.appendChild(headerElement) + serviceElement.appendChild(dataElement) + doc.appendChild(serviceElement) + val transformer = TransformerFactory.newInstance().newTransformer() + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes") + val stringWriter = StringWriter() + transformer.transform(DOMSource(doc), StreamResult(stringWriter)) + val requestXml = stringWriter.toString() + + Request.builder() + .url("$LIBRUS_MESSAGES_URL/$module") + .userAgent(SYNERGIA_USER_AGENT) + .setTextBody(requestXml, MediaTypeUtils.APPLICATION_XML) + .apply { + when (method) { + GET -> get() + POST -> post() + } + } + .callback(callback) + .build() + .enqueue() + } + + fun sandboxGet(tag: String, action: String, parameters: Map? = null, + onSuccess: (json: JsonObject) -> Unit) { + + d(tag, "Request: Librus/Messages - $LIBRUS_SANDBOX_URL$action") + + val callback = object : JsonCallbackHandler() { + override fun onSuccess(json: JsonObject?, response: Response?) { + if (json == null) { + data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) + .withResponse(response)) + return + } + + try { + onSuccess(json) + } catch (e: Exception) { + data.error(ApiError(tag, EXCEPTION_LIBRUS_MESSAGES_REQUEST) + .withResponse(response) + .withThrowable(e) + .withApiResponse(json)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(tag, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + Request.builder() + .url("$LIBRUS_SANDBOX_URL$action") + .userAgent(SYNERGIA_USER_AGENT) + .apply { + parameters?.forEach { (k, v) -> + addParameter(k, v) + } + } + .post() + .callback(callback) + .build() + .enqueue() + } + + fun sandboxGetFile(tag: String, url: String, targetFile: File, onSuccess: (file: File) -> Unit, + method: Int = GET, + onProgress: (written: Long, total: Long) -> Unit) { + + d(tag, "Request: Librus/Messages - $url") + + val callback = object : FileCallbackHandler(targetFile) { + override fun onSuccess(file: File?, response: Response?) { + if (file == null) { + data.error(ApiError(TAG, ERROR_FILE_DOWNLOAD) + .withResponse(response)) + return + } + + try { + onSuccess(file) + } catch (e: Exception) { + data.error(ApiError(tag, EXCEPTION_LIBRUS_MESSAGES_FILE_REQUEST) + .withResponse(response) + .withThrowable(e)) + } + } + + override fun onProgress(bytesWritten: Long, bytesTotal: Long) { + try { + onProgress(bytesWritten, bytesTotal) + } catch (e: Exception) { + data.error(ApiError(tag, EXCEPTION_LIBRUS_MESSAGES_FILE_REQUEST) + .withThrowable(e)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(tag, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + Request.builder() + .url(url) + .userAgent(SYNERGIA_USER_AGENT) + .also { + when (method) { + POST -> it.post() + else -> it.get() + } + } + .callback(callback) + .build() + .enqueue() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/LibrusPortal.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/LibrusPortal.kt new file mode 100644 index 00000000..d1d34226 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/LibrusPortal.kt @@ -0,0 +1,106 @@ +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data + +import com.google.gson.JsonObject +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.callback.JsonCallbackHandler +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.utils.Utils.d +import java.net.HttpURLConnection + +open class LibrusPortal(open val data: DataLibrus) { + companion object { + private const val TAG = "LibrusPortal" + } + + val profileId + get() = data.profile?.id ?: -1 + + val profile + get() = data.profile + + fun portalGet(tag: String, endpoint: String, method: Int = GET, payload: JsonObject? = null, onSuccess: (json: JsonObject, response: Response?) -> Unit) { + + d(tag, "Request: Librus/Portal - ${if (data.fakeLogin) FAKE_LIBRUS_PORTAL else LIBRUS_PORTAL_URL}$endpoint") + + val callback = object : JsonCallbackHandler() { + override fun onSuccess(json: JsonObject?, response: Response?) { + if (json == null) { + data.error(ApiError(tag, ERROR_RESPONSE_EMPTY) + .withResponse(response)) + return + } + val error = if (response?.code() == 200) null else + json.getString("reason") ?: + json.getString("message") ?: + json.getString("hint") ?: + json.getString("Code") + error?.let { code -> + when (code) { + "requires_an_action" -> ERROR_LIBRUS_PORTAL_SYNERGIA_DISCONNECTED + "Access token is invalid" -> ERROR_LIBRUS_PORTAL_ACCESS_DENIED + "ApiDisabled" -> ERROR_LIBRUS_PORTAL_API_DISABLED + "Account not found" -> ERROR_LIBRUS_PORTAL_SYNERGIA_NOT_FOUND + "Unable to refresh the account" -> ERROR_LIBRUS_PORTAL_MAINTENANCE + else -> when (json.getString("hint")) { + "Error while decoding to JSON" -> ERROR_LIBRUS_PORTAL_ACCESS_DENIED + else -> ERROR_LIBRUS_PORTAL_OTHER + } + }.let { errorCode -> + data.error(ApiError(tag, errorCode) + .withApiResponse(json) + .withResponse(response)) + return + } + } + if (response?.code() == HttpURLConnection.HTTP_OK) { + try { + onSuccess(json, response) + } catch (e: NullPointerException) { + e.printStackTrace() + data.error(ApiError(tag, EXCEPTION_LIBRUS_PORTAL_SYNERGIA_TOKEN) + .withResponse(response) + .withThrowable(e) + .withApiResponse(json)) + } + + } else { + data.error(ApiError(tag, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withApiResponse(json)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(tag, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + Request.builder() + .url((if (data.fakeLogin) FAKE_LIBRUS_PORTAL else LIBRUS_PORTAL_URL) + endpoint) + .userAgent(LIBRUS_USER_AGENT) + .addHeader("Authorization", "Bearer ${data.portalAccessToken}") + .apply { + when (method) { + GET -> get() + POST -> post() + } + if (payload != null) + setJsonBody(payload) + } + .allowErrorCode(HttpURLConnection.HTTP_NOT_FOUND) + .allowErrorCode(HttpURLConnection.HTTP_FORBIDDEN) + .allowErrorCode(HttpURLConnection.HTTP_UNAUTHORIZED) + .allowErrorCode(HttpURLConnection.HTTP_BAD_REQUEST) + .allowErrorCode(HttpURLConnection.HTTP_GONE) + .allowErrorCode(424) + .callback(callback) + .build() + .enqueue() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/LibrusSynergia.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/LibrusSynergia.kt new file mode 100644 index 00000000..72faf801 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/LibrusSynergia.kt @@ -0,0 +1,132 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-10-21. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data + +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.callback.TextCallbackHandler +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.utils.Utils.d + +open class LibrusSynergia(open val data: DataLibrus, open val lastSync: Long?) { + companion object { + private const val TAG = "LibrusSynergia" + } + + val profileId + get() = data.profile?.id ?: -1 + + val profile + get() = data.profile + + fun synergiaGet(tag: String, endpoint: String, method: Int = GET, + parameters: Map = emptyMap(), onSuccess: (text: String) -> Unit) { + d(tag, "Request: Librus/Synergia - $LIBRUS_SYNERGIA_URL/$endpoint") + + val callback = object : TextCallbackHandler() { + override fun onSuccess(text: String?, response: Response?) { + if (text.isNullOrEmpty()) { + data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) + .withResponse(response)) + return + } + + if (!text.contains("jesteś zalogowany") && !text.contains("Podgląd zadania")) { + when { + text.contains("stop.png") -> ERROR_LIBRUS_SYNERGIA_ACCESS_DENIED + text.contains("Przerwa techniczna") -> ERROR_LIBRUS_SYNERGIA_MAINTENANCE + else -> ERROR_LIBRUS_SYNERGIA_OTHER + }.let { errorCode -> + data.error(ApiError(tag, errorCode) + .withResponse(response) + .withApiResponse(text)) + return + } + } + + try { + onSuccess(text) + } catch (e: Exception) { + data.error(ApiError(tag, EXCEPTION_LIBRUS_SYNERGIA_REQUEST) + .withResponse(response) + .withThrowable(e) + .withApiResponse(text)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(tag, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + /*data.app.cookieJar.saveFromResponse(null, listOf( + Cookie.Builder() + .name("DZIENNIKSID") + .value(data.synergiaSessionId!!) + .domain("synergia.librus.pl") + .secure().httpOnly().build() + ))*/ + + Request.builder() + .url("$LIBRUS_SYNERGIA_URL/$endpoint") + .userAgent(LIBRUS_USER_AGENT) + .apply { + when (method) { + GET -> get() + POST -> post() + } + parameters.map { (name, value) -> + addParameter(name, value) + } + } + .callback(callback) + .build() + .enqueue() + } + + fun redirectUrlGet(tag: String, url: String, onSuccess: (url: String) -> Unit) { + d(tag, "Request: Librus/Synergia - $url") + + val callback = object : TextCallbackHandler() { + override fun onSuccess(text: String?, response: Response) { + val redirectUrl = response.headers().get("Location") + + if (redirectUrl != null) { + try { + onSuccess(redirectUrl) + } catch (e: Exception) { + data.error(ApiError(tag, EXCEPTION_LIBRUS_SYNERGIA_REQUEST) + .withResponse(response) + .withThrowable(e) + .withApiResponse(text)) + } + } else { + data.error(ApiError(tag, ERROR_LIBRUS_SYNERGIA_OTHER) + .withResponse(response) + .withApiResponse(text)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(tag, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + Request.builder() + .url(url) + .userAgent(LIBRUS_USER_AGENT) + .withClient(data.app.httpLazy) + .get() + .callback(callback) + .build() + .enqueue() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiAnnouncementMarkAsRead.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiAnnouncementMarkAsRead.kt new file mode 100644 index 00000000..23cfceb4 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiAnnouncementMarkAsRead.kt @@ -0,0 +1,45 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-27 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.data.api.ERROR_LIBRUS_API_INVALID_REQUEST_PARAMS +import pl.szczodrzynski.edziennik.data.api.ERROR_LIBRUS_API_NOTICEBOARD_PROBLEM +import pl.szczodrzynski.edziennik.data.api.POST +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.api.events.AnnouncementGetEvent +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.full.AnnouncementFull + +class LibrusApiAnnouncementMarkAsRead(override val data: DataLibrus, + private val announcement: AnnouncementFull, + val onSuccess: () -> Unit +) : LibrusApi(data, null) { + companion object { + const val TAG = "LibrusApiAnnouncementMarkAsRead" + } + + init { + apiGet(TAG, "SchoolNotices/MarkAsRead/${announcement.idString}", method = POST, + ignoreErrors = listOf( + ERROR_LIBRUS_API_INVALID_REQUEST_PARAMS, + ERROR_LIBRUS_API_NOTICEBOARD_PROBLEM + )) { + announcement.seen = true + + EventBus.getDefault().postSticky(AnnouncementGetEvent(announcement)) + + data.setSeenMetadataList.add(Metadata( + profileId, + Metadata.TYPE_ANNOUNCEMENT, + announcement.id, + announcement.seen, + announcement.notified + )) + onSuccess() + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiAnnouncements.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiAnnouncements.kt new file mode 100644 index 00000000..fcf68cad --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiAnnouncements.kt @@ -0,0 +1,68 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-10-13 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_ANNOUNCEMENTS +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.Announcement +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.models.Date + +class LibrusApiAnnouncements(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiAnnouncements" + } + + init { data.profile?.also { profile -> + apiGet(TAG, "SchoolNotices") { json -> + val announcements = json.getJsonArray("SchoolNotices")?.asJsonObjectList() + + announcements?.forEach { announcement -> + val longId = announcement.getString("Id") ?: return@forEach + val id = longId.crc32() + val subject = announcement.getString("Subject") ?: "" + val text = announcement.getString("Content") ?: "" + val startDate = Date.fromY_m_d(announcement.getString("StartDate")) + val endDate = Date.fromY_m_d(announcement.getString("EndDate")) + val teacherId = announcement.getJsonObject("AddedBy")?.getLong("Id") ?: -1 + val addedDate = announcement.getString("CreationDate")?.let { Date.fromIso(it) } + ?: System.currentTimeMillis() + val read = announcement.getBoolean("WasRead") ?: false + + val announcementObject = Announcement( + profileId = profileId, + id = id, + subject = subject, + text = text, + startDate = startDate, + endDate = endDate, + teacherId = teacherId, + addedDate = addedDate + ).also { + it.idString = longId + } + + data.announcementList.add(announcementObject) + data.setSeenMetadataList.add(Metadata( + profileId, + Metadata.TYPE_ANNOUNCEMENT, + id, + read, + profile.empty || read + )) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_ANNOUNCEMENTS, SYNC_ALWAYS) + onSuccess(ENDPOINT_LIBRUS_API_ANNOUNCEMENTS) + } + }} +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiAttendanceTypes.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiAttendanceTypes.kt new file mode 100644 index 00000000..417a1de0 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiAttendanceTypes.kt @@ -0,0 +1,66 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-10-13 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import android.graphics.Color +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_ATTENDANCE_TYPES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.data.db.entity.AttendanceType +import pl.szczodrzynski.edziennik.ext.* + +class LibrusApiAttendanceTypes(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiAttendanceTypes" + } + + init { + apiGet(TAG, "Attendances/Types") { json -> + val attendanceTypes = json.getJsonArray("Types")?.asJsonObjectList() + + attendanceTypes?.forEach { attendanceType -> + val id = attendanceType.getLong("Id") ?: return@forEach + + val typeName = attendanceType.getString("Name") ?: "" + val typeSymbol = attendanceType.getString("Short") ?: "" + val typeColor = attendanceType.getString("ColorRGB")?.let { Color.parseColor("#$it") } + + val isStandard = attendanceType.getBoolean("Standard") ?: false + val baseType = when (attendanceType.getJsonObject("StandardType")?.getLong("Id") ?: id) { + 1L -> Attendance.TYPE_ABSENT + 2L -> Attendance.TYPE_BELATED + 3L -> Attendance.TYPE_ABSENT_EXCUSED + 4L -> Attendance.TYPE_RELEASED + /*100*/else -> when (isStandard) { + true -> Attendance.TYPE_PRESENT + false -> Attendance.TYPE_PRESENT_CUSTOM + } + } + val typeShort = when (isStandard) { + true -> data.app.attendanceManager.getTypeShort(baseType) + false -> typeSymbol + } + + data.attendanceTypes.put(id, AttendanceType( + profileId, + id, + baseType, + typeName, + typeShort, + typeSymbol, + typeColor + )) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_ATTENDANCE_TYPES, 2* DAY) + onSuccess(ENDPOINT_LIBRUS_API_ATTENDANCE_TYPES) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiAttendances.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiAttendances.kt new file mode 100644 index 00000000..314a0716 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiAttendances.kt @@ -0,0 +1,91 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-10-13 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import androidx.core.util.isEmpty +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_ATTENDANCES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.models.Date + +class LibrusApiAttendances(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiAttendances" + } + + init { + if (data.attendanceTypes.isEmpty()) { + data.db.attendanceTypeDao().getAllNow(profileId).toSparseArray(data.attendanceTypes) { it.id } + } + if (data.librusLessons.isEmpty()) { + data.db.librusLessonDao().getAllNow(profileId).toSparseArray(data.librusLessons) { it.lessonId } + } + + apiGet(TAG, "Attendances") { json -> + val attendances = json.getJsonArray("Attendances")?.asJsonObjectList() + + attendances?.forEach { attendance -> + val id = ((attendance.getString("Id") ?: return@forEach) + .replace("[^\\d.]".toRegex(), "")).toLong() + val lessonId = attendance.getJsonObject("Lesson")?.getLong("Id") ?: -1 + val lessonNo = attendance.getInt("LessonNo") ?: return@forEach + val lessonDate = Date.fromY_m_d(attendance.getString("Date")) + val teacherId = attendance.getJsonObject("AddedBy")?.getLong("Id") + val semester = attendance.getInt("Semester") ?: return@forEach + + val typeId = attendance.getJsonObject("Type")?.getLong("Id") ?: return@forEach + val type = data.attendanceTypes[typeId] ?: null + + val startTime = data.lessonRanges.get(lessonNo)?.startTime + + val lesson = if (lessonId != -1L) + data.librusLessons.singleOrNull { it.lessonId == lessonId } + else null + + val addedDate = Date.fromIso(attendance.getString("AddDate") ?: return@forEach) + + val attendanceObject = Attendance( + profileId = profileId, + id = id, + baseType = type?.baseType ?: Attendance.TYPE_UNKNOWN, + typeName = type?.typeName ?: "nieznany rodzaj", + typeShort = type?.typeShort ?: "?", + typeSymbol = type?.typeSymbol ?: "?", + typeColor = type?.typeColor, + date = lessonDate, + startTime = startTime, + semester = semester, + teacherId = teacherId ?: lesson?.teacherId ?: -1, + subjectId = lesson?.subjectId ?: -1, + addedDate = addedDate + ).also { + it.lessonNumber = lessonNo + } + + data.attendanceList.add(attendanceObject) + if(type?.baseType != Attendance.TYPE_PRESENT) { + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_ATTENDANCE, + id, + profile?.empty ?: false || type?.baseType == Attendance.TYPE_PRESENT_CUSTOM || type?.baseType == Attendance.TYPE_UNKNOWN, + profile?.empty ?: false || type?.baseType == Attendance.TYPE_PRESENT_CUSTOM || type?.baseType == Attendance.TYPE_UNKNOWN + )) + } + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_ATTENDANCES, SYNC_ALWAYS) + onSuccess(ENDPOINT_LIBRUS_API_ATTENDANCES) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiBehaviourGradeCategories.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiBehaviourGradeCategories.kt new file mode 100644 index 00000000..24992be1 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiBehaviourGradeCategories.kt @@ -0,0 +1,49 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-3 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import android.graphics.Color +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADE_CATEGORIES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.GradeCategory +import pl.szczodrzynski.edziennik.ext.* + +class LibrusApiBehaviourGradeCategories(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiBehaviourGradeCategories" + } + + init { + apiGet(TAG, "BehaviourGrades/Points/Categories") { json -> + json.getJsonArray("Categories")?.asJsonObjectList()?.forEach { category -> + val id = category.getLong("Id") ?: return@forEach + val name = category.getString("Name") ?: "" + val valueFrom = category.getFloat("ValueFrom") ?: 0f + val valueTo = category.getFloat("ValueTo") ?: 0f + + val gradeCategoryObject = GradeCategory( + profileId, + id, + -1f, + Color.BLUE, + name + ).apply { + type = GradeCategory.TYPE_BEHAVIOUR + setValueRange(valueFrom, valueTo) + } + + data.gradeCategories.put(id, gradeCategoryObject) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADE_CATEGORIES, 1 * WEEK) + onSuccess(ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADE_CATEGORIES) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiBehaviourGradeComments.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiBehaviourGradeComments.kt new file mode 100644 index 00000000..4f44c0f0 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiBehaviourGradeComments.kt @@ -0,0 +1,47 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-7 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADE_COMMENTS +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.GradeCategory +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* + +class LibrusApiBehaviourGradeComments(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiBehaviourGradeComments" + } + + init { + apiGet(TAG, "BehaviourGrades/Points/Comments") { json -> + + json.getJsonArray("Comments")?.asJsonObjectList()?.forEach { comment -> + val id = comment.getLong("Id") ?: return@forEach + val text = comment.getString("Text")?.fixWhiteSpaces() ?: return@forEach + + val gradeCategoryObject = GradeCategory( + profileId, + id, + -1f, + -1, + text + ).apply { + type = GradeCategory.TYPE_BEHAVIOUR_COMMENT + } + + data.gradeCategories.put(id, gradeCategoryObject) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADE_COMMENTS, SYNC_ALWAYS) + onSuccess(ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADE_COMMENTS) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiBehaviourGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiBehaviourGrades.kt new file mode 100644 index 00000000..7a528407 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiBehaviourGrades.kt @@ -0,0 +1,180 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-3 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Grade +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_POINT_SUM +import pl.szczodrzynski.edziennik.data.db.entity.GradeCategory +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.models.Date +import java.text.DecimalFormat + +class LibrusApiBehaviourGrades(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiBehaviourGrades" + } + + private val nameFormat by lazy { DecimalFormat("#.##") } + + private val types by lazy { + mapOf( + 1 to ("wz" to "wzorowe"), + 2 to ("bdb" to "bardzo dobre"), + 3 to ("db" to "dobre"), + 4 to ("popr" to "poprawne"), + 5 to ("ndp" to "nieodpowiednie"), + 6 to ("ng" to "naganne") + ) + } + + init { data.profile?.also { profile -> + apiGet(TAG, "BehaviourGrades/Points") { json -> + + if (data.startPointsSemester1 > 0) { + val semester1StartGradeObject = Grade( + profileId = profileId, + id = -101, + name = nameFormat.format(data.startPointsSemester1), + type = TYPE_POINT_SUM, + value = data.startPointsSemester1.toFloat(), + weight = 0f, + color = 0xffbdbdbd.toInt(), + category = data.app.getString(R.string.grade_start_points), + description = data.app.getString(R.string.grade_start_points_format, 1), + comment = null, + semester = 1, + teacherId = -1, + subjectId = 1, + addedDate = profile.getSemesterStart(1).inMillis + ) + + data.gradeList.add(semester1StartGradeObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_GRADE, + semester1StartGradeObject.id, + true, + true + )) + } + + if (data.startPointsSemester2 > 0) { + val semester2StartGradeObject = Grade( + profileId = profileId, + id = -102, + name = nameFormat.format(data.startPointsSemester2), + type = TYPE_POINT_SUM, + value = data.startPointsSemester2.toFloat(), + weight = -1f, + color = 0xffbdbdbd.toInt(), + category = data.app.getString(R.string.grade_start_points), + description = data.app.getString(R.string.grade_start_points_format, 2), + comment = null, + semester = 2, + teacherId = -1, + subjectId = 1, + addedDate = profile.getSemesterStart(2).inMillis + ) + + data.gradeList.add(semester2StartGradeObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_GRADE, + semester2StartGradeObject.id, + true, + true + )) + } + + json.getJsonArray("Grades")?.asJsonObjectList()?.forEach { grade -> + val id = grade.getLong("Id") ?: return@forEach + val value = grade.getFloat("Value") + val shortName = grade.getString("ShortName") + val semester = grade.getInt("Semester") ?: profile.currentSemester + val teacherId = grade.getJsonObject("AddedBy")?.getLong("Id") ?: -1 + val addedDate = grade.getString("AddDate")?.let { Date.fromIso(it) } + ?: System.currentTimeMillis() + + val text = grade.getString("Text") + val type = grade.getJsonObject("BehaviourGrade")?.getInt("Id")?.let { types[it] } + + val name = when { + type != null -> type.first + value != null -> (if (value > 0) "+" else "") + nameFormat.format(value) + shortName != null -> shortName + else -> return@forEach + } + + val color = data.getColor(when { + value == null || value == 0f -> 12 + value > 0 -> 16 + value < 0 -> 26 + else -> 12 + }) + + val categoryId = grade.getJsonObject("Category")?.getLong("Id") ?: -1 + val category = data.gradeCategories.singleOrNull { + it.categoryId == categoryId && it.type == GradeCategory.TYPE_BEHAVIOUR + } + + val categoryName = category?.text ?: "" + + val comments = grade.getJsonArray("Comments") + ?.asJsonObjectList() + ?.mapNotNull { comment -> + val cId = comment.getLong("Id") ?: return@mapNotNull null + data.gradeCategories[cId]?.text + } ?: listOf() + + val description = listOfNotNull(type?.second) + comments + + val valueFrom = value ?: category?.valueFrom ?: 0f + val valueTo = category?.valueTo ?: 0f + + val gradeObject = Grade( + profileId = profileId, + id = id, + name = name, + type = TYPE_POINT_SUM, + value = valueFrom, + weight = -1f, + color = color, + category = categoryName, + description = text ?: description.join(" - "), + comment = if (text != null) description.join(" - ") else null, + semester = semester, + teacherId = teacherId, + subjectId = 1, + addedDate = addedDate + ).apply { + valueMax = valueTo + } + + data.gradeList.add(gradeObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_GRADE, + id, + profile.empty, + profile.empty + )) + } + + data.toRemove.add(DataRemoveModel.Grades.semesterWithType(profile.currentSemester, Grade.TYPE_POINT_SUM)) + data.setSyncNext(ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADES, SYNC_ALWAYS) + onSuccess(ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADES) + } + } ?: onSuccess(ENDPOINT_LIBRUS_API_BEHAVIOUR_GRADES) } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiClasses.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiClasses.kt new file mode 100644 index 00000000..43baf873 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiClasses.kt @@ -0,0 +1,63 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-10-14 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_CLASSES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.Team +import pl.szczodrzynski.edziennik.ext.DAY +import pl.szczodrzynski.edziennik.ext.getJsonObject +import pl.szczodrzynski.edziennik.ext.getLong +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.utils.models.Date + +class LibrusApiClasses(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiClasses" + } + + init { + apiGet(TAG, "Classes") { json -> + json.getJsonObject("Class")?.also { studentClass -> + val id = studentClass.getLong("Id") ?: return@also + val name = studentClass.getString("Number") + + studentClass.getString("Symbol") + val code = data.schoolName + ":" + name + val teacherId = studentClass.getJsonObject("ClassTutor")?.getLong("Id") ?: -1 + + val teamObject = Team( + profileId, + id, + name, + 1, + code, + teacherId + ) + + data.profile?.studentClassName = name + + data.teamList.put(id, teamObject) + + data.unitId = studentClass.getJsonObject("Unit").getLong("Id") ?: 0L + + profile?.apply { + dateSemester1Start = Date.fromY_m_d(studentClass.getString("BeginSchoolYear") + ?: return@apply) + dateSemester2Start = Date.fromY_m_d(studentClass.getString("EndFirstSemester") + ?: return@apply) + dateYearEnd = Date.fromY_m_d(studentClass.getString("EndSchoolYear") + ?: return@apply) + } + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_CLASSES, 4 * DAY) + onSuccess(ENDPOINT_LIBRUS_API_CLASSES) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiClassrooms.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiClassrooms.kt new file mode 100644 index 00000000..6fbebca5 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiClassrooms.kt @@ -0,0 +1,48 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-24. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_CLASSROOMS +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.Classroom +import pl.szczodrzynski.edziennik.ext.* +import java.util.* + +class LibrusApiClassrooms(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiClassrooms" + } + + init { + apiGet(TAG, "Classrooms") { json -> + val classrooms = json.getJsonArray("Classrooms")?.asJsonObjectList() + + classrooms?.forEach { classroom -> + val id = classroom.getLong("Id") ?: return@forEach + val name = classroom.getString("Name")?.lowercase() ?: "" + val symbol = classroom.getString("Symbol")?.lowercase() ?: "" + val nameShort = name.fixWhiteSpaces().split(" ").onEach { it[0] }.joinToString() + val symbolParts = symbol.fixWhiteSpaces().split(" ") + + val friendlyName = if (name != symbol && !name.contains(symbol) && !name.containsAll(symbolParts) && !nameShort.contains(symbol)) { + classroom.getString("Symbol") + " " + classroom.getString("Name") + } + else { + classroom.getString("Name") ?: "" + } + + data.classrooms.put(id, Classroom(profileId, id, friendlyName)) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_CLASSROOMS, 4* DAY) + onSuccess(ENDPOINT_LIBRUS_API_CLASSROOMS) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiDescriptiveGradeCategories.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiDescriptiveGradeCategories.kt new file mode 100644 index 00000000..c48d34f8 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiDescriptiveGradeCategories.kt @@ -0,0 +1,48 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-29 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import android.graphics.Color +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_DESCRIPTIVE_GRADE_CATEGORIES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.GradeCategory +import pl.szczodrzynski.edziennik.ext.* + +class LibrusApiDescriptiveGradeCategories(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiDescriptiveGradeCategories" + } + + init { + apiGet(TAG, "DescriptiveTextGrades/Skills") { json -> + json.getJsonArray("Skills")?.asJsonObjectList()?.forEach { category -> + val id = category.getLong("Id") ?: return@forEach + val name = category.getString("Name") ?: "" + val color = category.getJsonObject("Color")?.getInt("Id") + ?.let { data.getColor(it) } ?: Color.BLUE + + val gradeCategoryObject = GradeCategory( + profileId, + id, + -1f, + color, + name + ).apply { + type = GradeCategory.TYPE_DESCRIPTIVE + } + + data.gradeCategories.put(id, gradeCategoryObject) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_DESCRIPTIVE_GRADE_CATEGORIES, 1 * DAY) + onSuccess(ENDPOINT_LIBRUS_API_DESCRIPTIVE_GRADE_CATEGORIES) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiDescriptiveGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiDescriptiveGrades.kt new file mode 100644 index 00000000..9b214d04 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiDescriptiveGrades.kt @@ -0,0 +1,94 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-29 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_DESCRIPTIVE_GRADES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Grade +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_DESCRIPTIVE_TEXT +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_TEXT +import pl.szczodrzynski.edziennik.data.db.entity.GradeCategory +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.models.Date + +class LibrusApiDescriptiveGrades(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiDescriptiveGrades" + } + + init { data.profile?.also { profile -> + apiGet(TAG, "BaseTextGrades") { json -> + + json.getJsonArray("Grades")?.asJsonObjectList()?.forEach { grade -> + val id = grade.getLong("Id") ?: return@forEach + val teacherId = grade.getJsonObject("AddedBy")?.getLong("Id") ?: return@forEach + val semester = grade.getInt("Semester") ?: return@forEach + val subjectId = grade.getJsonObject("Subject")?.getLong("Id") ?: return@forEach + val description = grade.getString("Grade") + + val categoryId = grade.getJsonObject("Skill")?.getLong("Id") + ?: grade.getJsonObject("Category")?.getLong("Id") + ?: return@forEach + val type = when (grade.getJsonObject("Category")) { + null -> TYPE_DESCRIPTIVE_TEXT + else -> TYPE_TEXT + } + + val category = data.gradeCategories.singleOrNull { + it.categoryId == categoryId && it.type == when (type) { + TYPE_DESCRIPTIVE_TEXT -> GradeCategory.TYPE_DESCRIPTIVE + else -> GradeCategory.TYPE_NORMAL + } + } + + val addedDate = Date.fromIso(grade.getString("AddDate") ?: return@forEach) + + val gradeObject = Grade( + profileId = profileId, + id = id, + name = " ", + type = type, + value = 0f, + weight = 0f, + color = category?.color ?: -1, + category = category?.text, + description = description, + comment = null, + semester = semester, + teacherId = teacherId, + subjectId = subjectId, + addedDate = addedDate + ) + + data.gradeList.add(gradeObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_GRADE, + id, + profile.empty, + profile.empty + )) + } + + data.toRemove.addAll(listOf( + TYPE_DESCRIPTIVE_TEXT, + TYPE_TEXT + ).map { + DataRemoveModel.Grades.semesterWithType(profile.currentSemester, it) + }) + + data.setSyncNext(ENDPOINT_LIBRUS_API_DESCRIPTIVE_GRADES, SYNC_ALWAYS) + onSuccess(ENDPOINT_LIBRUS_API_DESCRIPTIVE_GRADES) + } + } ?: onSuccess(ENDPOINT_LIBRUS_API_DESCRIPTIVE_GRADES) } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiEventTypes.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiEventTypes.kt new file mode 100644 index 00000000..c2129ba6 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiEventTypes.kt @@ -0,0 +1,38 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-24. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_EVENT_TYPES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.EventType +import pl.szczodrzynski.edziennik.ext.* + +class LibrusApiEventTypes(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiEventTypes" + } + + init { + apiGet(TAG, "HomeWorks/Categories") { json -> + val eventTypes = json.getJsonArray("Categories")?.asJsonObjectList() + + eventTypes?.forEach { eventType -> + val id = eventType.getLong("Id") ?: return@forEach + val name = eventType.getString("Name") ?: "" + val color = data.getColor(eventType.getJsonObject("Color")?.getInt("Id")) + + data.eventTypes.put(id, EventType(profileId, id, name, color)) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_EVENT_TYPES, 4* DAY) + onSuccess(ENDPOINT_LIBRUS_API_EVENT_TYPES) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiEvents.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiEvents.kt new file mode 100644 index 00000000..82a0e267 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiEvents.kt @@ -0,0 +1,90 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-4. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import androidx.core.util.isEmpty +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_EVENTS +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time + +class LibrusApiEvents(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiEvents" + } + + init { + if (data.eventTypes.isEmpty()) { + data.db.eventTypeDao().getAllNow(profileId).toSparseArray(data.eventTypes) { it.id } + } + + apiGet(TAG, "HomeWorks") { json -> + val events = json.getJsonArray("HomeWorks")?.asJsonObjectList() + + events?.forEach { event -> + val id = event.getLong("Id") ?: return@forEach + val eventDate = Date.fromY_m_d(event.getString("Date")) + var topic = event.getString("Content")?.trim() ?: "" + val type = event.getJsonObject("Category")?.getLong("Id") ?: -1 + val teacherId = event.getJsonObject("CreatedBy")?.getLong("Id") ?: -1 + val subjectId = event.getJsonObject("Subject")?.getLong("Id") ?: -1 + val teamId = event.getJsonObject("Class")?.getLong("Id") ?: -1 + + val lessonNo = event.getInt("LessonNo") + val lessonRange = data.lessonRanges.singleOrNull { it.lessonNumber == lessonNo } + val startTime = lessonRange?.startTime ?: Time.fromH_m(event.getString("TimeFrom")) + val addedDate = Date.fromIso(event.getString("AddDate")) + + event.getJsonObject("onlineLessonUrl")?.let { onlineLesson -> + val text = onlineLesson.getString("text")?.let { "$it - " } ?: "" + val url = onlineLesson.getString("url") + topic += "\n\n$text$url" + } + + val eventObject = Event( + profileId = profileId, + id = id, + date = eventDate, + time = startTime, + topic = topic, + color = null, + type = type, + teacherId = teacherId, + subjectId = subjectId, + teamId = teamId, + addedDate = addedDate + ) + + data.eventList.add(eventObject) + data.metadataList.add( + Metadata( + profileId, + Metadata.TYPE_EVENT, + id, + profile?.empty ?: false, + profile?.empty ?: false + )) + } + + data.toRemove.add(DataRemoveModel.Events.futureExceptTypes(listOf( + Event.TYPE_HOMEWORK, + Event.TYPE_PT_MEETING + ))) + + data.setSyncNext(ENDPOINT_LIBRUS_API_EVENTS, SYNC_ALWAYS) + onSuccess(ENDPOINT_LIBRUS_API_EVENTS) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiGradeCategories.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiGradeCategories.kt new file mode 100644 index 00000000..c6c4fecc --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiGradeCategories.kt @@ -0,0 +1,51 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-11-5 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import android.graphics.Color +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_NORMAL_GRADE_CATEGORIES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.GradeCategory +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* + +class LibrusApiGradeCategories(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiGradeCategories" + } + + init { + apiGet(TAG, "Grades/Categories") { json -> + json.getJsonArray("Categories")?.asJsonObjectList()?.forEach { category -> + val id = category.getLong("Id") ?: return@forEach + val name = category.getString("Name")?.fixWhiteSpaces() ?: "" + val weight = when (category.getBoolean("CountToTheAverage")) { + true -> category.getFloat("Weight") ?: 0f + else -> 0f + } + val color = category.getJsonObject("Color")?.getInt("Id") + ?.let { data.getColor(it) } ?: Color.BLUE + + val gradeCategoryObject = GradeCategory( + profileId, + id, + weight, + color, + name + ) + + data.gradeCategories.put(id, gradeCategoryObject) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_NORMAL_GRADE_CATEGORIES, SYNC_ALWAYS) + onSuccess(ENDPOINT_LIBRUS_API_NORMAL_GRADE_CATEGORIES) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiGradeComments.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiGradeComments.kt new file mode 100644 index 00000000..96225b67 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiGradeComments.kt @@ -0,0 +1,47 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-11-20 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_NORMAL_GRADE_COMMENTS +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.GradeCategory +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* + +class LibrusApiGradeComments(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiGradeComments" + } + + init { + apiGet(TAG, "Grades/Comments") { json -> + + json.getJsonArray("Comments")?.asJsonObjectList()?.forEach { comment -> + val id = comment.getLong("Id") ?: return@forEach + val text = comment.getString("Text")?.fixWhiteSpaces() ?: return@forEach + + val gradeCategoryObject = GradeCategory( + profileId, + id, + -1f, + -1, + text + ).apply { + type = GradeCategory.TYPE_NORMAL_COMMENT + } + + data.gradeCategories.put(id, gradeCategoryObject) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_NORMAL_GRADE_COMMENTS, SYNC_ALWAYS) + onSuccess(ENDPOINT_LIBRUS_API_NORMAL_GRADE_COMMENTS) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiGrades.kt new file mode 100644 index 00000000..58621a0e --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiGrades.kt @@ -0,0 +1,122 @@ +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_NORMAL_GRADES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Grade +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_NORMAL +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_SEMESTER1_FINAL +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_SEMESTER1_PROPOSED +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_SEMESTER2_FINAL +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_SEMESTER2_PROPOSED +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_YEAR_FINAL +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_YEAR_PROPOSED +import pl.szczodrzynski.edziennik.data.db.entity.GradeCategory +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.Utils +import pl.szczodrzynski.edziennik.utils.models.Date + +class LibrusApiGrades(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiGrades" + } + + init { data.profile?.also { profile -> + apiGet(TAG, "Grades") { json -> + val grades = json.getJsonArray("Grades")?.asJsonObjectList() + + grades?.forEach { grade -> + val id = grade.getLong("Id") ?: return@forEach + val categoryId = grade.getJsonObject("Category")?.getLong("Id") ?: -1 + val name = grade.getString("Grade") ?: "" + val semester = grade.getInt("Semester") ?: return@forEach + val teacherId = grade.getJsonObject("AddedBy")?.getLong("Id") ?: -1 + val subjectId = grade.getJsonObject("Subject")?.getLong("Id") ?: -1 + val addedDate = Date.fromIso(grade.getString("AddDate")) + + val category = data.gradeCategories.singleOrNull { + it.categoryId == categoryId && it.type == GradeCategory.TYPE_NORMAL + } + + val value = Utils.getGradeValue(name) + val weight = if (name == "-" || name == "+" + || name.equals("np", ignoreCase = true) + || name.equals("bz", ignoreCase = true)) 0f + else category?.weight ?: 0f + + val description = grade.getJsonArray("Comments")?.asJsonObjectList()?.let { comments -> + if (comments.isNotEmpty()) { + data.gradeCategories.singleOrNull { + it.type == GradeCategory.TYPE_NORMAL_COMMENT + && it.categoryId == comments[0].asJsonObject.getLong("Id") + }?.text + } else null + } ?: "" + + val gradeObject = Grade( + profileId = profileId, + id = id, + name = name, + type = when { + grade.getBoolean("IsConstituent") ?: false -> TYPE_NORMAL + grade.getBoolean("IsSemester") ?: false -> if (semester == 1) TYPE_SEMESTER1_FINAL else TYPE_SEMESTER2_FINAL + grade.getBoolean("IsSemesterProposition") ?: false -> if (semester == 1) TYPE_SEMESTER1_PROPOSED else TYPE_SEMESTER2_PROPOSED + grade.getBoolean("IsFinal") ?: false -> TYPE_YEAR_FINAL + grade.getBoolean("IsFinalProposition") ?: false -> TYPE_YEAR_PROPOSED + else -> TYPE_NORMAL + }, + value = value, + weight = weight, + color = category?.color ?: -1, + category = category?.text ?: "", + description = description, + comment = null, + semester = semester, + teacherId = teacherId, + subjectId = subjectId, + addedDate = addedDate + ) + + grade.getJsonObject("Improvement")?.also { + val historicalId = it.getLong("Id") + data.gradeList.firstOrNull { grade -> grade.id == historicalId }?.also { grade -> + grade.parentId = gradeObject.id + if (grade.name == "nb") grade.weight = 0f + } + gradeObject.isImprovement = true + } + + data.gradeList.add(gradeObject) + data.metadataList.add( + Metadata( + profileId, + Metadata.TYPE_GRADE, + id, + profile.empty, + profile.empty + )) + } + + data.toRemove.addAll(listOf( + TYPE_NORMAL, + TYPE_SEMESTER1_FINAL, + TYPE_SEMESTER2_FINAL, + TYPE_SEMESTER1_PROPOSED, + TYPE_SEMESTER2_PROPOSED, + TYPE_YEAR_FINAL, + TYPE_YEAR_PROPOSED + ).map { + DataRemoveModel.Grades.semesterWithType(profile.currentSemester, it) + }) + data.setSyncNext(ENDPOINT_LIBRUS_API_NORMAL_GRADES, SYNC_ALWAYS) + onSuccess(ENDPOINT_LIBRUS_API_NORMAL_GRADES) + } + } ?: onSuccess(ENDPOINT_LIBRUS_API_NORMAL_GRADES) } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiHomework.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiHomework.kt new file mode 100644 index 00000000..f304aaad --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiHomework.kt @@ -0,0 +1,67 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-12. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_HOMEWORK +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.models.Date + +class LibrusApiHomework(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiHomework" + } + + init { + apiGet(TAG, "HomeWorkAssignments") { json -> + val homeworkList = json.getJsonArray("HomeWorkAssignments")?.asJsonObjectList() + + homeworkList?.forEach { homework -> + val id = homework.getLong("Id") ?: return@forEach + val eventDate = Date.fromY_m_d(homework.getString("DueDate")) + val topic = homework.getString("Topic") + "\n" + homework.getString("Text") + val teacherId = homework.getJsonObject("Teacher")?.getLong("Id") ?: -1 + val addedDate = Date.fromY_m_d(homework.getString("Date")) + + val eventObject = Event( + profileId = profileId, + id = id, + date = eventDate, + time = null, + topic = topic, + color = null, + type = -1, + teacherId = teacherId, + subjectId = -1, + teamId = -1, + addedDate = addedDate.inMillis + ) + + data.eventList.add(eventObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_HOMEWORK, + id, + profile?.empty ?: false, + profile?.empty ?: false + )) + } + + data.toRemove.add(DataRemoveModel.Events.futureWithType(Event.TYPE_HOMEWORK)) + + data.setSyncNext(ENDPOINT_LIBRUS_API_HOMEWORK, SYNC_ALWAYS) + onSuccess(ENDPOINT_LIBRUS_API_HOMEWORK) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiLessons.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiLessons.kt new file mode 100644 index 00000000..66075008 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiLessons.kt @@ -0,0 +1,47 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-1-6. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_LESSONS +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.LibrusLesson +import pl.szczodrzynski.edziennik.ext.* + +class LibrusApiLessons(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiLessons" + } + + init { + apiGet(TAG, "Lessons") { json -> + val lessons = json.getJsonArray("Lessons")?.asJsonObjectList() + + lessons?.forEach { lesson -> + val id = lesson.getLong("Id") ?: return@forEach + val teacherId = lesson.getJsonObject("Teacher")?.getLong("Id") ?: return@forEach + val subjectId = lesson.getJsonObject("Subject")?.getLong("Id") ?: return@forEach + val teamId = lesson.getJsonObject("Class")?.getLong("Id") + + val librusLesson = LibrusLesson( + profileId, + id, + teacherId, + subjectId, + teamId + ) + + data.librusLessons.put(id, librusLesson) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_LESSONS, 4* DAY) + onSuccess(ENDPOINT_LIBRUS_API_LESSONS) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiLuckyNumber.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiLuckyNumber.kt new file mode 100644 index 00000000..6ebe9e63 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiLuckyNumber.kt @@ -0,0 +1,62 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-10-14 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_LUCKY_NUMBER +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.LuckyNumber +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time + +class LibrusApiLuckyNumber(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiLuckyNumber" + } + + init { + var nextSync = System.currentTimeMillis() + 2* DAY *1000 + + apiGet(TAG, "LuckyNumbers") { json -> + if (json.isJsonNull) { + //profile?.luckyNumberEnabled = false + } else { + json.getJsonObject("LuckyNumber")?.also { luckyNumberEl -> + + val luckyNumberDate = Date.fromY_m_d(luckyNumberEl.getString("LuckyNumberDay")) ?: Date.getToday() + val luckyNumber = luckyNumberEl.getInt("LuckyNumber") ?: -1 + val luckyNumberObject = LuckyNumber( + profileId = profileId, + date = luckyNumberDate, + number = luckyNumber + ) + + if (luckyNumberDate >= Date.getToday()) + nextSync = luckyNumberDate.combineWith(Time(15, 0, 0)) + else + nextSync = System.currentTimeMillis() + 6* HOUR *1000 + + data.luckyNumberList.add(luckyNumberObject) + data.metadataList.add( + Metadata( + profileId, + Metadata.TYPE_LUCKY_NUMBER, + luckyNumberObject.date.value.toLong(), + true, + profile?.empty ?: false + )) + } + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_LUCKY_NUMBER, syncAt = nextSync) + onSuccess(ENDPOINT_LIBRUS_API_LUCKY_NUMBER) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiMe.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiMe.kt new file mode 100644 index 00000000..ea46971f --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiMe.kt @@ -0,0 +1,41 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-3. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_ME +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.ext.* + +class LibrusApiMe(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiMe" + } + + init { + apiGet(TAG, "Me") { json -> + val me = json.getJsonObject("Me") + val account = me?.getJsonObject("Account") + val user = me?.getJsonObject("User") + + data.isPremium = account?.getBoolean("IsPremium") == true || account?.getBoolean("IsPremiumDemo") == true + + val isParent = account?.getInt("GroupId") == 5 + data.profile?.accountName = + if (isParent) + buildFullName(account?.getString("FirstName"), account?.getString("LastName")) + else null + + data.profile?.studentNameLong = + buildFullName(user?.getString("FirstName"), user?.getString("LastName")) + + data.setSyncNext(ENDPOINT_LIBRUS_API_ME, 2* DAY) + onSuccess(ENDPOINT_LIBRUS_API_ME) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiNoticeTypes.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiNoticeTypes.kt new file mode 100644 index 00000000..7e90fbb2 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiNoticeTypes.kt @@ -0,0 +1,37 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-24. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_NOTICE_TYPES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.NoticeType +import pl.szczodrzynski.edziennik.ext.* + +class LibrusApiNoticeTypes(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiNoticeTypes" + } + + init { + apiGet(TAG, "Notes/Categories") { json -> + val noticeTypes = json.getJsonArray("Categories")?.asJsonObjectList() + + noticeTypes?.forEach { noticeType -> + val id = noticeType.getLong("Id") ?: return@forEach + val name = noticeType.getString("CategoryName") ?: "" + + data.noticeTypes.put(id, NoticeType(profileId, id, name)) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_NOTICE_TYPES, 4* DAY) + onSuccess(ENDPOINT_LIBRUS_API_NOTICE_TYPES) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiNotices.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiNotices.kt new file mode 100644 index 00000000..ea61428e --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiNotices.kt @@ -0,0 +1,76 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-24. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import androidx.core.util.isEmpty +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_NOTICES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.Notice +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.models.Date + +class LibrusApiNotices(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiNotices" + } + + init { + if (data.noticeTypes.isEmpty()) { + data.db.noticeTypeDao().getAllNow(profileId).toSparseArray(data.noticeTypes) { it.id } + } + + apiGet(TAG, "Notes") { json -> + val notes = json.getJsonArray("Notes")?.asJsonObjectList() + + notes?.forEach { note -> + val id = note.getLong("Id") ?: return@forEach + val text = note.getString("Text") ?: "" + val categoryId = note.getJsonObject("Category")?.getLong("Id") ?: -1 + val teacherId = note.getJsonObject("AddedBy")?.getLong("Id") ?: -1 + val addedDate = note.getString("Date")?.let { Date.fromY_m_d(it) } ?: return@forEach + + val type = when (note.getInt("Positive")) { + 0 -> Notice.TYPE_NEGATIVE + 1 -> Notice.TYPE_POSITIVE + /*2*/else -> Notice.TYPE_NEUTRAL + } + val categoryText = data.noticeTypes[categoryId]?.name ?: "" + val semester = profile?.dateToSemester(addedDate) ?: 1 + + val noticeObject = Notice( + profileId = profileId, + id = id, + type = type, + semester = semester, + text = text, + category = categoryText, + points = null, + teacherId = teacherId, + addedDate = addedDate.inMillis + ) + + data.noticeList.add(noticeObject) + data.metadataList.add( + Metadata( + profileId, + Metadata.TYPE_NOTICE, + id, + profile?.empty ?: false, + profile?.empty ?: false + )) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_NOTICES, SYNC_ALWAYS) + onSuccess(ENDPOINT_LIBRUS_API_NOTICES) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiPointGradeCategories.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiPointGradeCategories.kt new file mode 100644 index 00000000..775f0897 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiPointGradeCategories.kt @@ -0,0 +1,53 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-29 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import android.graphics.Color +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_POINT_GRADE_CATEGORIES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.GradeCategory +import pl.szczodrzynski.edziennik.ext.* + +class LibrusApiPointGradeCategories(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiPointGradeCategories" + } + + init { + apiGet(TAG, "PointGrades/Categories") { json -> + json.getJsonArray("Categories")?.asJsonObjectList()?.forEach { category -> + val id = category.getLong("Id") ?: return@forEach + val name = category.getString("Name") ?: "" + val color = category.getJsonObject("Color")?.getInt("Id") + ?.let { data.getColor(it) } ?: Color.BLUE + val countToAverage = category.getBoolean("CountToTheAverage") ?: true + val weight = if (countToAverage) category.getFloat("Weight") ?: 0f else 0f + val valueFrom = category.getFloat("ValueFrom") ?: 0f + val valueTo = category.getFloat("ValueTo") ?: 0f + + val gradeCategoryObject = GradeCategory( + profileId, + id, + weight, + color, + name + ).apply { + type = GradeCategory.TYPE_POINT + setValueRange(valueFrom, valueTo) + } + + data.gradeCategories.put(id, gradeCategoryObject) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_POINT_GRADE_CATEGORIES, 1 * DAY) + onSuccess(ENDPOINT_LIBRUS_API_POINT_GRADE_CATEGORIES) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiPointGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiPointGrades.kt new file mode 100644 index 00000000..8a7ad29f --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiPointGrades.kt @@ -0,0 +1,82 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-29 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_POINT_GRADES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Grade +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_POINT_AVG +import pl.szczodrzynski.edziennik.data.db.entity.GradeCategory +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.models.Date + +class LibrusApiPointGrades(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiPointGrades" + } + + init { data.profile?.also { profile -> + apiGet(TAG, "PointGrades") { json -> + + json.getJsonArray("Grades")?.asJsonObjectList()?.forEach { grade -> + val id = grade.getLong("Id") ?: return@forEach + val teacherId = grade.getJsonObject("AddedBy")?.getLong("Id") ?: return@forEach + val semester = grade.getInt("Semester") ?: return@forEach + val subjectId = grade.getJsonObject("Subject")?.getLong("Id") ?: return@forEach + val name = grade.getString("Grade") ?: return@forEach + val value = grade.getFloat("GradeValue") ?: 0f + + val categoryId = grade.getJsonObject("Category")?.getLong("Id") ?: return@forEach + + val category = data.gradeCategories.singleOrNull { + it.categoryId == categoryId && it.type == GradeCategory.TYPE_POINT + } + + val addedDate = Date.fromIso(grade.getString("AddDate") ?: return@forEach) + + val gradeObject = Grade( + profileId = profileId, + id = id, + name = name, + type = TYPE_POINT_AVG, + value = value, + weight = category?.weight ?: 0f, + color = category?.color ?: -1, + category = category?.text ?: "", + description = null, + comment = null, + semester = semester, + teacherId = teacherId, + subjectId = subjectId, + addedDate = addedDate + ).apply { + valueMax = category?.valueTo ?: 0f + } + + data.gradeList.add(gradeObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_GRADE, + id, + profile.empty, + profile.empty + )) + } + + data.toRemove.add(DataRemoveModel.Grades.semesterWithType(profile.currentSemester, TYPE_POINT_AVG)) + + data.setSyncNext(ENDPOINT_LIBRUS_API_POINT_GRADES, SYNC_ALWAYS) + onSuccess(ENDPOINT_LIBRUS_API_POINT_GRADES) + } + } ?: onSuccess(ENDPOINT_LIBRUS_API_POINT_GRADES) } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiPtMeetings.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiPtMeetings.kt new file mode 100644 index 00000000..170c6135 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiPtMeetings.kt @@ -0,0 +1,72 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-24. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_PT_MEETINGS +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time + +class LibrusApiPtMeetings(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiPtMeetings" + } + + init { + apiGet(TAG, "ParentTeacherConferences") { json -> + val ptMeetings = json.getJsonArray("ParentTeacherConferences")?.asJsonObjectList() + + ptMeetings?.forEach { meeting -> + val id = meeting.getLong("Id") ?: return@forEach + val topic = meeting.getString("Topic") ?: "" + val teacherId = meeting.getJsonObject("Teacher")?.getLong("Id") ?: -1 + val eventDate = meeting.getString("Date")?.let { Date.fromY_m_d(it) } ?: return@forEach + val startTime = meeting.getString("Time")?.let { + if (it == "00:00:00") + null + else + Time.fromH_m_s(it) + } + + val eventObject = Event( + profileId = profileId, + id = id, + date = eventDate, + time = startTime, + topic = topic, + color = null, + type = Event.TYPE_PT_MEETING, + teacherId = teacherId, + subjectId = -1, + teamId = data.teamClass?.id ?: -1 + ) + + data.eventList.add(eventObject) + data.metadataList.add( + Metadata( + profileId, + Metadata.TYPE_EVENT, + id, + profile?.empty ?: false, + profile?.empty ?: false + )) + } + + data.toRemove.add(DataRemoveModel.Events.futureWithType(Event.TYPE_PT_MEETING)) + + data.setSyncNext(ENDPOINT_LIBRUS_API_PT_MEETINGS, 12* HOUR) + onSuccess(ENDPOINT_LIBRUS_API_PT_MEETINGS) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiPushConfig.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiPushConfig.kt new file mode 100644 index 00000000..5dac1841 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiPushConfig.kt @@ -0,0 +1,47 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-2-21. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_PUSH_CONFIG +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.JsonObject +import pl.szczodrzynski.edziennik.ext.getInt +import pl.szczodrzynski.edziennik.ext.getJsonObject + +class LibrusApiPushConfig(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiPushConfig" + } + + init { data.app.config.sync.tokenLibrus?.also { tokenLibrus -> + if(tokenLibrus.isEmpty()) { + data.setSyncNext(ENDPOINT_LIBRUS_API_PUSH_CONFIG, SYNC_ALWAYS) + data.app.config.sync.tokenLibrusList = + data.app.config.sync.tokenLibrusList + profileId + onSuccess(ENDPOINT_LIBRUS_API_PUSH_CONFIG) + return@also + } + + apiGet(TAG, "ChangeRegister", payload = JsonObject( + "provider" to "FCM", + "device" to tokenLibrus, + "sendPush" to "1", + "appVersion" to 4 + )) { json -> + json.getJsonObject("ChangeRegister")?.getInt("Id")?.let { data.pushDeviceId = it } + + // sync always: this endpoint has .shouldSync set + data.setSyncNext(ENDPOINT_LIBRUS_API_PUSH_CONFIG, SYNC_ALWAYS) + data.app.config.sync.tokenLibrusList = + data.app.config.sync.tokenLibrusList + profileId + onSuccess(ENDPOINT_LIBRUS_API_PUSH_CONFIG) + } + } ?: onSuccess(ENDPOINT_LIBRUS_API_PUSH_CONFIG) } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiSchools.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiSchools.kt new file mode 100644 index 00000000..e42ab949 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiSchools.kt @@ -0,0 +1,57 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-4. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_SCHOOLS +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.LessonRange +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.models.Time +import java.util.* + +class LibrusApiSchools(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiSchools" + } + + init { + apiGet(TAG, "Schools") { json -> + val school = json.getJsonObject("School") + val schoolId = school?.getInt("Id") + val schoolNameLong = school?.getString("Name") + + // create the school's short name using first letters of each long name's word + // append the town name and save to student data + val schoolNameShort = schoolNameLong?.firstLettersName + val schoolTown = school?.getString("Town")?.lowercase() + data.schoolName = schoolId.toString() + schoolNameShort + "_" + schoolTown + + school?.getJsonArray("LessonsRange")?.let { ranges -> + data.lessonRanges.clear() + ranges.forEachIndexed { index, rangeEl -> + val range = rangeEl.asJsonObject + val from = range.getString("From") ?: return@forEachIndexed + val to = range.getString("To") ?: return@forEachIndexed + data.lessonRanges.put( + index, + LessonRange( + profileId, + index, + Time.fromH_m(from), + Time.fromH_m(to) + )) + } + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_SCHOOLS, 4 * DAY) + onSuccess(ENDPOINT_LIBRUS_API_SCHOOLS) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiSubjects.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiSubjects.kt new file mode 100644 index 00000000..17e30559 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiSubjects.kt @@ -0,0 +1,40 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-23. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_SUBJECTS +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.Subject +import pl.szczodrzynski.edziennik.ext.* + +class LibrusApiSubjects(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiSubjects" + } + + init { + apiGet(TAG, "Subjects") { json -> + val subjects = json.getJsonArray("Subjects")?.asJsonObjectList() + + subjects?.forEach { subject -> + val id = subject.getLong("Id") ?: return@forEach + val longName = subject.getString("Name") ?: "" + val shortName = subject.getString("Short") ?: "" + + data.subjectList.put(id, Subject(profileId, id, longName, shortName)) + } + + data.subjectList.put(1, Subject(profileId, 1, "Zachowanie", "zach")) + + data.setSyncNext(ENDPOINT_LIBRUS_API_SUBJECTS, 4* DAY) + onSuccess(ENDPOINT_LIBRUS_API_SUBJECTS) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTeacherFreeDays.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTeacherFreeDays.kt new file mode 100644 index 00000000..09ed5416 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTeacherFreeDays.kt @@ -0,0 +1,70 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-10-4. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import androidx.core.util.isEmpty +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_AGENDA +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_TEACHER_FREE_DAYS +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.TeacherAbsence +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time + +class LibrusApiTeacherFreeDays(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiTeacherFreeDays" + } + + init { + if (data.teacherAbsenceTypes.isEmpty()) { + data.db.teacherAbsenceTypeDao().getAllNow(profileId).toSparseArray(data.teacherAbsenceTypes) { it.id } + } + + apiGet(TAG, "TeacherFreeDays") { json -> + val teacherAbsences = json.getJsonArray("TeacherFreeDays")?.asJsonObjectList() + + teacherAbsences?.forEach { teacherAbsence -> + val id = teacherAbsence.getLong("Id") ?: return@forEach + val teacherId = teacherAbsence.getJsonObject("Teacher")?.getLong("Id") + ?: return@forEach + val dateFrom = Date.fromY_m_d(teacherAbsence.getString("DateFrom")) + val dateTo = Date.fromY_m_d(teacherAbsence.getString("DateTo")) + val timeFrom = teacherAbsence.getString("TimeFrom")?.let { Time.fromH_m_s(it) } + val timeTo = teacherAbsence.getString("TimeTo")?.let { Time.fromH_m_s(it) } + + val teacherAbsenceObject = TeacherAbsence( + profileId = profileId, + id = id, + type = -1L, + name = null, + dateFrom = dateFrom, + dateTo = dateTo, + timeFrom = timeFrom, + timeTo = timeTo, + teacherId = teacherId + ) + + data.teacherAbsenceList.add(teacherAbsenceObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_TEACHER_ABSENCE, + id, + true, + profile?.empty ?: false + )) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_TEACHER_FREE_DAYS, 6* HOUR, DRAWER_ITEM_AGENDA) + onSuccess(ENDPOINT_LIBRUS_API_TEACHER_FREE_DAYS) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTemplate.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTemplate.kt new file mode 100644 index 00000000..9fd6afee --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTemplate.kt @@ -0,0 +1,25 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-4. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi + +class LibrusApiTemplate(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApi" + } + + init { + /*apiGet(TAG, "") { json -> + + data.setSyncNext(ENDPOINT_LIBRUS_API_, SYNC_ALWAYS) + onSuccess(ENDPOINT_LIBRUS_API_) + }*/ + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTextGradeCategories.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTextGradeCategories.kt new file mode 100644 index 00000000..441e3b60 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTextGradeCategories.kt @@ -0,0 +1,48 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-29 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import android.graphics.Color +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_TEXT_GRADE_CATEGORIES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.GradeCategory +import pl.szczodrzynski.edziennik.ext.* + +class LibrusApiTextGradeCategories(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiTextGradeCategories" + } + + init { + apiGet(TAG, "TextGrades/Categories") { json -> + json.getJsonArray("Categories")?.asJsonObjectList()?.forEach { category -> + val id = category.getLong("Id") ?: return@forEach + val name = category.getString("Name") ?: "" + val color = category.getJsonObject("Color")?.getInt("Id") + ?.let { data.getColor(it) } ?: Color.BLUE + + val gradeCategoryObject = GradeCategory( + profileId, + id, + -1f, + color, + name + ).apply { + type = GradeCategory.TYPE_TEXT + } + + data.gradeCategories.put(id, gradeCategoryObject) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_TEXT_GRADE_CATEGORIES, 1 * DAY) + onSuccess(ENDPOINT_LIBRUS_API_TEXT_GRADE_CATEGORIES) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTextGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTextGrades.kt new file mode 100644 index 00000000..bb19f11f --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTextGrades.kt @@ -0,0 +1,84 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-29 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_TEXT_GRADES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Grade +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_DESCRIPTIVE +import pl.szczodrzynski.edziennik.data.db.entity.GradeCategory +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.models.Date + +class LibrusApiTextGrades(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiTextGrades" + } + + init { data.profile?.also { profile -> + apiGet(TAG, "DescriptiveGrades") { json -> + + json.getJsonArray("Grades")?.asJsonObjectList()?.forEach { grade -> + val id = grade.getLong("Id") ?: return@forEach + val teacherId = grade.getJsonObject("AddedBy")?.getLong("Id") ?: return@forEach + val semester = grade.getInt("Semester") ?: return@forEach + val subjectId = grade.getJsonObject("Subject")?.getLong("Id") ?: return@forEach + + val map = grade.getString("Map") + val realValue = grade.getString("RealGradeValue") + + val name = map ?: realValue ?: return@forEach + val description = if (map != null && map != realValue) realValue ?: "" else "" + + val categoryId = grade.getJsonObject("Skill")?.getLong("Id") ?: return@forEach + + val category = data.gradeCategories.singleOrNull { + it.categoryId == categoryId && it.type == GradeCategory.TYPE_DESCRIPTIVE + } + + val addedDate = Date.fromIso(grade.getString("AddDate") ?: return@forEach) + + val gradeObject = Grade( + profileId = profileId, + id = id, + name = name, + type = TYPE_DESCRIPTIVE, + value = 0f, + weight = 0f, + color = category?.color ?: -1, + category = category?.text ?: "", + description = description, + comment = grade.getString("Phrase") /* whatever it is */, + semester = semester, + teacherId = teacherId, + subjectId = subjectId, + addedDate = addedDate + ) + + data.gradeList.add(gradeObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_GRADE, + id, + profile.empty, + profile.empty + )) + } + + data.toRemove.add(DataRemoveModel.Grades.semesterWithType(profile.currentSemester, TYPE_DESCRIPTIVE)) + + data.setSyncNext(ENDPOINT_LIBRUS_API_TEXT_GRADES, SYNC_ALWAYS) + onSuccess(ENDPOINT_LIBRUS_API_TEXT_GRADES) + } + } ?: onSuccess(ENDPOINT_LIBRUS_API_TEXT_GRADES) } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTimetables.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTimetables.kt new file mode 100644 index 00000000..b224a381 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTimetables.kt @@ -0,0 +1,207 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-11-10. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import androidx.core.util.isEmpty +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_TIMETABLES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Lesson +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.Utils.d +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time +import pl.szczodrzynski.edziennik.utils.models.Week + +class LibrusApiTimetables(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiTimetables" + } + + init { + if (data.classrooms.isEmpty()) { + data.db.classroomDao().getAllNow(profileId).toSparseArray(data.classrooms) { it.id } + } + + val currentWeekStart = Week.getWeekStart() + + if (Date.getToday().weekDay > 4) { + currentWeekStart.stepForward(0, 0, 7) + } + + val getDate = data.arguments?.getString("weekStart") ?: currentWeekStart.stringY_m_d + + val weekStart = Date.fromY_m_d(getDate) + val weekEnd = weekStart.clone().stepForward(0, 0, 6) + + apiGet(TAG, "Timetables?weekStart=${weekStart.stringY_m_d}") { json -> + val days = json.getJsonObject("Timetable") + + days?.entrySet()?.forEach { (dateString, dayEl) -> + val day = dayEl?.asJsonArray + + val lessonDate = dateString?.let { Date.fromY_m_d(it) } ?: return@forEach + + var lessonsFound = false + day?.forEach { lessonRangeEl -> + val lessonRange = lessonRangeEl?.asJsonArray?.asJsonObjectList() + if (lessonRange?.isNullOrEmpty() == false) + lessonsFound = true + lessonRange?.forEach { lesson -> + parseLesson(lessonDate, lesson) + } + } + + if (day.isNullOrEmpty() || !lessonsFound) { + data.lessonList.add(Lesson(profileId, lessonDate.value.toLong()).apply { + type = Lesson.TYPE_NO_LESSONS + date = lessonDate + }) + } + } + + d(TAG, "Clearing lessons between ${weekStart.stringY_m_d} and ${weekEnd.stringY_m_d} - timetable downloaded for $getDate") + + if (data.timetableNotPublic) data.timetableNotPublic = false + + data.toRemove.add(DataRemoveModel.Timetable.between(weekStart, weekEnd)) + data.setSyncNext(ENDPOINT_LIBRUS_API_TIMETABLES, SYNC_ALWAYS) + onSuccess(ENDPOINT_LIBRUS_API_TIMETABLES) + } + } + + private fun parseLesson(lessonDate: Date, lesson: JsonObject) { data.profile?.also { profile -> + val isSubstitution = lesson.getBoolean("IsSubstitutionClass") ?: false + val isCancelled = lesson.getBoolean("IsCanceled") ?: false + + val lessonNo = lesson.getInt("LessonNo") ?: return + val startTime = lesson.getString("HourFrom")?.let { Time.fromH_m(it) } ?: return + val endTime = lesson.getString("HourTo")?.let { Time.fromH_m(it) } ?: return + val subjectId = lesson.getJsonObject("Subject")?.getLong("Id") + val teacherId = lesson.getJsonObject("Teacher")?.getLong("Id") + val classroomId = lesson.getJsonObject("Classroom")?.getLong("Id") ?: -1 + val virtualClassId = lesson.getJsonObject("VirtualClass")?.getLong("Id") + val teamId = lesson.getJsonObject("Class")?.getLong("Id") ?: virtualClassId + + val lessonObject = Lesson(profileId, -1) + + if (isSubstitution && isCancelled) { + // shifted lesson - source + val newDate = lesson.getString("NewDate")?.let { Date.fromY_m_d(it) } ?: return + val newLessonNo = lesson.getInt("NewLessonNo") ?: return + val newStartTime = lesson.getString("NewHourFrom")?.let { Time.fromH_m(it) } ?: return + val newEndTime = lesson.getString("NewHourTo")?.let { Time.fromH_m(it) } ?: return + val newSubjectId = lesson.getJsonObject("NewSubject")?.getLong("Id") + val newTeacherId = lesson.getJsonObject("NewTeacher")?.getLong("Id") + val newClassroomId = lesson.getJsonObject("NewClassroom")?.getLong("Id") ?: -1 + val newVirtualClassId = lesson.getJsonObject("NewVirtualClass")?.getLong("Id") + val newTeamId = lesson.getJsonObject("NewClass")?.getLong("Id") ?: newVirtualClassId + + lessonObject.let { + it.type = Lesson.TYPE_SHIFTED_SOURCE + it.oldDate = lessonDate + it.oldLessonNumber = lessonNo + it.oldStartTime = startTime + it.oldEndTime = endTime + it.oldSubjectId = subjectId + it.oldTeacherId = teacherId + it.oldTeamId = teamId + it.oldClassroom = data.classrooms[classroomId]?.name + + it.date = newDate + it.lessonNumber = newLessonNo + it.startTime = newStartTime + it.endTime = newEndTime + it.subjectId = newSubjectId + it.teacherId = newTeacherId + it.teamId = newTeamId + it.classroom = data.classrooms[newClassroomId]?.name + } + } + else if (isSubstitution) { + // lesson change OR shifted lesson - target + val oldDate = lesson.getString("OrgDate")?.let { Date.fromY_m_d(it) } ?: return + val oldLessonNo = lesson.getInt("OrgLessonNo") ?: return + val oldStartTime = lesson.getString("OrgHourFrom")?.let { Time.fromH_m(it) } ?: return + val oldEndTime = lesson.getString("OrgHourTo")?.let { Time.fromH_m(it) } ?: return + val oldSubjectId = lesson.getJsonObject("OrgSubject")?.getLong("Id") + val oldTeacherId = lesson.getJsonObject("OrgTeacher")?.getLong("Id") + val oldClassroomId = lesson.getJsonObject("OrgClassroom")?.getLong("Id") ?: -1 + val oldVirtualClassId = lesson.getJsonObject("OrgVirtualClass")?.getLong("Id") + val oldTeamId = lesson.getJsonObject("OrgClass")?.getLong("Id") ?: oldVirtualClassId + + lessonObject.let { + it.type = if (lessonDate == oldDate && lessonNo == oldLessonNo) Lesson.TYPE_CHANGE else Lesson.TYPE_SHIFTED_TARGET + it.oldDate = oldDate + it.oldLessonNumber = oldLessonNo + it.oldStartTime = oldStartTime + it.oldEndTime = oldEndTime + it.oldSubjectId = oldSubjectId + it.oldTeacherId = oldTeacherId + it.oldTeamId = oldTeamId + it.oldClassroom = data.classrooms[oldClassroomId]?.name + + it.date = lessonDate + it.lessonNumber = lessonNo + it.startTime = startTime + it.endTime = endTime + it.subjectId = subjectId + it.teacherId = teacherId + it.teamId = teamId + it.classroom = data.classrooms[classroomId]?.name + } + } + else if (isCancelled) { + lessonObject.let { + it.type = Lesson.TYPE_CANCELLED + it.oldDate = lessonDate + it.oldLessonNumber = lessonNo + it.oldStartTime = startTime + it.oldEndTime = endTime + it.oldSubjectId = subjectId + it.oldTeacherId = teacherId + it.oldTeamId = teamId + it.oldClassroom = data.classrooms[classroomId]?.name + } + } + else { + lessonObject.let { + it.type = Lesson.TYPE_NORMAL + it.date = lessonDate + it.lessonNumber = lessonNo + it.startTime = startTime + it.endTime = endTime + it.subjectId = subjectId + it.teacherId = teacherId + it.teamId = teamId + it.classroom = data.classrooms[classroomId]?.name + } + } + + lessonObject.id = lessonObject.buildId() + + val seen = profile.empty || lessonDate < Date.getToday() + + if (lessonObject.type != Lesson.TYPE_NORMAL) { + data.metadataList.add( + Metadata( + profileId, + Metadata.TYPE_LESSON_CHANGE, + lessonObject.id, + seen, + seen + )) + } + data.lessonList.add(lessonObject) + }} +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiUnits.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiUnits.kt new file mode 100644 index 00000000..03fcf4a5 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiUnits.kt @@ -0,0 +1,47 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-23. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_UNITS +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.ext.* + +class LibrusApiUnits(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiUnits" + } + + init { run { + if (data.unitId == 0L) { + data.setSyncNext(ENDPOINT_LIBRUS_API_UNITS, 12 * DAY) + onSuccess(ENDPOINT_LIBRUS_API_UNITS) + return@run + } + + apiGet(TAG, "Units") { json -> + val units = json.getJsonArray("Units")?.asJsonObjectList() + + units?.singleOrNull { it.getLong("Id") == data.unitId }?.also { unit -> + val startPoints = unit.getJsonObject("BehaviourGradesSettings")?.getJsonObject("StartPoints") + startPoints?.apply { + data.startPointsSemester1 = getInt("Semester1", defaultValue = 0) + data.startPointsSemester2 = getInt("Semester2", defaultValue = data.startPointsSemester1) + } + unit.getJsonObject("GradesSettings")?.apply { + data.enablePointGrades = getBoolean("PointGradesEnabled", true) + data.enableDescriptiveGrades = getBoolean("DescriptiveGradesEnabled", true) + } + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_UNITS, 7 * DAY) + onSuccess(ENDPOINT_LIBRUS_API_UNITS) + } + }} +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiUsers.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiUsers.kt new file mode 100644 index 00000000..fb82849f --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiUsers.kt @@ -0,0 +1,45 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-23. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_USERS +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.ext.* + +class LibrusApiUsers(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiUsers" + } + + init { + apiGet(TAG, "Users") { json -> + val users = json.getJsonArray("Users")?.asJsonObjectList() + + users?.forEach { user -> + val id = user.getLong("Id") ?: return@forEach + val firstName = user.getString("FirstName")?.fixName() ?: "" + val lastName = user.getString("LastName")?.fixName() ?: "" + + val teacher = Teacher(profileId, id, firstName, lastName) + + if (user.getBoolean("IsSchoolAdministrator") == true) + teacher.setTeacherType(Teacher.TYPE_SCHOOL_ADMIN) + if (user.getBoolean("IsPedagogue") == true) + teacher.setTeacherType(Teacher.TYPE_PEDAGOGUE) + + data.teacherList.put(id, teacher) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_USERS, 4* DAY) + onSuccess(ENDPOINT_LIBRUS_API_USERS) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiVirtualClasses.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiVirtualClasses.kt new file mode 100644 index 00000000..2d6a7958 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiVirtualClasses.kt @@ -0,0 +1,39 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-23. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_VIRTUAL_CLASSES +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.db.entity.Team +import pl.szczodrzynski.edziennik.ext.* + +class LibrusApiVirtualClasses(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusApi(data, lastSync) { + companion object { + const val TAG = "LibrusApiVirtualClasses" + } + + init { + apiGet(TAG, "VirtualClasses") { json -> + val virtualClasses = json.getJsonArray("VirtualClasses")?.asJsonObjectList() + + virtualClasses?.forEach { virtualClass -> + val id = virtualClass.getLong("Id") ?: return@forEach + val name = virtualClass.getString("Name") ?: "" + val teacherId = virtualClass.getJsonObject("Teacher")?.getLong("Id") ?: -1 + val code = "${data.schoolName}:$name" + + data.teamList.put(id, Team(profileId, id, name, 2, code, teacherId)) + } + + data.setSyncNext(ENDPOINT_LIBRUS_API_VIRTUAL_CLASSES, 4* DAY) + onSuccess(ENDPOINT_LIBRUS_API_VIRTUAL_CLASSES) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesGetAttachment.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesGetAttachment.kt new file mode 100644 index 00000000..b54e704b --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesGetAttachment.kt @@ -0,0 +1,41 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-11-24 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusMessages +import pl.szczodrzynski.edziennik.data.db.entity.Message +import kotlin.coroutines.CoroutineContext + +class LibrusMessagesGetAttachment(override val data: DataLibrus, + val message: Message, + val attachmentId: Long, + val attachmentName: String, + val onSuccess: () -> Unit +) : LibrusMessages(data, null), CoroutineScope { + companion object { + const val TAG = "LibrusMessagesGetAttachment" + } + + private var job = Job() + + override val coroutineContext: CoroutineContext + get() = job + Dispatchers.Default + + init { + messagesGet(TAG, "GetFileDownloadLink", parameters = mapOf( + "fileId" to attachmentId, + "msgId" to message.id, + "archive" to 0 + )) { doc -> + val downloadLink = doc.select("response GetFileDownloadLink downloadLink").text() + + LibrusSandboxDownloadAttachment(data, downloadLink, message, attachmentId, attachmentName, onSuccess) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesGetList.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesGetList.kt new file mode 100644 index 00000000..7d0cfeef --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesGetList.kt @@ -0,0 +1,139 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-10-24 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages + +import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_MESSAGES +import pl.szczodrzynski.edziennik.data.api.ERROR_NOT_IMPLEMENTED +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_MESSAGES_RECEIVED +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_MESSAGES_SENT +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusMessages +import pl.szczodrzynski.edziennik.data.db.entity.* +import pl.szczodrzynski.edziennik.data.db.entity.Message.Companion.TYPE_RECEIVED +import pl.szczodrzynski.edziennik.ext.DAY +import pl.szczodrzynski.edziennik.ext.fixName +import pl.szczodrzynski.edziennik.ext.singleOrNull +import pl.szczodrzynski.edziennik.utils.Utils +import pl.szczodrzynski.edziennik.utils.models.Date + +class LibrusMessagesGetList(override val data: DataLibrus, + override val lastSync: Long?, + private val type: Int = TYPE_RECEIVED, + archived: Boolean = false, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusMessages(data, lastSync) { + companion object { + const val TAG = "LibrusMessagesGetList" + } + + init { + val endpoint = when (type) { + TYPE_RECEIVED -> "Inbox/action/GetList" + Message.TYPE_SENT -> "Outbox/action/GetList" + else -> null + } + val endpointId = when (type) { + TYPE_RECEIVED -> ENDPOINT_LIBRUS_MESSAGES_RECEIVED + else -> ENDPOINT_LIBRUS_MESSAGES_SENT + } + + if (endpoint != null) { + messagesGet(TAG, endpoint, parameters = mapOf( + "archive" to if (archived) 1 else 0 + )) { doc -> + doc.select("GetList data").firstOrNull()?.children()?.forEach { element -> + val id = element.select("messageId").text().toLong() + val subject = element.select("topic").text().trim() + val readDateText = element.select("readDate").text().trim() + val readDate = when (readDateText.isNotBlank()) { + true -> Date.fromIso(readDateText) + else -> 0 + } + val sentDate = Date.fromIso(element.select("sendDate").text().trim()) + + val recipientFirstName = element.select(when (type) { + TYPE_RECEIVED -> "senderFirstName" + else -> "receiverFirstName" + }).text().fixName() + + val recipientLastName = element.select(when (type) { + TYPE_RECEIVED -> "senderLastName" + else -> "receiverLastName" + }).text().fixName() + + val recipientId = data.teacherList.singleOrNull { + it.name == recipientFirstName && it.surname == recipientLastName + }?.id ?: { + val teacherObject = Teacher( + profileId, + -1 * Utils.crc16("$recipientFirstName $recipientLastName".toByteArray()).toLong(), + recipientFirstName, + recipientLastName + ) + data.teacherList.put(teacherObject.id, teacherObject) + teacherObject.id + }.invoke() + + val senderId = when (type) { + TYPE_RECEIVED -> recipientId + else -> null + } + + val receiverId = when (type) { + TYPE_RECEIVED -> -1 + else -> recipientId + } + + val notified = when (type) { + Message.TYPE_SENT -> true + else -> readDate > 0 || profile?.empty ?: false + } + + val messageObject = Message( + profileId = profileId, + id = id, + type = type, + subject = subject, + body = null, + senderId = senderId, + addedDate = sentDate + ) + + val messageRecipientObject = MessageRecipient( + profileId, + receiverId, + -1, + readDate, + id + ) + + element.select("isAnyFileAttached").text()?.let { + if (it == "1") + messageObject.hasAttachments = true + } + + data.messageList.add(messageObject) + data.messageRecipientList.add(messageRecipientObject) + data.setSeenMetadataList.add(Metadata( + profileId, + Metadata.TYPE_MESSAGE, + id, + notified, + notified + )) + } + + when (type) { + TYPE_RECEIVED -> data.setSyncNext(ENDPOINT_LIBRUS_MESSAGES_RECEIVED, SYNC_ALWAYS) + Message.TYPE_SENT -> data.setSyncNext(ENDPOINT_LIBRUS_MESSAGES_SENT, DAY, DRAWER_ITEM_MESSAGES) + } + onSuccess(endpointId) + } + } else { + data.error(TAG, ERROR_NOT_IMPLEMENTED) + onSuccess(endpointId) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesGetMessage.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesGetMessage.kt new file mode 100644 index 00000000..8e6435c6 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesGetMessage.kt @@ -0,0 +1,167 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-11-11 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages + +import android.util.Base64 +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusMessages +import pl.szczodrzynski.edziennik.data.api.events.MessageGetEvent +import pl.szczodrzynski.edziennik.data.db.entity.Message.Companion.TYPE_RECEIVED +import pl.szczodrzynski.edziennik.data.db.entity.Message.Companion.TYPE_SENT +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.data.db.full.MessageFull +import pl.szczodrzynski.edziennik.data.db.full.MessageRecipientFull +import pl.szczodrzynski.edziennik.ext.fixName +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty +import pl.szczodrzynski.edziennik.ext.notEmptyOrNull +import pl.szczodrzynski.edziennik.ext.singleOrNull +import pl.szczodrzynski.edziennik.utils.models.Date +import java.nio.charset.Charset + +class LibrusMessagesGetMessage(override val data: DataLibrus, + private val messageObject: MessageFull, + val onSuccess: () -> Unit +) : LibrusMessages(data, null) { + companion object { + const val TAG = "LibrusMessagesGetMessage" + } + + init { data.profile?.also { profile -> + messagesGet(TAG, "GetMessage", parameters = mapOf( + "messageId" to messageObject.id, + "archive" to 0 + )) { doc -> + val message = doc.select("response GetMessage data").first() ?: return@messagesGet + + val body = Base64.decode(message.select("Message").text(), Base64.DEFAULT) + .toString(Charset.defaultCharset()) + .replace("\n", "
    ") + .replace("", "") + + messageObject.apply { + this.body = body + + clearAttachments() + message.select("attachments ArrayItem").forEach { + val attachmentId = it.select("id").text().toLong() + val attachmentName = it.select("filename").text() + addAttachment(attachmentId, attachmentName, -1) + } + } + + val messageRecipientList = mutableListOf() + + when (messageObject.type) { + TYPE_RECEIVED -> { + val senderLoginId = message.select("senderId").text().notEmptyOrNull() + val senderGroupId = message.select("senderGroupId").text().toIntOrNull() + val userClass = message.select("userClass").text().notEmptyOrNull() + data.teacherList.singleOrNull { it.id == messageObject.senderId }?.apply { + loginId = senderLoginId + setTeacherType(when (senderGroupId) { + /* https://api.librus.pl/2.0/Messages/Role */ + 0, 1, 99 -> Teacher.TYPE_SUPER_ADMIN + 2 -> Teacher.TYPE_SCHOOL_ADMIN + 3 -> Teacher.TYPE_PRINCIPAL + 4 -> Teacher.TYPE_TEACHER + 5, 9 -> { + if (typeDescription == null) + typeDescription = userClass + Teacher.TYPE_PARENT + } + 7 -> Teacher.TYPE_SECRETARIAT + 8 -> { + if (typeDescription == null) + typeDescription = userClass + Teacher.TYPE_STUDENT + } + 10 -> Teacher.TYPE_PEDAGOGUE + 11 -> Teacher.TYPE_LIBRARIAN + 12 -> Teacher.TYPE_SPECIALIST + 21 -> { + typeDescription = "Jednostka Nadrzędna" + Teacher.TYPE_OTHER + } + 50 -> { + typeDescription = "Jednostka Samorządu Terytorialnego" + Teacher.TYPE_OTHER + } + else -> Teacher.TYPE_OTHER + }) + } + + val readDateText = message.select("readDate").text() + val readDate = when (readDateText.isNotNullNorEmpty()) { + true -> Date.fromIso(readDateText) + else -> 0 + } + + val messageRecipientObject = MessageRecipientFull( + profileId = profileId, + id = -1, + messageId = messageObject.id, + readDate = readDate + ) + + messageRecipientObject.fullName = profile.accountName ?: profile.studentNameLong + + messageRecipientList.add(messageRecipientObject) + } + + TYPE_SENT -> { + + message.select("receivers ArrayItem").forEach { receiver -> + val receiverFirstName = receiver.select("firstName").text().fixName() + val receiverLastName = receiver.select("lastName").text().fixName() + val receiverLoginId = receiver.select("receiverId").text() + + val teacher = data.teacherList.singleOrNull { it.name == receiverFirstName && it.surname == receiverLastName } + val receiverId = teacher?.id ?: -1 + teacher?.loginId = receiverLoginId + + val readDateText = message.select("readed").text() + val readDate = when (readDateText.isNotNullNorEmpty()) { + true -> Date.fromIso(readDateText) + else -> 0 + } + + val messageRecipientObject = MessageRecipientFull( + profileId = profileId, + id = receiverId, + messageId = messageObject.id, + readDate = readDate + ) + + messageRecipientObject.fullName = "$receiverFirstName $receiverLastName" + + messageRecipientList.add(messageRecipientObject) + } + } + } + + if (!messageObject.seen) { + data.setSeenMetadataList.add(Metadata( + messageObject.profileId, + Metadata.TYPE_MESSAGE, + messageObject.id, + true, + true + )) + } + + messageObject.recipients = messageRecipientList + data.messageRecipientList.addAll(messageRecipientList) + + data.messageList.add(messageObject) + data.messageListReplace = true + + EventBus.getDefault().postSticky(MessageGetEvent(messageObject)) + onSuccess() + } + } ?: onSuccess()} +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesGetRecipientList.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesGetRecipientList.kt new file mode 100644 index 00000000..b6881f17 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesGetRecipientList.kt @@ -0,0 +1,176 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-12-31. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages + +import androidx.core.util.set +import androidx.room.OnConflictStrategy +import com.google.gson.JsonArray +import com.google.gson.JsonObject +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusMessages +import pl.szczodrzynski.edziennik.data.api.events.RecipientListGetEvent +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.ext.* + +class LibrusMessagesGetRecipientList(override val data: DataLibrus, + val onSuccess: () -> Unit +) : LibrusMessages(data, null) { + companion object { + private const val TAG = "LibrusMessagesGetRecipientList" + } + + private val listTypes = mutableListOf>() + + init { + messagesGet(TAG, "Receivers/action/GetTypes", parameters = mapOf( + "includeClass" to 1 + )) { doc -> + doc.select("response GetTypes data list ArrayItem").forEach { + val id = it.getElementsByTag("id").firstOrNull()?.ownText() ?: return@forEach + val name = it.getElementsByTag("name").firstOrNull()?.ownText() ?: return@forEach + listTypes += id to name + } + + getLists() + } + } + + private fun getLists() { + if (listTypes.isEmpty()) { + finish() + return + } + val type = listTypes.removeAt(0) + if (type.first == "contactsGroups") { + getLists() + return + } + messagesGetJson(TAG, "Receivers/action/GetListForType", parameters = mapOf( + "receiverType" to type.first + )) { json -> + val dataEl = json?.getJsonObject("response")?.getJsonObject("GetListForType")?.get("data") + if (dataEl is JsonObject) { + val listEl = dataEl.get("ArrayItem") + if (listEl is JsonArray) { + listEl.asJsonObjectList().forEach { item -> + processElement(item, type.first, type.second) + } + } + if (listEl is JsonObject) { + processElement(listEl, type.first, type.second) + } + } + + getLists() + } + } + + private fun processElement(element: JsonObject, typeId: String, typeName: String, listName: String? = null) { + val listEl = element.getJsonObject("list")?.get("ArrayItem") + if (listEl is JsonArray) { + listEl.asJsonObjectList().let { list -> + val label = element.getString("label") ?: "" + list.forEach { item -> + processElement(item, typeId, typeName, label) + } + return + } + } + if (listEl is JsonObject) { + val label = element.getString("label") ?: "" + processElement(listEl, typeId, typeName, label) + return + } + processRecipient(element, typeId, typeName, listName) + } + + private fun processRecipient(recipient: JsonObject, typeId: String, typeName: String, listName: String? = null) { + val id = recipient.getLong("id") ?: return + val label = recipient.getString("label") ?: return + + val fullNameLastFirst: String + val description: String? + if (typeId == "parentsCouncil" || typeId == "schoolParentsCouncil") { + val delimiterIndex = label.lastIndexOf(" - ") + if (delimiterIndex == -1) { + fullNameLastFirst = label.fixName() + description = null + } + else { + fullNameLastFirst = label.substring(0, delimiterIndex).fixName() + description = label.substring(delimiterIndex+3) + } + } + else { + fullNameLastFirst = label.fixName() + description = null + } + + var typeDescription: String? = null + val type = when (typeId) { + "tutors" -> Teacher.TYPE_EDUCATOR + "teachers" -> Teacher.TYPE_TEACHER + "classParents" -> Teacher.TYPE_PARENT + "guardians" -> Teacher.TYPE_PARENT + "parentsCouncil" -> { + typeDescription = joinNotNullStrings(": ", listName, description) + Teacher.TYPE_PARENTS_COUNCIL + } + "schoolParentsCouncil" -> { + typeDescription = joinNotNullStrings(": ", listName, description) + Teacher.TYPE_SCHOOL_PARENTS_COUNCIL + } + "pedagogue" -> Teacher.TYPE_PEDAGOGUE + "librarian" -> Teacher.TYPE_LIBRARIAN + "admin" -> Teacher.TYPE_SCHOOL_ADMIN + "secretary" -> Teacher.TYPE_SECRETARIAT + "sadmin" -> Teacher.TYPE_SUPER_ADMIN + else -> { + typeDescription = typeName + Teacher.TYPE_OTHER + } + } + + // get teacher by fullName AND type or create it + val teacher = data.teacherList.singleOrNull { + it.fullNameLastFirst == fullNameLastFirst && ((type != Teacher.TYPE_SCHOOL_ADMIN && type != Teacher.TYPE_PEDAGOGUE) || it.isType(type)) + } ?: Teacher(data.profileId, id).apply { + if (typeId == "sadmin" && id == 2L) { + name = "Pomoc" + surname = "Techniczna LIBRUS" + } + else { + name = fullNameLastFirst + fullNameLastFirst.splitName()?.let { + name = it.second + surname = it.first + } + } + data.teacherList[id] = this + } + + teacher.apply { + this.loginId = id.toString() + this.setTeacherType(type) + if (this.typeDescription.isNullOrBlank()) + this.typeDescription = typeDescription + } + } + + private fun finish() { + val event = RecipientListGetEvent( + data.profileId, + data.teacherList.filter { it.loginId != null } + ) + + profile?.lastReceiversSync = System.currentTimeMillis() + + data.teacherOnConflictStrategy = OnConflictStrategy.REPLACE + EventBus.getDefault().postSticky(event) + onSuccess() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesSendMessage.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesSendMessage.kt new file mode 100644 index 00000000..02248e99 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesSendMessage.kt @@ -0,0 +1,59 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-1-2. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages + +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusMessages +import pl.szczodrzynski.edziennik.data.api.events.MessageSentEvent +import pl.szczodrzynski.edziennik.data.db.entity.Message +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.ext.base64Encode +import pl.szczodrzynski.edziennik.ext.getJsonObject +import pl.szczodrzynski.edziennik.ext.getLong +import pl.szczodrzynski.edziennik.ext.getString + +class LibrusMessagesSendMessage(override val data: DataLibrus, + val recipients: List, + val subject: String, + val text: String, + val onSuccess: () -> Unit +) : LibrusMessages(data, null) { + companion object { + const val TAG = "LibrusMessages" + } + + init { + val params = mapOf( + "topic" to subject.base64Encode(), + "message" to text.base64Encode(), + "receivers" to recipients + .filter { it.loginId != null } + .joinToString(",") { it.loginId ?: "" }, + "actions" to "".base64Encode() + ) + + messagesGetJson(TAG, "SendMessage", parameters = params) { json -> + + val response = json.getJsonObject("response").getJsonObject("SendMessage") + val id = response.getLong("data") + + if (response.getString("status") != "ok" || id == null) { + // val message = response.getString("message") + // TODO error + return@messagesGetJson + } + + LibrusMessagesGetList(data, type = Message.TYPE_SENT, lastSync = null) { + val message = data.messageList.firstOrNull { it.isSent && it.id == id } + // val metadata = data.metadataList.firstOrNull { it.thingType == Metadata.TYPE_MESSAGE && it.thingId == message?.id } + val event = MessageSentEvent(data.profileId, message, message?.addedDate) + + EventBus.getDefault().postSticky(event) + onSuccess() + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesTemplate.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesTemplate.kt new file mode 100644 index 00000000..6115e136 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusMessagesTemplate.kt @@ -0,0 +1,24 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-10-25 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages + +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusMessages + +class LibrusMessagesTemplate(override val data: DataLibrus, + val onSuccess: () -> Unit +) : LibrusMessages(data, null) { + companion object { + const val TAG = "LibrusMessages" + } + + init { + /* messagesGet(TAG, "") { doc -> + + data.setSyncNext(ENDPOINT_LIBRUS_MESSAGES_, SYNC_ALWAYS) + onSuccess() + } */ + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusSandboxDownloadAttachment.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusSandboxDownloadAttachment.kt new file mode 100644 index 00000000..c58c185f --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/messages/LibrusSandboxDownloadAttachment.kt @@ -0,0 +1,117 @@ +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages + +import kotlinx.coroutines.* +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusMessages +import pl.szczodrzynski.edziennik.data.api.events.AttachmentGetEvent +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.utils.Utils +import java.io.File +import kotlin.coroutines.CoroutineContext + +class LibrusSandboxDownloadAttachment(override val data: DataLibrus, + downloadLink: String, + val owner: Any, + val attachmentId: Long, + val attachmentName: String, + val onSuccess: () -> Unit +) : LibrusMessages(data, null), CoroutineScope { + companion object { + const val TAG = "LibrusSandboxDownloadAttachment" + } + + private var job = Job() + + override val coroutineContext: CoroutineContext + get() = job + Dispatchers.Default + + private var getAttachmentCheckKeyTries = 0 + + init { + val keyMatcher = Regexes.LIBRUS_ATTACHMENT_KEY.find(downloadLink) + + when { + downloadLink.contains("CSDownloadFailed") -> { + data.error(ApiError(TAG, ERROR_LIBRUS_MESSAGES_ATTACHMENT_NOT_FOUND)) + onSuccess() + } + keyMatcher != null -> { + getAttachmentCheckKeyTries = 0 + + val attachmentKey = keyMatcher[1] + getAttachmentCheckKey(attachmentKey) { + downloadAttachment("${LIBRUS_SANDBOX_URL}CSDownload&singleUseKey=$attachmentKey", method = POST) + } + } + else -> { + downloadAttachment("$downloadLink/get", method = GET) + } + } + } + + private fun getAttachmentCheckKey(attachmentKey: String, callback: () -> Unit) { + sandboxGet(TAG, "CSCheckKey", + parameters = mapOf("singleUseKey" to attachmentKey)) { json -> + + when (json.getString("status")) { + "not_downloaded_yet" -> { + if (getAttachmentCheckKeyTries++ > 5) { + data.error(ApiError(TAG, ERROR_FILE_DOWNLOAD) + .withApiResponse(json)) + return@sandboxGet + } + launch { + delay(2000) + getAttachmentCheckKey(attachmentKey, callback) + } + } + + "ready" -> { + launch { callback() } + } + + else -> { + data.error(ApiError(TAG, EXCEPTION_LIBRUS_MESSAGES_REQUEST) + .withApiResponse(json)) + } + } + } + } + + private fun downloadAttachment(url: String, method: Int = GET) { + val targetFile = File(Utils.getStorageDir(), attachmentName) + + sandboxGetFile(TAG, url, targetFile, { file -> + + val event = AttachmentGetEvent( + profileId, + owner, + attachmentId, + AttachmentGetEvent.TYPE_FINISHED, + file.absolutePath + ) + + val attachmentDataFile = File(Utils.getStorageDir(), ".${profileId}_${event.ownerId}_${event.attachmentId}") + Utils.writeStringToFile(attachmentDataFile, event.fileName) + + EventBus.getDefault().postSticky(event) + + onSuccess() + + }) { written, _ -> + val event = AttachmentGetEvent( + profileId, + owner, + attachmentId, + AttachmentGetEvent.TYPE_PROGRESS, + bytesWritten = written + ) + + EventBus.getDefault().postSticky(event) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaGetAttachment.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaGetAttachment.kt new file mode 100644 index 00000000..6b1f2eba --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaGetAttachment.kt @@ -0,0 +1,24 @@ +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.synergia + +import pl.szczodrzynski.edziennik.data.api.LIBRUS_SYNERGIA_MESSAGES_ATTACHMENT_URL +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusSynergia +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages.LibrusSandboxDownloadAttachment +import pl.szczodrzynski.edziennik.data.db.entity.Message + +class LibrusSynergiaGetAttachment(override val data: DataLibrus, + val message: Message, + val attachmentId: Long, + val attachmentName: String, + val onSuccess: () -> Unit +) : LibrusSynergia(data, null) { + companion object { + const val TAG = "LibrusSynergiaGetAttachment" + } + + init { + redirectUrlGet(TAG, "$LIBRUS_SYNERGIA_MESSAGES_ATTACHMENT_URL/${message.id}/$attachmentId") { url -> + LibrusSandboxDownloadAttachment(data, url, message, attachmentId, attachmentName, onSuccess) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaGetHomework.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaGetHomework.kt new file mode 100644 index 00000000..4ba502f0 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaGetHomework.kt @@ -0,0 +1,52 @@ +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.synergia + +import org.greenrobot.eventbus.EventBus +import org.jsoup.Jsoup +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusSynergia +import pl.szczodrzynski.edziennik.data.api.events.EventGetEvent +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.utils.html.BetterHtml + +class LibrusSynergiaGetHomework(override val data: DataLibrus, + val event: EventFull, + val onSuccess: () -> Unit +) : LibrusSynergia(data, null) { + companion object { + const val TAG = "LibrusSynergiaGetHomework" + } + + init { + synergiaGet(TAG, "moje_zadania/podglad/${event.id}") { text -> + val doc = Jsoup.parse(text) + + val table = doc.select("table.decorated tbody > tr") + + event.topic = table[1].select("td")[1].text() + event.homeworkBody = BetterHtml.fromHtml( + context = null, + html = table[5].select("td")[1].html(), + ).toString() + event.isDownloaded = true + + event.attachmentIds = mutableListOf() + event.attachmentNames = mutableListOf() + + if (table.size > 6) { + table[6].select("a").forEach { a -> + val attachmentId = a.attr("href").split('/') + .last().toLongOrNull() ?: return@forEach + val filename = a.text() + event.attachmentIds?.add(attachmentId) + event.attachmentNames?.add(filename) + } + } + + data.eventList.add(event) + data.eventListReplace = true + + EventBus.getDefault().postSticky(EventGetEvent(event)) + onSuccess() + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaGetMessage.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaGetMessage.kt new file mode 100644 index 00000000..b9df2af1 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaGetMessage.kt @@ -0,0 +1,160 @@ +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.synergia + +import org.greenrobot.eventbus.EventBus +import org.jsoup.Jsoup +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusSynergia +import pl.szczodrzynski.edziennik.data.api.events.MessageGetEvent +import pl.szczodrzynski.edziennik.data.db.entity.Message +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.data.db.full.MessageFull +import pl.szczodrzynski.edziennik.data.db.full.MessageRecipientFull +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty +import pl.szczodrzynski.edziennik.ext.singleOrNull +import pl.szczodrzynski.edziennik.ext.swapFirstLastName +import pl.szczodrzynski.edziennik.utils.models.Date + +class LibrusSynergiaGetMessage(override val data: DataLibrus, + private val messageObject: MessageFull, + val onSuccess: () -> Unit) : LibrusSynergia(data, null) { + companion object { + const val TAG = "LibrusSynergiaGetMessage" + } + + init { + val endpoint = when (messageObject.type) { + Message.TYPE_SENT -> "wiadomosci/1/6/${messageObject.id}/f0" + else -> "wiadomosci/1/5/${messageObject.id}/f0" + } + + data.profile?.also { profile -> + synergiaGet(TAG, endpoint) { text -> + val doc = Jsoup.parse(text) + + val messageElement = doc.select(".container-message tr")[0].child(1) + val detailsElement = messageElement.child(1) + val readElement = messageElement.children().last() + + val body = messageElement.select(".container-message-content").html() + + messageObject.apply { + this.body = body + + clearAttachments() + if (messageElement.children().size >= 5) { + messageElement.child(3).select("tr").forEachIndexed { i, attachment -> + if (i == 0) return@forEachIndexed // Skip the header + val filename = attachment.child(0).text().trim() + val attachmentId = "wiadomosci\\\\/pobierz_zalacznik\\\\/[0-9]+?\\\\/([0-9]+)\"".toRegex() + .find(attachment.select("img").attr("onclick"))?.get(1) + ?: return@forEachIndexed + addAttachment(attachmentId.toLong(), filename, -1) + } + } + } + + val messageRecipientList = mutableListOf() + + when (messageObject.type) { + Message.TYPE_RECEIVED -> { + val senderFullName = detailsElement.child(0).select(".left").text() + val senderGroupName = "\\[(.+?)]".toRegex().find(senderFullName)?.get(1)?.trim() + + data.teacherList.singleOrNull { it.id == messageObject.senderId }?.apply { + setTeacherType(when (senderGroupName) { + /* https://api.librus.pl/2.0/Messages/Role */ + "Pomoc techniczna Librus", "SuperAdministrator" -> Teacher.TYPE_SUPER_ADMIN + "Administrator szkoły" -> Teacher.TYPE_SCHOOL_ADMIN + "Dyrektor Szkoły" -> Teacher.TYPE_PRINCIPAL + "Nauczyciel" -> Teacher.TYPE_TEACHER + "Rodzic", "Opiekun" -> Teacher.TYPE_PARENT + "Sekretariat" -> Teacher.TYPE_SECRETARIAT + "Uczeń" -> Teacher.TYPE_STUDENT + "Pedagog/Psycholog szkolny" -> Teacher.TYPE_PEDAGOGUE + "Pracownik biblioteki" -> Teacher.TYPE_LIBRARIAN + "Inny specjalista" -> Teacher.TYPE_SPECIALIST + "Jednostka Nadrzędna" -> { + typeDescription = "Jednostka Nadrzędna" + Teacher.TYPE_OTHER + } + "Jednostka Samorządu Terytorialnego" -> { + typeDescription = "Jednostka Samorządu Terytorialnego" + Teacher.TYPE_OTHER + } + else -> Teacher.TYPE_OTHER + }) + } + + val readDateText = readElement?.select(".left")?.text() + val readDate = when (readDateText.isNotNullNorEmpty()) { + true -> Date.fromIso(readDateText) + else -> 0 + } + + val messageRecipientObject = MessageRecipientFull( + profileId = profileId, + id = -1, + messageId = messageObject.id, + readDate = readDate + ) + + messageRecipientObject.fullName = profile.accountName + ?: profile.studentNameLong + + messageRecipientList.add(messageRecipientObject) + } + + Message.TYPE_SENT -> { + + readElement?.select("tr")?.forEachIndexed { i, receiver -> + if (i == 0) return@forEachIndexed // Skip the header + + val receiverFullName = receiver.child(0).text() + val receiverName = receiverFullName.split('(')[0].swapFirstLastName() + + val teacher = data.teacherList.singleOrNull { it.fullName == receiverName } + val receiverId = teacher?.id ?: -1 + + val readDate = when (val readDateText = receiver.child(1).text().trim()) { + "NIE" -> 0 + else -> Date.fromIso(readDateText) + } + + val messageRecipientObject = MessageRecipientFull( + profileId = profileId, + id = receiverId, + messageId = messageObject.id, + readDate = readDate + ) + + messageRecipientObject.fullName = receiverName + + messageRecipientList.add(messageRecipientObject) + } + } + } + + if (!messageObject.seen) { + data.setSeenMetadataList.add(Metadata( + messageObject.profileId, + Metadata.TYPE_MESSAGE, + messageObject.id, + true, + true + )) + } + + messageObject.recipients = messageRecipientList + data.messageRecipientList.addAll(messageRecipientList) + + data.messageList.add(messageObject) + data.messageListReplace = true + + EventBus.getDefault().postSticky(MessageGetEvent(messageObject)) + onSuccess() + } + } ?: onSuccess() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaGetMessages.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaGetMessages.kt new file mode 100644 index 00000000..01cc69f6 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaGetMessages.kt @@ -0,0 +1,117 @@ +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.synergia + +import org.jsoup.Jsoup +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.ERROR_NOT_IMPLEMENTED +import pl.szczodrzynski.edziennik.data.api.Regexes +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusSynergia +import pl.szczodrzynski.edziennik.data.db.entity.* +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.Utils +import pl.szczodrzynski.edziennik.utils.models.Date + +class LibrusSynergiaGetMessages(override val data: DataLibrus, + override val lastSync: Long?, + private val type: Int = Message.TYPE_RECEIVED, + archived: Boolean = false, + val onSuccess: (Int) -> Unit) : LibrusSynergia(data, lastSync) { + companion object { + const val TAG = "LibrusSynergiaGetMessages" + } + + init { + val endpoint = when (type) { + Message.TYPE_RECEIVED -> "wiadomosci/5" + Message.TYPE_SENT -> "wiadomosci/6" + else -> null + } + val endpointId = when (type) { + Message.TYPE_RECEIVED -> ENDPOINT_LIBRUS_SYNERGIA_MESSAGES_RECEIVED + else -> ENDPOINT_LIBRUS_SYNERGIA_MESSAGES_SENT + } + + if (endpoint != null) { + synergiaGet(TAG, endpoint) { text -> + val doc = Jsoup.parse(text) + + fun getRecipientId(name: String): Long = data.teacherList.singleOrNull { + it.fullNameLastFirst == name + }?.id ?: run { + val teacherObject = Teacher( + profileId, + -1 * Utils.crc16(name.swapFirstLastName().toByteArray()).toLong(), + name.splitName()?.second!!, + name.splitName()?.first!! + ) + data.teacherList.put(teacherObject.id, teacherObject) + teacherObject.id + } + + doc.select(".decorated.stretch tbody > tr").forEach { messageElement -> + val url = messageElement.select("a").first()?.attr("href") ?: return@forEach + val id = Regexes.LIBRUS_MESSAGE_ID.find(url)?.get(1)?.toLong() ?: return@forEach + val subject = messageElement.child(3).text() + val sentDate = Date.fromIso(messageElement.child(4).text()) + val recipientName = messageElement.child(2).text().split('(')[0].fixName() + val recipientId = getRecipientId(recipientName) + val read = messageElement.child(2).attr("style").isNullOrBlank() + + val senderId = when (type) { + Message.TYPE_RECEIVED -> recipientId + else -> null + } + + val receiverId = when (type) { + Message.TYPE_RECEIVED -> -1 + else -> recipientId + } + + val notified = when (type) { + Message.TYPE_SENT -> true + else -> read || profile?.empty ?: false + } + + val messageObject = Message( + profileId = profileId, + id = id, + type = type, + subject = subject, + body = null, + senderId = senderId, + addedDate = sentDate + ) + + val messageRecipientObject = MessageRecipient( + profileId, + receiverId, + -1, + if (read) 1 else 0, + id + ) + + messageObject.hasAttachments = !messageElement.child(1).select("img").isEmpty() + + data.messageList.add(messageObject) + data.messageRecipientList.add(messageRecipientObject) + data.setSeenMetadataList.add(Metadata( + profileId, + Metadata.TYPE_MESSAGE, + id, + notified, + notified + )) + } + + when (type) { + Message.TYPE_RECEIVED -> data.setSyncNext(ENDPOINT_LIBRUS_MESSAGES_RECEIVED, SYNC_ALWAYS) + Message.TYPE_SENT -> data.setSyncNext(ENDPOINT_LIBRUS_MESSAGES_SENT, DAY, MainActivity.DRAWER_ITEM_MESSAGES) + } + onSuccess(endpointId) + } + } else { + data.error(TAG, ERROR_NOT_IMPLEMENTED) + onSuccess(endpointId) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaHomework.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaHomework.kt new file mode 100644 index 00000000..ddf6635c --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaHomework.kt @@ -0,0 +1,102 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-10-22. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.synergia + +import org.jsoup.Jsoup +import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_HOMEWORK +import pl.szczodrzynski.edziennik.data.api.POST +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_SYNERGIA_HOMEWORK +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusSynergia +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.ext.HOUR +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.ext.singleOrNull +import pl.szczodrzynski.edziennik.utils.models.Date + +class LibrusSynergiaHomework(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusSynergia(data, lastSync) { + companion object { + const val TAG = "LibrusSynergiaHomework" + } + + init { data.profile?.also { profile -> + synergiaGet(TAG, "moje_zadania", method = POST, parameters = mapOf( + "dataOd" to + if (profile.empty) + profile.getSemesterStart(1).stringY_m_d + else + Date.getToday().stringY_m_d, + "dataDo" to Date.getToday().stepForward(0, 0, 7).stringY_m_d, + "przedmiot" to -1 + + )) { text -> + val doc = Jsoup.parse(text) + + doc.select("table.myHomeworkTable > tbody").firstOrNull()?.also { homeworkTable -> + val homeworkElements = homeworkTable.children() + + homeworkElements.forEach { el -> + val elements = el.children() + + val subjectName = elements[0].text().trim() + val subjectId = data.subjectList.singleOrNull { it.longName == subjectName }?.id + ?: -1 + val teacherName = elements[1].text().trim() + val teacherId = data.teacherList.singleOrNull { teacherName == it.fullName }?.id + ?: -1 + val topic = elements[2].text().trim() + val addedDate = Date.fromY_m_d(elements[4].text().trim()) + val eventDate = Date.fromY_m_d(elements[6].text().trim()) + val id = "/podglad/([0-9]+)'".toRegex().find( + elements[9].select("input").attr("onclick") + )?.get(1)?.toLong() ?: return@forEach + + val lessons = data.db.timetableDao().getAllForDateNow(profileId, eventDate) + val startTime = lessons.firstOrNull { it.subjectId == subjectId }?.startTime + + val seen = when (profile.empty) { + true -> true + else -> eventDate < Date.getToday() + } + + val eventObject = Event( + profileId = profileId, + id = id, + date = eventDate, + time = startTime, + topic = topic, + color = null, + type = Event.TYPE_HOMEWORK, + teacherId = teacherId, + subjectId = subjectId, + teamId = data.teamClass?.id ?: -1, + addedDate = addedDate.inMillis + ) + eventObject.isDownloaded = false + + data.eventList.add(eventObject) + data.metadataList.add(Metadata( + profileId, + Metadata.TYPE_HOMEWORK, + id, + seen, + seen + )) + } + } + + data.toRemove.add(DataRemoveModel.Events.futureWithType(Event.TYPE_HOMEWORK)) + + // because this requires a synergia login (2 more requests!!!) sync this every few hours or if explicit :D + data.setSyncNext(ENDPOINT_LIBRUS_SYNERGIA_HOMEWORK, 5 * HOUR, DRAWER_ITEM_HOMEWORK) + onSuccess(ENDPOINT_LIBRUS_SYNERGIA_HOMEWORK) + } + } ?: onSuccess(ENDPOINT_LIBRUS_SYNERGIA_HOMEWORK) } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaHomeworkGetAttachment.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaHomeworkGetAttachment.kt new file mode 100644 index 00000000..a6d4b94b --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaHomeworkGetAttachment.kt @@ -0,0 +1,25 @@ +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.synergia + +import pl.szczodrzynski.edziennik.data.api.LIBRUS_SYNERGIA_HOMEWORK_ATTACHMENT_URL +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusSynergia +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages.LibrusSandboxDownloadAttachment +import pl.szczodrzynski.edziennik.data.db.full.EventFull + +class LibrusSynergiaHomeworkGetAttachment( + override val data: DataLibrus, + val event: EventFull, + val attachmentId: Long, + val attachmentName: String, + val onSuccess: () -> Unit +) : LibrusSynergia(data, null) { + companion object { + const val TAG = "LibrusSynergiaHomeworkGetAttachment" + } + + init { + redirectUrlGet(TAG, "$LIBRUS_SYNERGIA_HOMEWORK_ATTACHMENT_URL/$attachmentId") { url -> + LibrusSandboxDownloadAttachment(data, url, event, attachmentId, attachmentName, onSuccess) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaInfo.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaInfo.kt new file mode 100644 index 00000000..74458fb5 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaInfo.kt @@ -0,0 +1,37 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-10-23 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.synergia + +import org.jsoup.Jsoup +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_SYNERGIA_INFO +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusSynergia +import pl.szczodrzynski.edziennik.ext.MONTH + +class LibrusSynergiaInfo(override val data: DataLibrus, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : LibrusSynergia(data, lastSync) { + companion object { + const val TAG = "LibrusSynergiaInfo" + } + + init { + synergiaGet(TAG, "informacja") { text -> + val doc = Jsoup.parse(text) + + doc.select("table.form tbody").firstOrNull()?.children()?.also { info -> + val studentNumber = info[2].select("td").text().trim().toIntOrNull() + + studentNumber?.also { + data.profile?.studentNumber = it + } + } + + data.setSyncNext(ENDPOINT_LIBRUS_SYNERGIA_INFO, MONTH) + onSuccess(ENDPOINT_LIBRUS_SYNERGIA_INFO) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaMarkAllAnnouncementsAsRead.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaMarkAllAnnouncementsAsRead.kt new file mode 100644 index 00000000..04a7f5b6 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaMarkAllAnnouncementsAsRead.kt @@ -0,0 +1,24 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-10-26 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.synergia + +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusSynergia +import pl.szczodrzynski.edziennik.data.db.entity.Metadata + +class LibrusSynergiaMarkAllAnnouncementsAsRead(override val data: DataLibrus, + val onSuccess: () -> Unit +) : LibrusSynergia(data, null) { + companion object { + const val TAG = "LibrusSynergiaMarkAllAnnouncementsAsRead" + } + + init { + synergiaGet(TAG, "ogloszenia") { + data.app.db.metadataDao().setAllSeen(profileId, Metadata.TYPE_ANNOUNCEMENT, true) + onSuccess() + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaTemplate.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaTemplate.kt new file mode 100644 index 00000000..ddfb4457 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/synergia/LibrusSynergiaTemplate.kt @@ -0,0 +1,25 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-10-23 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.synergia + +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusSynergia + +class LibrusSynergiaTemplate(override val data: DataLibrus, + val onSuccess: () -> Unit +) : LibrusSynergia(data, null) { + companion object { + const val TAG = "LibrusSynergia" + } + + init { + /* synergiaGet(TAG, "") { text -> + val doc = Jsoup.parse(text) + + data.setSyncNext(ENDPOINT_LIBRUS_SYNERGIA_, SYNC_ALWAYS) + onSuccess() + } */ + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/firstlogin/LibrusFirstLogin.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/firstlogin/LibrusFirstLogin.kt new file mode 100644 index 00000000..43e5bda9 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/firstlogin/LibrusFirstLogin.kt @@ -0,0 +1,134 @@ +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.firstlogin + +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusPortal +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.login.LibrusLoginApi +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.login.LibrusLoginPortal +import pl.szczodrzynski.edziennik.data.api.events.FirstLoginFinishedEvent +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.* + +class LibrusFirstLogin(val data: DataLibrus, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "LibrusFirstLogin" + } + + private val portal = LibrusPortal(data) + private val api = LibrusApi(data, null) + private val profileList = mutableListOf() + + init { + val loginStoreId = data.loginStore.id + val loginStoreType = LOGIN_TYPE_LIBRUS + var firstProfileId = loginStoreId + + if (data.loginStore.mode == LOGIN_MODE_LIBRUS_EMAIL) { + // email login: use Portal for account list + LibrusLoginPortal(data) { + portal.portalGet(TAG, if (data.fakeLogin) FAKE_LIBRUS_ACCOUNTS else LIBRUS_ACCOUNTS_URL) { json, response -> + val accounts = json.getJsonArray("accounts") + + if (accounts == null || accounts.size() < 1) { + EventBus.getDefault().postSticky(FirstLoginFinishedEvent(listOf(), data.loginStore)) + onSuccess() + return@portalGet + } + val accountDataTime = json.getLong("lastModification") + + for (accountEl in accounts) { + val account = accountEl.asJsonObject + + val state = account.getString("state") + when (state) { + "requiring_an_action" -> ERROR_LIBRUS_PORTAL_SYNERGIA_DISCONNECTED + "need-activation" -> ERROR_LOGIN_LIBRUS_PORTAL_NOT_ACTIVATED + else -> null + }?.let { errorCode -> + data.error(ApiError(TAG, errorCode) + .withApiResponse(json) + .withResponse(response)) + return@portalGet + } + + val isParent = account.getString("group") == "parent" + + val id = account.getInt("id") ?: continue + val login = account.getString("login") ?: continue + val token = account.getString("accessToken") ?: continue + val tokenTime = (accountDataTime ?: 0) + DAY + val studentNameLong = account.getString("studentName").fixName() + val studentNameShort = studentNameLong.getShortName() + + val profile = Profile( + firstProfileId++, + loginStoreId, + loginStoreType, + studentNameLong, + data.portalEmail, + studentNameLong, + studentNameShort, + if (isParent) studentNameLong else null /* temporarily - there is no parent name provided, only the type */ + ).apply { + studentData["accountId"] = id + studentData["accountLogin"] = login + studentData["accountToken"] = token + studentData["accountTokenTime"] = tokenTime + } + profileList.add(profile) + } + + EventBus.getDefault().postSticky(FirstLoginFinishedEvent(profileList, data.loginStore)) + onSuccess() + } + } + } + else { + // synergia or JST login: use Api for account info + LibrusLoginApi(data) { + api.apiGet(TAG, "Me") { json -> + + val me = json.getJsonObject("Me") + val account = me?.getJsonObject("Account") + val user = me?.getJsonObject("User") + + val login = account.getString("Login") + val isParent = account?.getInt("GroupId") in 5..6 + + val studentNameLong = buildFullName(user?.getString("FirstName"), user?.getString("LastName")) + val studentNameShort = studentNameLong.getShortName() + val accountNameLong = if (isParent) + buildFullName(account?.getString("FirstName"), account?.getString("LastName")) + else null + + val profile = Profile( + firstProfileId++, + loginStoreId, + loginStoreType, + studentNameLong, + login, + studentNameLong, + studentNameShort, + accountNameLong + ).apply { + studentData["isPremium"] = account?.getBoolean("IsPremium") == true || account?.getBoolean("IsPremiumDemo") == true + studentData["accountId"] = account.getInt("Id") ?: 0 + studentData["accountLogin"] = data.apiLogin ?: login + studentData["accountPassword"] = data.apiPassword + studentData["accountToken"] = data.apiAccessToken + studentData["accountTokenTime"] = data.apiTokenExpiryTime + studentData["accountRefreshToken"] = data.apiRefreshToken + } + profileList.add(profile) + + EventBus.getDefault().postSticky(FirstLoginFinishedEvent(profileList, data.loginStore)) + onSuccess() + } + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/LibrusLogin.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/LibrusLogin.kt new file mode 100644 index 00000000..c79acd2e --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/LibrusLogin.kt @@ -0,0 +1,69 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.login + +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_LIBRUS_API +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_LIBRUS_MESSAGES +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_LIBRUS_PORTAL +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_LIBRUS_SYNERGIA +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.utils.Utils + +class LibrusLogin(val data: DataLibrus, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "LibrusLogin" + } + + private var cancelled = false + + init { + nextLoginMethod(onSuccess) + } + + private fun nextLoginMethod(onSuccess: () -> Unit) { + if (data.targetLoginMethodIds.isEmpty()) { + onSuccess() + return + } + if (cancelled) { + onSuccess() + return + } + useLoginMethod(data.targetLoginMethodIds.removeAt(0)) { usedMethodId -> + data.progress(data.progressStep) + if (usedMethodId != -1) + data.loginMethods.add(usedMethodId) + nextLoginMethod(onSuccess) + } + } + + private fun useLoginMethod(loginMethodId: Int, onSuccess: (usedMethodId: Int) -> Unit) { + // this should never be true + if (data.loginMethods.contains(loginMethodId)) { + onSuccess(-1) + return + } + Utils.d(TAG, "Using login method $loginMethodId") + when (loginMethodId) { + LOGIN_METHOD_LIBRUS_PORTAL -> { + data.startProgress(R.string.edziennik_progress_login_librus_portal) + LibrusLoginPortal(data) { onSuccess(loginMethodId) } + } + LOGIN_METHOD_LIBRUS_API -> { + data.startProgress(R.string.edziennik_progress_login_librus_api) + LibrusLoginApi(data) { onSuccess(loginMethodId) } + } + LOGIN_METHOD_LIBRUS_SYNERGIA -> { + data.startProgress(R.string.edziennik_progress_login_librus_synergia) + LibrusLoginSynergia(data) { onSuccess(loginMethodId) } + } + LOGIN_METHOD_LIBRUS_MESSAGES -> { + data.startProgress(R.string.edziennik_progress_login_librus_messages) + LibrusLoginMessages(data) { onSuccess(loginMethodId) } + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/LibrusLoginApi.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/LibrusLoginApi.kt new file mode 100644 index 00000000..58f7181d --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/LibrusLoginApi.kt @@ -0,0 +1,253 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-20. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.login + +import com.google.gson.JsonObject +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.body.MediaTypeUtils +import im.wangchao.mhttp.callback.JsonCallbackHandler +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.getInt +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.ext.getUnixDate +import pl.szczodrzynski.edziennik.utils.Utils.d +import java.net.HttpURLConnection.* + +@Suppress("ConvertSecondaryConstructorToPrimary") +class LibrusLoginApi { + companion object { + private const val TAG = "LoginLibrusApi" + } + + private lateinit var data: DataLibrus + private lateinit var onSuccess: () -> Unit + + /* do NOT move this to primary constructor */ + constructor(data: DataLibrus, onSuccess: () -> Unit) { + this.data = data + this.onSuccess = onSuccess + + if (data.loginStore.mode == LOGIN_MODE_LIBRUS_EMAIL && data.profile == null) { + data.error(ApiError(TAG, ERROR_PROFILE_MISSING)) + return + } + + if (data.isApiLoginValid()) { + onSuccess() + } + else { + when (data.loginStore.mode) { + LOGIN_MODE_LIBRUS_EMAIL -> loginWithPortal() + LOGIN_MODE_LIBRUS_SYNERGIA -> loginWithSynergia() + LOGIN_MODE_LIBRUS_JST -> loginWithJst() + else -> { + data.error(ApiError(TAG, ERROR_INVALID_LOGIN_MODE)) + } + } + } + } + + private fun loginWithPortal() { + if (!data.loginMethods.contains(LOGIN_METHOD_LIBRUS_PORTAL)) { + data.error(ApiError(TAG, ERROR_LOGIN_METHOD_NOT_SATISFIED)) + return + } + SynergiaTokenExtractor(data) { + onSuccess() + } + } + + private fun copyFromLoginStore() { + data.loginStore.data.apply { + if (has("accountLogin")) { + data.apiLogin = getString("accountLogin") + remove("accountLogin") + } + if (has("accountPassword")) { + data.apiPassword = getString("accountPassword") + remove("accountPassword") + } + if (has("accountCode")) { + data.apiCode = getString("accountCode") + remove("accountCode") + } + if (has("accountPin")) { + data.apiPin = getString("accountPin") + remove("accountPin") + } + } + } + + private fun loginWithSynergia() { + copyFromLoginStore() + if (data.apiRefreshToken != null) { + // refresh a Synergia token + synergiaRefreshToken() + } + else if (data.apiLogin != null && data.apiPassword != null) { + synergiaGetToken() + } + else { + // cannot log in: token expired, no login data present + data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) + } + } + + private fun loginWithJst() { + copyFromLoginStore() + + if (data.apiRefreshToken != null) { + // refresh a JST token + jstRefreshToken() + } + else if (data.apiCode != null && data.apiPin != null) { + // get a JST token from Code and PIN + jstGetToken() + } + else { + // cannot log in: token expired, no login data present + data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) + } + } + + private val tokenCallback = object : JsonCallbackHandler() { + override fun onSuccess(json: JsonObject?, response: Response?) { + if (response?.code() == HTTP_UNAVAILABLE) { + data.error(ApiError(TAG, ERROR_LIBRUS_API_MAINTENANCE) + .withApiResponse(json) + .withResponse(response)) + return + } + + if (json == null) { + data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) + .withResponse(response)) + return + } + if (response?.code() != 200) json.getString("error")?.let { error -> + when (error) { + "librus_captcha_needed" -> ERROR_LOGIN_LIBRUS_API_CAPTCHA_NEEDED + "connection_problems" -> ERROR_LOGIN_LIBRUS_API_CONNECTION_PROBLEMS + "invalid_client" -> ERROR_LOGIN_LIBRUS_API_INVALID_CLIENT + "librus_reg_accept_needed" -> ERROR_LOGIN_LIBRUS_API_REG_ACCEPT_NEEDED + "librus_change_password_error" -> ERROR_LOGIN_LIBRUS_API_CHANGE_PASSWORD_ERROR + "librus_password_change_required" -> ERROR_LOGIN_LIBRUS_API_PASSWORD_CHANGE_REQUIRED + "invalid_grant" -> ERROR_LOGIN_LIBRUS_API_INVALID_LOGIN + "invalid_request" -> ERROR_LOGIN_LIBRUS_API_INVALID_REQUEST + else -> ERROR_LOGIN_LIBRUS_API_OTHER + }.let { errorCode -> + data.error(ApiError(TAG, errorCode) + .withApiResponse(json) + .withResponse(response)) + return + } + } + + try { + data.apiAccessToken = json.getString("access_token") + data.apiRefreshToken = json.getString("refresh_token") + data.apiTokenExpiryTime = response.getUnixDate() + json.getInt("expires_in", 86400) + onSuccess() + } catch (e: NullPointerException) { + data.error(ApiError(TAG, EXCEPTION_LOGIN_LIBRUS_API_TOKEN) + .withResponse(response) + .withThrowable(e) + .withApiResponse(json)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(TAG, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + private fun synergiaGetToken() { + d(TAG, "Request: Librus/Login/Api - $LIBRUS_API_TOKEN_URL") + + Request.builder() + .url(LIBRUS_API_TOKEN_URL) + .userAgent(LIBRUS_USER_AGENT) + .addParameter("grant_type", "password") + .addParameter("username", data.apiLogin) + .addParameter("password", data.apiPassword) + .addParameter("librus_long_term_token", "1") + .addParameter("librus_rules_accepted", "1") + .addHeader("Authorization", "Basic $LIBRUS_API_AUTHORIZATION") + .contentType(MediaTypeUtils.APPLICATION_FORM) + .post() + .allowErrorCode(HTTP_BAD_REQUEST) + .allowErrorCode(HTTP_UNAUTHORIZED) + .allowErrorCode(HTTP_UNAVAILABLE) + .callback(tokenCallback) + .build() + .enqueue() + } + private fun synergiaRefreshToken() { + d(TAG, "Request: Librus/Login/Api - $LIBRUS_API_TOKEN_URL") + + Request.builder() + .url(LIBRUS_API_TOKEN_URL) + .userAgent(LIBRUS_USER_AGENT) + .addParameter("grant_type", "refresh_token") + .addParameter("refresh_token", data.apiRefreshToken) + .addParameter("librus_long_term_token", "1") + .addParameter("librus_rules_accepted", "1") + .addHeader("Authorization", "Basic $LIBRUS_API_AUTHORIZATION") + .contentType(MediaTypeUtils.APPLICATION_FORM) + .post() + .allowErrorCode(HTTP_BAD_REQUEST) + .allowErrorCode(HTTP_UNAUTHORIZED) + .callback(tokenCallback) + .build() + .enqueue() + } + private fun jstGetToken() { + d(TAG, "Request: Librus/Login/Api - $LIBRUS_API_TOKEN_JST_URL") + + Request.builder() + .url(LIBRUS_API_TOKEN_JST_URL) + .userAgent(LIBRUS_USER_AGENT) + .addParameter("grant_type", "implicit_grant") + .addParameter("client_id", LIBRUS_API_CLIENT_ID_JST) + .addParameter("secret", LIBRUS_API_SECRET_JST) + .addParameter("code", data.apiCode) + .addParameter("pin", data.apiPin) + .addParameter("librus_rules_accepted", "1") + .addParameter("librus_mobile_rules_accepted", "1") + .addParameter("librus_long_term_token", "1") + .contentType(MediaTypeUtils.APPLICATION_FORM) + .post() + .allowErrorCode(HTTP_BAD_REQUEST) + .allowErrorCode(HTTP_UNAUTHORIZED) + .callback(tokenCallback) + .build() + .enqueue() + } + private fun jstRefreshToken() { + d(TAG, "Request: Librus/Login/Api - $LIBRUS_API_TOKEN_JST_URL") + + Request.builder() + .url(LIBRUS_API_TOKEN_JST_URL) + .userAgent(LIBRUS_USER_AGENT) + .addParameter("grant_type", "refresh_token") + .addParameter("client_id", LIBRUS_API_CLIENT_ID_JST) + .addParameter("refresh_token", data.apiRefreshToken) + .addParameter("librus_long_term_token", "1") + .addParameter("mobile_app_accept_rules", "1") + .addParameter("synergy_accept_rules", "1") + .contentType(MediaTypeUtils.APPLICATION_FORM) + .post() + .allowErrorCode(HTTP_BAD_REQUEST) + .allowErrorCode(HTTP_UNAUTHORIZED) + .callback(tokenCallback) + .build() + .enqueue() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/LibrusLoginMessages.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/LibrusLoginMessages.kt new file mode 100644 index 00000000..2a61f641 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/LibrusLoginMessages.kt @@ -0,0 +1,179 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-20. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.login + +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.body.MediaTypeUtils +import im.wangchao.mhttp.callback.TextCallbackHandler +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.LibrusRecaptchaHelper +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.getUnixDate +import pl.szczodrzynski.edziennik.utils.Utils.d +import java.io.StringWriter +import javax.xml.parsers.DocumentBuilderFactory +import javax.xml.transform.OutputKeys +import javax.xml.transform.TransformerFactory +import javax.xml.transform.dom.DOMSource +import javax.xml.transform.stream.StreamResult + +class LibrusLoginMessages(val data: DataLibrus, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "LoginLibrusMessages" + } + + private val callback by lazy { object : TextCallbackHandler() { + override fun onSuccess(text: String?, response: Response?) { + val location = response?.headers()?.get("Location") + when { + location?.contains("MultiDomainLogon") == true -> loginWithSynergia(location) + location?.contains("AutoLogon") == true -> { + saveSessionId(response, text) + onSuccess() + } + + text?.contains("grecaptcha.ready") == true -> { + val url = response?.request()?.url()?.toString() ?: run { + //data.error(TAG, ERROR_LIBRUS_MESSAGES_OTHER, response, text) + data.messagesLoginSuccessful = false + onSuccess() + return + } + + LibrusRecaptchaHelper(data.app, url, text, onSuccess = { newUrl -> + loginWithSynergia(newUrl) + }, onTimeout = { + //data.error(TAG, ERROR_LOGIN_LIBRUS_MESSAGES_TIMEOUT, response, text) + data.messagesLoginSuccessful = false + onSuccess() + }) + } + + text?.contains("ok") == true -> { + saveSessionId(response, text) + onSuccess() + } + text?.contains("Niepoprawny login i/lub hasło.") == true -> data.error(TAG, ERROR_LOGIN_LIBRUS_MESSAGES_INVALID_LOGIN, response, text) + text?.contains("stop.png") == true -> data.error(TAG, ERROR_LIBRUS_SYNERGIA_ACCESS_DENIED, response, text) + text?.contains("eAccessDeny") == true -> { + // data.error(TAG, ERROR_LIBRUS_MESSAGES_ACCESS_DENIED, response, text) + data.messagesLoginSuccessful = false + onSuccess() + } + text?.contains("OffLine") == true -> data.error(TAG, ERROR_LIBRUS_MESSAGES_MAINTENANCE, response, text) + text?.contains("error") == true -> data.error(TAG, ERROR_LIBRUS_MESSAGES_ERROR, response, text) + text?.contains("eVarWhitThisNameNotExists") == true -> data.error(TAG, ERROR_LIBRUS_MESSAGES_ACCESS_DENIED, response, text) + text?.contains("") == true -> data.error(TAG, ERROR_LIBRUS_MESSAGES_OTHER, response, text) + else -> data.error(TAG, ERROR_LIBRUS_MESSAGES_OTHER, response, text) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(TAG, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + }} + + init { run { + if (data.profile == null) { + data.error(ApiError(TAG, ERROR_PROFILE_MISSING)) + return@run + } + + if (data.isMessagesLoginValid()) { + data.app.cookieJar.set("wiadomosci.librus.pl", "DZIENNIKSID", data.messagesSessionId) + onSuccess() + } + else { + data.app.cookieJar.clear("wiadomosci.librus.pl") + if (data.loginMethods.contains(LOGIN_METHOD_LIBRUS_SYNERGIA)) { + loginWithSynergia() + } + else if (data.apiLogin != null && data.apiPassword != null && false) { + loginWithCredentials() + } + else { + data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) + } + } + }} + + /** + * XML (Flash messages website) login method. Uses a Synergia login and password. + */ + private fun loginWithCredentials() { + d(TAG, "Request: Librus/Login/Messages - $LIBRUS_MESSAGES_URL/Login") + + val docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder() + val doc = docBuilder.newDocument() + val serviceElement = doc.createElement("service") + val headerElement = doc.createElement("header") + val dataElement = doc.createElement("data") + val loginElement = doc.createElement("login") + loginElement.appendChild(doc.createTextNode(data.apiLogin)) + dataElement.appendChild(loginElement) + val passwordElement = doc.createElement("password") + passwordElement.appendChild(doc.createTextNode(data.apiPassword)) + dataElement.appendChild(passwordElement) + val keyStrokeElement = doc.createElement("KeyStroke") + val keysElement = doc.createElement("Keys") + val upElement = doc.createElement("Up") + keysElement.appendChild(upElement) + val downElement = doc.createElement("Down") + keysElement.appendChild(downElement) + keyStrokeElement.appendChild(keysElement) + dataElement.appendChild(keyStrokeElement) + serviceElement.appendChild(headerElement) + serviceElement.appendChild(dataElement) + doc.appendChild(serviceElement) + val transformer = TransformerFactory.newInstance().newTransformer() + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes") + val stringWriter = StringWriter() + transformer.transform(DOMSource(doc), StreamResult(stringWriter)) + val requestXml = stringWriter.toString() + + Request.builder() + .url("$LIBRUS_MESSAGES_URL/Login") + .userAgent(SYNERGIA_USER_AGENT) + .setTextBody(requestXml, MediaTypeUtils.APPLICATION_XML) + .post() + .callback(callback) + .build() + .enqueue() + } + + /** + * A login method using the Synergia website (/wiadomosci2 Auto Login). + */ + private fun loginWithSynergia(url: String = "https://synergia.librus.pl/wiadomosci2") { + d(TAG, "Request: Librus/Login/Messages - $url") + + Request.builder() + .url(url) + .userAgent(SYNERGIA_USER_AGENT) + .get() + .callback(callback) + .withClient(data.app.httpLazy) + .build() + .enqueue() + } + + private fun saveSessionId(response: Response?, text: String?) { + var sessionId = data.app.cookieJar.get("wiadomosci.librus.pl", "DZIENNIKSID") + sessionId = sessionId?.replace("-MAINT", "") // dunno what's this + sessionId = sessionId?.replace("MAINT", "") // dunno what's this + if (sessionId == null) { + data.error(ApiError(TAG, ERROR_LOGIN_LIBRUS_MESSAGES_NO_SESSION_ID) + .withResponse(response) + .withApiResponse(text)) + return + } + data.messagesSessionId = sessionId + data.messagesSessionIdExpiryTime = response.getUnixDate() + 45 * 60 /* 45min */ + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/LibrusLoginPortal.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/LibrusLoginPortal.kt new file mode 100644 index 00000000..ed01d01f --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/LibrusLoginPortal.kt @@ -0,0 +1,262 @@ +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.login + +import android.util.Pair +import com.google.gson.JsonObject +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.body.MediaTypeUtils +import im.wangchao.mhttp.callback.JsonCallbackHandler +import im.wangchao.mhttp.callback.TextCallbackHandler +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.Utils.d +import java.net.HttpURLConnection.* +import java.util.* +import java.util.regex.Pattern + +class LibrusLoginPortal(val data: DataLibrus, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "LoginLibrusPortal" + } + + init { run { + if (data.loginStore.mode != LOGIN_MODE_LIBRUS_EMAIL) { + data.error(ApiError(TAG, ERROR_INVALID_LOGIN_MODE)) + return@run + } + if (data.portalEmail == null || data.portalPassword == null) { + data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) + return@run + } + + // succeed having a non-expired access token and a refresh token + if (data.isPortalLoginValid()) { + onSuccess() + } + else if (data.portalRefreshToken != null) { + if (data.fakeLogin) { + data.app.cookieJar.clear("librus.szkolny.eu") + } + else { + data.app.cookieJar.clear("portal.librus.pl") + } + accessToken(null, data.portalRefreshToken) + } + else { + if (data.fakeLogin) { + data.app.cookieJar.clear("librus.szkolny.eu") + } + else { + data.app.cookieJar.clear("portal.librus.pl") + } + authorize(if (data.fakeLogin) FAKE_LIBRUS_AUTHORIZE else LIBRUS_AUTHORIZE_URL) + } + }} + + private fun authorize(url: String?) { + d(TAG, "Request: Librus/Login/Portal - $url") + + Request.builder() + .url(url) + .userAgent(LIBRUS_USER_AGENT) + .withClient(data.app.httpLazy) + .callback(object : TextCallbackHandler() { + override fun onSuccess(text: String, response: Response) { + val location = response.headers().get("Location") + if (location != null) { + val authMatcher = Pattern.compile("$LIBRUS_REDIRECT_URL\\?code=([A-z0-9]+?)$", Pattern.DOTALL or Pattern.MULTILINE).matcher(location) + when { + authMatcher.find() -> { + accessToken(authMatcher.group(1), null) + } + location.contains("rejected_client") -> { + data.error(ApiError(TAG, ERROR_LOGIN_LIBRUS_PORTAL_INVALID_CLIENT_ID) + .withResponse(response) + .withApiResponse("Location: $location\n$text")) + } + else -> { + authorize(location) + } + } + } else { + val csrfMatcher = Pattern.compile("name=\"csrf-token\" content=\"([A-z0-9=+/\\-_]+?)\"", Pattern.DOTALL).matcher(text) + if (csrfMatcher.find()) { + login(csrfMatcher.group(1) ?: "") + } else { + data.error(ApiError(TAG, ERROR_LOGIN_LIBRUS_PORTAL_CSRF_MISSING) + .withResponse(response) + .withApiResponse(text)) + } + } + } + + override fun onFailure(response: Response, throwable: Throwable) { + data.error(ApiError(TAG, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + }) + .build() + .enqueue() + } + + private fun login(csrfToken: String) { + d(TAG, "Request: Librus/Login/Portal - ${if (data.fakeLogin) FAKE_LIBRUS_LOGIN else LIBRUS_LOGIN_URL}") + + val recaptchaCode = data.arguments?.getString("recaptchaCode") ?: data.loginStore.getLoginData("recaptchaCode", null) + val recaptchaTime = data.arguments?.getLong("recaptchaTime") ?: data.loginStore.getLoginData("recaptchaTime", 0L) + data.loginStore.removeLoginData("recaptchaCode") + data.loginStore.removeLoginData("recaptchaTime") + + Request.builder() + .url(if (data.fakeLogin) FAKE_LIBRUS_LOGIN else LIBRUS_LOGIN_URL) + .userAgent(LIBRUS_USER_AGENT) + .addParameter("email", data.portalEmail) + .addParameter("password", data.portalPassword) + .also { + if (recaptchaCode != null && System.currentTimeMillis() - recaptchaTime < 2*60*1000 /* 2 minutes */) + it.addParameter("g-recaptcha-response", recaptchaCode) + } + .addHeader("X-CSRF-TOKEN", csrfToken) + .allowErrorCode(HTTP_BAD_REQUEST) + .allowErrorCode(HTTP_FORBIDDEN) + .contentType(MediaTypeUtils.APPLICATION_JSON) + .post() + .callback(object : JsonCallbackHandler() { + override fun onSuccess(json: JsonObject?, response: Response) { + val location = response.headers()?.get("Location") + if (location == "$LIBRUS_REDIRECT_URL?command=close") { + data.error(ApiError(TAG, ERROR_LIBRUS_PORTAL_MAINTENANCE) + .withApiResponse(json) + .withResponse(response)) + return + } + + if (json == null) { + if (response.parserErrorBody?.contains("wciąż nieaktywne") == true) { + data.error(ApiError(TAG, ERROR_LOGIN_LIBRUS_PORTAL_NOT_ACTIVATED) + .withResponse(response)) + return + } + data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) + .withResponse(response)) + return + } + val error = if (response.code() == 200) null else + json.getJsonArray("errors")?.getString(0) + ?: json.getJsonObject("errors")?.entrySet()?.firstOrNull()?.value?.asString + error?.let { code -> + when { + code.contains("Sesja logowania wygasła") -> ERROR_LOGIN_LIBRUS_PORTAL_CSRF_EXPIRED + code.contains("Upewnij się, że nie") -> ERROR_LOGIN_LIBRUS_PORTAL_INVALID_LOGIN + // this doesn't work anyway: `errors` is an object with `g-recaptcha-response` set + code.contains("robotem") -> ERROR_CAPTCHA_LIBRUS_PORTAL + code.contains("Podany adres e-mail jest nieprawidłowy.") -> ERROR_LOGIN_LIBRUS_PORTAL_INVALID_LOGIN + else -> ERROR_LOGIN_LIBRUS_PORTAL_ACTION_ERROR + }.let { errorCode -> + data.error(ApiError(TAG, errorCode) + .withApiResponse(json) + .withResponse(response)) + return + } + } + if (json.getBoolean("captchaRequired") == true) { + data.error(ApiError(TAG, ERROR_CAPTCHA_LIBRUS_PORTAL) + .withResponse(response) + .withApiResponse(json)) + return + } + authorize(json.getString("redirect", LIBRUS_AUTHORIZE_URL)) + } + + override fun onFailure(response: Response, throwable: Throwable) { + data.error(ApiError(TAG, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + }) + .build() + .enqueue() + } + + private fun accessToken(code: String?, refreshToken: String?) { + d(TAG, "Request: Librus/Login/Portal - ${if (data.fakeLogin) FAKE_LIBRUS_TOKEN else LIBRUS_TOKEN_URL}") + + val onSuccess = { json: JsonObject, response: Response? -> + data.portalAccessToken = json.getString("access_token") + data.portalRefreshToken = json.getString("refresh_token") + data.portalTokenExpiryTime = response.getUnixDate() + json.getInt("expires_in", 86400) + onSuccess() + } + + val callback = object : JsonCallbackHandler() { + override fun onSuccess(json: JsonObject?, response: Response?) { + if (json == null) { + data.error(TAG, ERROR_RESPONSE_EMPTY, response) + return + } + val error = if (response?.code() == 200) null else + json.getString("hint") ?: json.getString("error") + error?.let { code -> + when (code) { + "Authorization code has expired" -> ERROR_LOGIN_LIBRUS_PORTAL_CODE_EXPIRED + "Authorization code has been revoked" -> ERROR_LOGIN_LIBRUS_PORTAL_CODE_REVOKED + "Cannot decrypt the refresh token" -> ERROR_LOGIN_LIBRUS_PORTAL_REFRESH_INVALID + "Token has been revoked" -> ERROR_LOGIN_LIBRUS_PORTAL_REFRESH_REVOKED + "Check the `client_id` parameter" -> ERROR_LOGIN_LIBRUS_PORTAL_NO_CLIENT_ID + "Check the `code` parameter" -> ERROR_LOGIN_LIBRUS_PORTAL_NO_CODE + "Check the `refresh_token` parameter" -> ERROR_LOGIN_LIBRUS_PORTAL_NO_REFRESH + "Check the `redirect_uri` parameter" -> ERROR_LOGIN_LIBRUS_PORTAL_NO_REDIRECT + "unsupported_grant_type" -> ERROR_LOGIN_LIBRUS_PORTAL_UNSUPPORTED_GRANT + "invalid_client" -> ERROR_LOGIN_LIBRUS_PORTAL_INVALID_CLIENT_ID + else -> ERROR_LOGIN_LIBRUS_PORTAL_OTHER + }.let { errorCode -> + data.error(ApiError(TAG, errorCode) + .withApiResponse(json) + .withResponse(response)) + return + } + } + + try { + onSuccess(json, response) + } catch (e: NullPointerException) { + data.error(ApiError(TAG, EXCEPTION_LOGIN_LIBRUS_PORTAL_TOKEN) + .withResponse(response) + .withThrowable(e) + .withApiResponse(json)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(TAG, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + val params = ArrayList>() + params.add(Pair("client_id", LIBRUS_CLIENT_ID)) + if (code != null) { + params.add(Pair("grant_type", "authorization_code")) + params.add(Pair("code", code)) + params.add(Pair("redirect_uri", LIBRUS_REDIRECT_URL)) + } else if (refreshToken != null) { + params.add(Pair("grant_type", "refresh_token")) + params.add(Pair("refresh_token", refreshToken)) + } + + Request.builder() + .url(if (data.fakeLogin) FAKE_LIBRUS_TOKEN else LIBRUS_TOKEN_URL) + .userAgent(LIBRUS_USER_AGENT) + .addParams(params) + .post() + .allowErrorCode(HTTP_UNAUTHORIZED) + .callback(callback) + .build() + .enqueue() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/LibrusLoginSynergia.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/LibrusLoginSynergia.kt new file mode 100644 index 00000000..a95af893 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/LibrusLoginSynergia.kt @@ -0,0 +1,126 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-20. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.login + +import com.google.gson.JsonObject +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.callback.TextCallbackHandler +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.ext.getUnixDate +import pl.szczodrzynski.edziennik.utils.Utils.d +import java.net.HttpURLConnection + +class LibrusLoginSynergia(override val data: DataLibrus, val onSuccess: () -> Unit) : LibrusApi(data, null) { + companion object { + private const val TAG = "LoginLibrusSynergia" + } + + init { run { + if (data.profile == null) { + data.error(ApiError(TAG, ERROR_PROFILE_MISSING)) + return@run + } + + if (data.isSynergiaLoginValid()) { + data.app.cookieJar.set("synergia.librus.pl", "DZIENNIKSID", data.synergiaSessionId) + onSuccess() + } + else { + data.app.cookieJar.clear("synergia.librus.pl") + if (data.loginMethods.contains(LOGIN_METHOD_LIBRUS_API)) { + loginWithApi() + } + else if (data.apiLogin != null && data.apiPassword != null && false) { + loginWithCredentials() + } + else { + data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) + } + } + }} + + /** + * HTML form-based login method. Uses a Synergia login and password. + */ + private fun loginWithCredentials() { + + } + + /** + * A login method using the Synergia API (AutoLoginToken endpoint). + */ + private fun loginWithApi() { + d(TAG, "Request: Librus/Login/Synergia - $LIBRUS_API_URL/AutoLoginToken") + + val onSuccess = { json: JsonObject -> + loginWithToken(json.getString("Token")) + } + + apiGet(TAG, "AutoLoginToken", POST, onSuccess = onSuccess) + } + + private fun loginWithToken(token: String?) { + if (token == null) { + data.error(ApiError(TAG, ERROR_LOGIN_LIBRUS_SYNERGIA_NO_TOKEN)) + return + } + + d(TAG, "Request: Librus/Login/Synergia - " + LIBRUS_SYNERGIA_TOKEN_LOGIN_URL.replace("TOKEN", token) + "/uczen/widok/centrum_powiadomien") + + val callback = object : TextCallbackHandler() { + override fun onSuccess(json: String?, response: Response?) { + val location = response?.headers()?.get("Location") + if (location?.endsWith("przerwa_techniczna") == true) { + data.error(ApiError(TAG, ERROR_LIBRUS_SYNERGIA_MAINTENANCE) + .withApiResponse(json) + .withResponse(response)) + return + } + + if (location?.endsWith("centrum_powiadomien") == true) { + val sessionId = data.app.cookieJar.get("synergia.librus.pl", "DZIENNIKSID") + if (sessionId == null) { + data.error(ApiError(TAG, ERROR_LOGIN_LIBRUS_SYNERGIA_NO_SESSION_ID) + .withResponse(response) + .withApiResponse(json)) + return + } + data.synergiaSessionId = sessionId + data.synergiaSessionIdExpiryTime = response.getUnixDate() + 45 * 60 /* 45min */ + onSuccess() + } + else { + data.error(ApiError(TAG, ERROR_LOGIN_LIBRUS_SYNERGIA_TOKEN_INVALID) + .withResponse(response) + .withApiResponse(json)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(TAG, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + data.app.cookieJar.clear("synergia.librus.pl") + Request.builder() + .url(LIBRUS_SYNERGIA_TOKEN_LOGIN_URL.replace("TOKEN", token) + "/uczen/widok/centrum_powiadomien") + .userAgent(LIBRUS_USER_AGENT) + .get() + .allowErrorCode(HttpURLConnection.HTTP_BAD_REQUEST) + .allowErrorCode(HttpURLConnection.HTTP_FORBIDDEN) + .allowErrorCode(HttpURLConnection.HTTP_UNAUTHORIZED) + .callback(callback) + .withClient(data.app.httpLazy) + .build() + .enqueue() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/SynergiaTokenExtractor.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/SynergiaTokenExtractor.kt new file mode 100644 index 00000000..807bb131 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/login/SynergiaTokenExtractor.kt @@ -0,0 +1,69 @@ +package pl.szczodrzynski.edziennik.data.api.edziennik.librus.login + +import com.google.gson.JsonObject +import im.wangchao.mhttp.Response +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.DataLibrus +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusPortal +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.Utils.d + +class SynergiaTokenExtractor(override val data: DataLibrus, val onSuccess: () -> Unit) : LibrusPortal(data) { + companion object { + private const val TAG = "SynergiaTokenExtractor" + } + + init { run { + if (data.loginStore.mode != LOGIN_MODE_LIBRUS_EMAIL) { + data.error(ApiError(TAG, ERROR_INVALID_LOGIN_MODE)) + return@run + } + if (data.profile == null) { + data.error(ApiError(TAG, ERROR_PROFILE_MISSING)) + return@run + } + + if (data.apiTokenExpiryTime-30 > currentTimeUnix() && data.apiAccessToken.isNotNullNorEmpty()) { + onSuccess() + } + else { + if (!synergiaAccount()) { + data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) + } + } + }} + + /** + * Get an Api token from the Portal account, using Portal API. + * If necessary, refreshes the token. + */ + private fun synergiaAccount(): Boolean { + + val accountLogin = data.apiLogin ?: return false + data.portalAccessToken ?: return false + + d(TAG, "Request: Librus/SynergiaTokenExtractor - ${if (data.fakeLogin) FAKE_LIBRUS_ACCOUNT else LIBRUS_ACCOUNT_URL}$accountLogin") + + val onSuccess = { json: JsonObject, response: Response? -> + // synergiaAccount is executed when a synergia token needs a refresh + val accountId = json.getInt("id") + val accountToken = json.getString("accessToken") + if (accountId == null || accountToken == null) { + data.error(ApiError(TAG, ERROR_LOGIN_LIBRUS_PORTAL_SYNERGIA_TOKEN_MISSING) + .withResponse(response) + .withApiResponse(json)) + } + else { + data.apiAccessToken = accountToken + data.apiTokenExpiryTime = response.getUnixDate() + 6 * 60 * 60 + + onSuccess() + } + } + + portalGet(TAG, (if (data.fakeLogin) FAKE_LIBRUS_ACCOUNT else LIBRUS_ACCOUNT_URL)+accountLogin, onSuccess = onSuccess) + return true + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/DataMobidziennik.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/DataMobidziennik.kt new file mode 100644 index 00000000..cee3cda5 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/DataMobidziennik.kt @@ -0,0 +1,184 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-6. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik + +import android.util.LongSparseArray +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_MOBIDZIENNIK_WEB +import pl.szczodrzynski.edziennik.data.api.Regexes +import pl.szczodrzynski.edziennik.data.api.models.Data +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.currentTimeUnix +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time + +class DataMobidziennik(app: App, profile: Profile?, loginStore: LoginStore) : Data(app, profile, loginStore) { + + fun isWebLoginValid() = webSessionIdExpiryTime-30 > currentTimeUnix() + && webSessionValue.isNotNullNorEmpty() + && webSessionKey.isNotNullNorEmpty() + && webServerId.isNotNullNorEmpty() + + fun isApi2LoginValid() = loginEmail.isNotNullNorEmpty() + && loginId.isNotNullNorEmpty() + && globalId.isNotNullNorEmpty() + + override fun satisfyLoginMethods() { + loginMethods.clear() + if (isWebLoginValid()) { + loginMethods += LOGIN_METHOD_MOBIDZIENNIK_WEB + } + } + + override fun generateUserCode() = "$loginServerName:$loginUsername:$studentId" + + fun parseDateTime(dateStr: String): Pair { + // pt, 4 lut, 09:11 + val dateParts = dateStr.split(',', ' ').filter { it.isNotEmpty() } + // [pt], [4], [lut], [09:11] + val date = Date.getToday() + date.day = dateParts[1].toIntOrNull() ?: 1 + date.month = when (dateParts[2]) { + "sty" -> 1 + "lut" -> 2 + "mar" -> 3 + "kwi" -> 4 + "maj" -> 5 + "cze" -> 6 + "lip" -> 7 + "sie" -> 8 + "wrz" -> 9 + "paź" -> 10 + "lis" -> 11 + "gru" -> 12 + else -> 1 + } + val time = Time.fromH_m(dateParts[3]) + return date to time + } + + val teachersMap = LongSparseArray() + val subjectsMap = LongSparseArray() + + val gradeAddedDates = sortedMapOf() + val gradeAverages = sortedMapOf() + val gradeColors = sortedMapOf() + + private var mLoginServerName: String? = null + var loginServerName: String? + get() { mLoginServerName = mLoginServerName ?: loginStore.getLoginData("serverName", null); return mLoginServerName } + set(value) { loginStore.putLoginData("serverName", value); mLoginServerName = value } + + private var mLoginUsername: String? = null + var loginUsername: String? + get() { mLoginUsername = mLoginUsername ?: loginStore.getLoginData("username", null); return mLoginUsername } + set(value) { loginStore.putLoginData("username", value); mLoginUsername = value } + + private var mLoginPassword: String? = null + var loginPassword: String? + get() { mLoginPassword = mLoginPassword ?: loginStore.getLoginData("password", null); return mLoginPassword } + set(value) { loginStore.putLoginData("password", value); mLoginPassword = value } + + private var mStudentId: Int? = null + var studentId: Int + get() { mStudentId = mStudentId ?: profile?.getStudentData("studentId", 0); return mStudentId ?: 0 } + set(value) { profile?.putStudentData("studentId", value) ?: return; mStudentId = value } + + /* __ __ _ + \ \ / / | | + \ \ /\ / /__| |__ + \ \/ \/ / _ \ '_ \ + \ /\ / __/ |_) | + \/ \/ \___|_._*/ + private var mWebSessionKey: String? = null + var webSessionKey: String? + get() { mWebSessionKey = mWebSessionKey ?: loginStore.getLoginData("sessionCookie", null); return mWebSessionKey } + set(value) { loginStore.putLoginData("sessionCookie", value); mWebSessionKey = value } + + private var mWebSessionValue: String? = null + var webSessionValue: String? + get() { mWebSessionValue = mWebSessionValue ?: loginStore.getLoginData("sessionID", null); return mWebSessionValue } + set(value) { loginStore.putLoginData("sessionID", value); mWebSessionValue = value } + + private var mWebServerId: String? = null + var webServerId: String? + get() { mWebServerId = mWebServerId ?: loginStore.getLoginData("sessionServer", null); return mWebServerId } + set(value) { loginStore.putLoginData("sessionServer", value); mWebServerId = value } + + private var mWebSessionIdExpiryTime: Long? = null + var webSessionIdExpiryTime: Long + get() { mWebSessionIdExpiryTime = mWebSessionIdExpiryTime ?: loginStore.getLoginData("sessionIDTime", 0L); return mWebSessionIdExpiryTime ?: 0L } + set(value) { loginStore.putLoginData("sessionIDTime", value); mWebSessionIdExpiryTime = value } + + /* _____ _____ ___ + /\ | __ \_ _| |__ \ + / \ | |__) || | ) | + / /\ \ | ___/ | | / / + / ____ \| | _| |_ / /_ + /_/ \_\_| |_____| |___*/ + /** + * A global ID (whatever it is) used in API 2 + * and Firebase push from Mobidziennik. + */ + var globalId: String? + get() { mGlobalId = mGlobalId ?: profile?.getStudentData("globalId", null); return mGlobalId } + set(value) { profile?.putStudentData("globalId", value) ?: return; mGlobalId = value } + private var mGlobalId: String? = null + + /** + * User's email that may or may not + * be retrieved from Web by [MobidziennikWebAccountEmail]. + * Used to log in to API 2. + */ + var loginEmail: String? + get() { mLoginEmail = mLoginEmail ?: profile?.getStudentData("email", null); return mLoginEmail } + set(value) { profile?.putStudentData("email", value); mLoginEmail = value } + private var mLoginEmail: String? = null + + /** + * A login ID used in the API 2. + * Looks more or less like "7063@2019@zslpoznan". + */ + var loginId: String? + get() { mLoginId = mLoginId ?: profile?.getStudentData("loginId", null); return mLoginId } + set(value) { profile?.putStudentData("loginId", value) ?: return; mLoginId = value } + private var mLoginId: String? = null + + /** + * No need to explain. + */ + var ciasteczkoAutoryzacji: String? + get() { mCiasteczkoAutoryzacji = mCiasteczkoAutoryzacji ?: profile?.getStudentData("ciasteczkoAutoryzacji", null); return mCiasteczkoAutoryzacji } + set(value) { profile?.putStudentData("ciasteczkoAutoryzacji", value) ?: return; mCiasteczkoAutoryzacji = value } + private var mCiasteczkoAutoryzacji: String? = null + + + override fun saveData() { + super.saveData() + if (gradeAddedDates.isNotEmpty()) { + app.db.gradeDao().updateDetails(profileId, gradeAverages, gradeAddedDates, gradeColors) + } + } + + val mobiLessons = mutableListOf() + + data class MobiLesson( + var id: Long, + var subjectId: Long, + var teacherId: Long, + var teamId: Long, + var topic: String, + var date: Date, + var startTime: Time, + var endTime: Time, + var presentCount: Int, + var absentCount: Int, + var lessonNumber: Int, + var signed: String + ) +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/Mobidziennik.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/Mobidziennik.kt new file mode 100644 index 00000000..e19fabca --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/Mobidziennik.kt @@ -0,0 +1,169 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.MobidziennikData +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.web.* +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.firstlogin.MobidziennikFirstLogin +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.login.MobidziennikLogin +import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikCallback +import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.data.db.full.AnnouncementFull +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.data.db.full.MessageFull +import pl.szczodrzynski.edziennik.utils.Utils.d + +class Mobidziennik(val app: App, val profile: Profile?, val loginStore: LoginStore, val callback: EdziennikCallback) : EdziennikInterface { + companion object { + private const val TAG = "Mobidziennik" + + const val API_KEY = "szkolny_eu_72c7dbc8b97f1e5dd2d118cacf51c2b8543d15c0f65b7a59979adb0a1296b235d7febb826dd2a28688def6efe0811b924b04d7f3c7b7d005354e06dc56815d57" + } + + val internalErrorList = mutableListOf() + val data: DataMobidziennik + private var afterLogin: (() -> Unit)? = null + + init { + data = DataMobidziennik(app, profile, loginStore).apply { + callback = wrapCallback(this@Mobidziennik.callback) + satisfyLoginMethods() + } + } + + private fun completed() { + data.saveData() + callback.onCompleted() + } + + /* _______ _ _ _ _ _ + |__ __| | /\ | | (_) | | | + | | | |__ ___ / \ | | __ _ ___ _ __ _| |_| |__ _ __ ___ + | | | '_ \ / _ \ / /\ \ | |/ _` |/ _ \| '__| | __| '_ \| '_ ` _ \ + | | | | | | __/ / ____ \| | (_| | (_) | | | | |_| | | | | | | | | + |_| |_| |_|\___| /_/ \_\_|\__, |\___/|_| |_|\__|_| |_|_| |_| |_| + __/ | + |__*/ + override fun sync(featureIds: List, viewId: Int?, onlyEndpoints: List?, arguments: JsonObject?) { + data.arguments = arguments + data.prepare(mobidziennikLoginMethods, MobidziennikFeatures, featureIds, viewId, onlyEndpoints) + login() + } + + private fun login(loginMethodId: Int? = null, afterLogin: (() -> Unit)? = null) { + d(TAG, "Trying to login with ${data.targetLoginMethodIds}") + if (internalErrorList.isNotEmpty()) { + d(TAG, " - Internal errors:") + internalErrorList.forEach { d(TAG, " - code $it") } + } + loginMethodId?.let { data.prepareFor(mobidziennikLoginMethods, it) } + afterLogin?.let { this.afterLogin = it } + MobidziennikLogin(data) { + data() + } + } + + private fun data() { + d(TAG, "Endpoint IDs: ${data.targetEndpointIds}") + if (internalErrorList.isNotEmpty()) { + d(TAG, " - Internal errors:") + internalErrorList.forEach { d(TAG, " - code $it") } + } + afterLogin?.invoke() ?: MobidziennikData(data) { + completed() + } + } + + override fun getMessage(message: MessageFull) { + login(LOGIN_METHOD_MOBIDZIENNIK_WEB) { + MobidziennikWebGetMessage(data, message) { + completed() + } + } + } + + override fun sendMessage(recipients: List, subject: String, text: String) { + login(LOGIN_METHOD_MOBIDZIENNIK_WEB) { + MobidziennikWebSendMessage(data, recipients, subject, text) { + completed() + } + } + } + + override fun markAllAnnouncementsAsRead() {} + override fun getAnnouncement(announcement: AnnouncementFull) {} + + override fun getAttachment(owner: Any, attachmentId: Long, attachmentName: String) { + login(LOGIN_METHOD_MOBIDZIENNIK_WEB) { + MobidziennikWebGetAttachment(data, owner, attachmentId, attachmentName) { + completed() + } + } + } + + override fun getRecipientList() { + login(LOGIN_METHOD_MOBIDZIENNIK_WEB) { + MobidziennikWebGetRecipientList(data) { + completed() + } + } + } + + override fun getEvent(eventFull: EventFull) { + login(LOGIN_METHOD_MOBIDZIENNIK_WEB) { + if (eventFull.isHomework) { + MobidziennikWebGetHomework(data, eventFull) { + completed() + } + } + else { + MobidziennikWebGetEvent(data, eventFull) { + completed() + } + } + } + } + + override fun firstLogin() { MobidziennikFirstLogin(data) { completed() } } + override fun cancel() { + d(TAG, "Cancelled") + data.cancel() + } + + private fun wrapCallback(callback: EdziennikCallback): EdziennikCallback { + return object : EdziennikCallback { + override fun onCompleted() { callback.onCompleted() } + override fun onProgress(step: Float) { callback.onProgress(step) } + override fun onStartProgress(stringRes: Int) { callback.onStartProgress(stringRes) } + override fun onError(apiError: ApiError) { + if (apiError.errorCode in internalErrorList) { + // finish immediately if the same error occurs twice during the same sync + callback.onError(apiError) + return + } + internalErrorList.add(apiError.errorCode) + when (apiError.errorCode) { + ERROR_MOBIDZIENNIK_WEB_ACCESS_DENIED, + ERROR_MOBIDZIENNIK_WEB_NO_SESSION_KEY, + ERROR_MOBIDZIENNIK_WEB_NO_SESSION_VALUE, + ERROR_MOBIDZIENNIK_WEB_NO_SERVER_ID -> { + data.loginMethods.remove(LOGIN_METHOD_MOBIDZIENNIK_WEB) + data.prepareFor(mobidziennikLoginMethods, LOGIN_METHOD_MOBIDZIENNIK_WEB) + data.webSessionIdExpiryTime = 0 + login() + } + else -> callback.onError(apiError) + } + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/MobidziennikFeatures.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/MobidziennikFeatures.kt new file mode 100644 index 00000000..7b39e455 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/MobidziennikFeatures.kt @@ -0,0 +1,117 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik + +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.models.Feature + +const val ENDPOINT_MOBIDZIENNIK_API_MAIN = 1000 +const val ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_INBOX = 2011 +const val ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_SENT = 2012 +const val ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_ALL = 2019 +const val ENDPOINT_MOBIDZIENNIK_WEB_CALENDAR = 2020 +const val ENDPOINT_MOBIDZIENNIK_WEB_GRADES = 2030 +const val ENDPOINT_MOBIDZIENNIK_WEB_NOTICES = 2040 +const val ENDPOINT_MOBIDZIENNIK_WEB_ATTENDANCE = 2050 +const val ENDPOINT_MOBIDZIENNIK_WEB_MANUALS = 2100 +const val ENDPOINT_MOBIDZIENNIK_WEB_ACCOUNT_EMAIL = 2200 +const val ENDPOINT_MOBIDZIENNIK_WEB_HOMEWORK = 2300 // not used as an endpoint +const val ENDPOINT_MOBIDZIENNIK_WEB_TIMETABLE = 2400 +const val ENDPOINT_MOBIDZIENNIK_API2_MAIN = 3000 + +val MobidziennikFeatures = listOf( + // always synced + Feature(LOGIN_TYPE_MOBIDZIENNIK, FEATURE_ALWAYS_NEEDED, listOf( + ENDPOINT_MOBIDZIENNIK_API_MAIN to LOGIN_METHOD_MOBIDZIENNIK_WEB, + ENDPOINT_MOBIDZIENNIK_WEB_ACCOUNT_EMAIL to LOGIN_METHOD_MOBIDZIENNIK_WEB + ), listOf(LOGIN_METHOD_MOBIDZIENNIK_WEB)), // TODO divide features into separate view IDs (all with API_MAIN) + + // push config + Feature(LOGIN_TYPE_MOBIDZIENNIK, FEATURE_PUSH_CONFIG, listOf( + ENDPOINT_MOBIDZIENNIK_API2_MAIN to LOGIN_METHOD_MOBIDZIENNIK_API2 + ), listOf(LOGIN_METHOD_MOBIDZIENNIK_API2)).withShouldSync { data -> + !data.app.config.sync.tokenMobidziennikList.contains(data.profileId) + }, + + + + + + /** + * Timetable - web scraping - does nothing if the API_MAIN timetable is enough. + */ + Feature(LOGIN_TYPE_MOBIDZIENNIK, FEATURE_TIMETABLE, listOf( + ENDPOINT_MOBIDZIENNIK_WEB_TIMETABLE to LOGIN_METHOD_MOBIDZIENNIK_WEB + ), listOf(LOGIN_METHOD_MOBIDZIENNIK_WEB, LOGIN_METHOD_MOBIDZIENNIK_WEB)), + /** + * Agenda - "API" + web scraping. + */ + Feature(LOGIN_TYPE_MOBIDZIENNIK, FEATURE_AGENDA, listOf( + ENDPOINT_MOBIDZIENNIK_API_MAIN to LOGIN_METHOD_MOBIDZIENNIK_WEB, + ENDPOINT_MOBIDZIENNIK_WEB_CALENDAR to LOGIN_METHOD_MOBIDZIENNIK_WEB + ), listOf(LOGIN_METHOD_MOBIDZIENNIK_WEB, LOGIN_METHOD_MOBIDZIENNIK_WEB)), + /** + * Grades - "API" + web scraping. + */ + Feature(LOGIN_TYPE_MOBIDZIENNIK, FEATURE_GRADES, listOf( + ENDPOINT_MOBIDZIENNIK_API_MAIN to LOGIN_METHOD_MOBIDZIENNIK_WEB, + ENDPOINT_MOBIDZIENNIK_WEB_GRADES to LOGIN_METHOD_MOBIDZIENNIK_WEB + ), listOf(LOGIN_METHOD_MOBIDZIENNIK_WEB, LOGIN_METHOD_MOBIDZIENNIK_WEB)), + /** + * Behaviour - "API" + web scraping. + */ + Feature(LOGIN_TYPE_MOBIDZIENNIK, FEATURE_BEHAVIOUR, listOf( + ENDPOINT_MOBIDZIENNIK_API_MAIN to LOGIN_METHOD_MOBIDZIENNIK_WEB, + ENDPOINT_MOBIDZIENNIK_WEB_NOTICES to LOGIN_METHOD_MOBIDZIENNIK_WEB + ), listOf(LOGIN_METHOD_MOBIDZIENNIK_WEB, LOGIN_METHOD_MOBIDZIENNIK_WEB)), + /** + * Attendance - only web scraping. + */ + Feature(LOGIN_TYPE_MOBIDZIENNIK, FEATURE_ATTENDANCE, listOf( + ENDPOINT_MOBIDZIENNIK_WEB_ATTENDANCE to LOGIN_METHOD_MOBIDZIENNIK_WEB + ), listOf(LOGIN_METHOD_MOBIDZIENNIK_WEB)), + + + + + + /** + * Messages inbox - using web scraper. + */ + Feature(LOGIN_TYPE_MOBIDZIENNIK, FEATURE_MESSAGES_INBOX, listOf( + ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_INBOX to LOGIN_METHOD_MOBIDZIENNIK_WEB, + ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_ALL to LOGIN_METHOD_MOBIDZIENNIK_WEB + ), listOf(LOGIN_METHOD_MOBIDZIENNIK_WEB)), + /** + * Messages sent - using web scraper. + */ + Feature(LOGIN_TYPE_MOBIDZIENNIK, FEATURE_MESSAGES_SENT, listOf( + ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_SENT to LOGIN_METHOD_MOBIDZIENNIK_WEB, + ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_ALL to LOGIN_METHOD_MOBIDZIENNIK_WEB + ), listOf(LOGIN_METHOD_MOBIDZIENNIK_WEB)) + + // lucky number possibilities + // all endpoints that may supply the lucky number + /*Feature(LOGIN_TYPE_MOBIDZIENNIK, FEATURE_LUCKY_NUMBER, listOf( + ENDPOINT_MOBIDZIENNIK_WEB_MANUALS to LOGIN_METHOD_MOBIDZIENNIK_WEB + ), listOf(LOGIN_METHOD_MOBIDZIENNIK_WEB)).apply { priority = 10 }, + + Feature(LOGIN_TYPE_MOBIDZIENNIK, FEATURE_LUCKY_NUMBER, listOf( + ENDPOINT_MOBIDZIENNIK_WEB_CALENDAR to LOGIN_METHOD_MOBIDZIENNIK_WEB + ), listOf(LOGIN_METHOD_MOBIDZIENNIK_WEB)).apply { priority = 3 }, + + Feature(LOGIN_TYPE_MOBIDZIENNIK, FEATURE_LUCKY_NUMBER, listOf( + ENDPOINT_MOBIDZIENNIK_WEB_GRADES to LOGIN_METHOD_MOBIDZIENNIK_WEB + ), listOf(LOGIN_METHOD_MOBIDZIENNIK_WEB)).apply { priority = 2 }, + + Feature(LOGIN_TYPE_MOBIDZIENNIK, FEATURE_LUCKY_NUMBER, listOf( + ENDPOINT_MOBIDZIENNIK_WEB_NOTICES to LOGIN_METHOD_MOBIDZIENNIK_WEB + ), listOf(LOGIN_METHOD_MOBIDZIENNIK_WEB)).apply { priority = 1 }, + + Feature(LOGIN_TYPE_MOBIDZIENNIK, FEATURE_LUCKY_NUMBER, listOf( + ENDPOINT_MOBIDZIENNIK_WEB_ATTENDANCE to LOGIN_METHOD_MOBIDZIENNIK_WEB + ), listOf(LOGIN_METHOD_MOBIDZIENNIK_WEB)).apply { priority = 4 }*/ + +) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/MobidziennikData.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/MobidziennikData.kt new file mode 100644 index 00000000..b82f6355 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/MobidziennikData.kt @@ -0,0 +1,94 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data + +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.* +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.api.MobidziennikApi +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.api2.MobidziennikApi2Main +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.web.* +import pl.szczodrzynski.edziennik.utils.Utils + +class MobidziennikData(val data: DataMobidziennik, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "MobidziennikData" + } + + init { + nextEndpoint(onSuccess) + } + + private fun nextEndpoint(onSuccess: () -> Unit) { + if (data.targetEndpointIds.isEmpty()) { + onSuccess() + return + } + if (data.cancelled) { + onSuccess() + return + } + val id = data.targetEndpointIds.firstKey() + val lastSync = data.targetEndpointIds.remove(id) + useEndpoint(id, lastSync) { endpointId -> + data.progress(data.progressStep) + nextEndpoint(onSuccess) + } + } + + private fun useEndpoint(endpointId: Int, lastSync: Long?, onSuccess: (endpointId: Int) -> Unit) { + Utils.d(TAG, "Using endpoint $endpointId. Last sync time = $lastSync") + when (endpointId) { + ENDPOINT_MOBIDZIENNIK_API_MAIN -> { + data.startProgress(R.string.edziennik_progress_endpoint_data) + MobidziennikApi(data, lastSync, onSuccess) + } + ENDPOINT_MOBIDZIENNIK_API2_MAIN -> { + data.startProgress(R.string.edziennik_progress_endpoint_push_config) + MobidziennikApi2Main(data, lastSync, onSuccess) + } + ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_INBOX -> { + data.startProgress(R.string.edziennik_progress_endpoint_messages_inbox) + MobidziennikWebMessagesInbox(data, lastSync, onSuccess) + } + ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_SENT -> { + data.startProgress(R.string.edziennik_progress_endpoint_messages_outbox) + MobidziennikWebMessagesSent(data, lastSync, onSuccess) + } + ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_ALL -> { + data.startProgress(R.string.edziennik_progress_endpoint_messages) + MobidziennikWebMessagesAll(data, lastSync, onSuccess) + } + ENDPOINT_MOBIDZIENNIK_WEB_CALENDAR -> { + data.startProgress(R.string.edziennik_progress_endpoint_calendar) + MobidziennikWebCalendar(data, lastSync, onSuccess) + } + ENDPOINT_MOBIDZIENNIK_WEB_GRADES -> { + data.startProgress(R.string.edziennik_progress_endpoint_grades) + MobidziennikWebGrades(data, lastSync, onSuccess) + } + ENDPOINT_MOBIDZIENNIK_WEB_ACCOUNT_EMAIL -> { + data.startProgress(R.string.edziennik_progress_endpoint_account_details) + MobidziennikWebAccountEmail(data, lastSync, onSuccess) + } + ENDPOINT_MOBIDZIENNIK_WEB_ATTENDANCE -> { + data.startProgress(R.string.edziennik_progress_endpoint_attendance) + MobidziennikWebAttendance(data, lastSync, onSuccess) + }/* + ENDPOINT_MOBIDZIENNIK_WEB_NOTICES -> { + data.startProgress(R.string.edziennik_progress_endpoint_behaviour) + MobidziennikWebNotices(data, lastSync, onSuccess) + }] + ENDPOINT_MOBIDZIENNIK_WEB_MANUALS -> { + data.startProgress(R.string.edziennik_progress_endpoint_lucky_number) + MobidziennikWebManuals(data, lastSync, onSuccess) + }*/ + ENDPOINT_MOBIDZIENNIK_WEB_TIMETABLE-> { + data.startProgress(R.string.edziennik_progress_endpoint_timetable) + MobidziennikWebTimetable(data, lastSync, onSuccess) + } + else -> onSuccess(endpointId) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/MobidziennikWeb.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/MobidziennikWeb.kt new file mode 100644 index 00000000..cfb4ab49 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/MobidziennikWeb.kt @@ -0,0 +1,189 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data + +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.callback.FileCallbackHandler +import im.wangchao.mhttp.callback.TextCallbackHandler +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.utils.Utils.d +import java.io.File + +open class MobidziennikWeb(open val data: DataMobidziennik, open val lastSync: Long?) { + companion object { + private const val TAG = "MobidziennikWeb" + } + + val profileId + get() = data.profile?.id ?: -1 + + val profile + get() = data.profile + + /* TODO + add error handling: + + +
    + +

    Ważna informacja!

    + +
    + Korzystasz z hasła, które zostało wygenerowane automatycznie.
    + Pamiętaj, aby je zmienić oraz uzupełnić dane w swoim profilu.

    + Obie te operacje można wykonać uruchamiając opcję + Moje konto->Edycja profilu. +
    + + */ + + fun webGet( + tag: String, + endpoint: String, + method: Int = GET, + parameters: List> = emptyList(), + fullUrl: String? = null, + onSuccess: (text: String) -> Unit + ) { + val url = fullUrl ?: "https://${data.loginServerName}.mobidziennik.pl$endpoint" + + d(tag, "Request: Mobidziennik/Web - $url") + + if (data.webSessionKey == null) { + data.error(TAG, ERROR_MOBIDZIENNIK_WEB_NO_SESSION_KEY) + return + } + if (data.webSessionValue == null) { + data.error(TAG, ERROR_MOBIDZIENNIK_WEB_NO_SESSION_VALUE) + return + } + if (data.webServerId == null) { + data.error(TAG, ERROR_MOBIDZIENNIK_WEB_NO_SERVER_ID) + return + } + + val callback = object : TextCallbackHandler() { + override fun onSuccess(text: String?, response: Response?) { + if (text.isNullOrEmpty()) { + data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) + .withResponse(response)) + return + } + if (text == "Nie jestes zalogowany" + || text.contains("przypomnij_haslo_email")) { + data.error(ApiError(TAG, ERROR_MOBIDZIENNIK_WEB_ACCESS_DENIED) + .withResponse(response)) + return + } + + if (text.contains("

    Problemy z wydajnością

    ")) { + data.error(ApiError(TAG, ERROR_MOBIDZIENNIK_WEB_SERVER_PROBLEM) + .withResponse(response)) + return + } + + try { + onSuccess(text) + } catch (e: Exception) { + data.error(ApiError(tag, EXCEPTION_MOBIDZIENNIK_WEB_REQUEST) + .withResponse(response) + .withThrowable(e) + .withApiResponse(text)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(TAG, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + data.app.cookieJar.set("${data.loginServerName}.mobidziennik.pl", data.webSessionKey, data.webSessionValue) + data.app.cookieJar.set("${data.loginServerName}.mobidziennik.pl", "SERVERID", data.webServerId) + + Request.builder() + .url(url) + .userAgent(MOBIDZIENNIK_USER_AGENT) + .apply { + when (method) { + GET -> get() + POST -> post() + } + parameters.map { (name, value) -> + addParameter(name, value) + } + } + .callback(callback) + .build() + .enqueue() + } + + fun webGetFile(tag: String, action: String, targetFile: File, onSuccess: (file: File) -> Unit, + onProgress: (written: Long, total: Long) -> Unit) { + val url = "https://${data.loginServerName}.mobidziennik.pl$action" + + d(tag, "Request: Mobidziennik/Web - $url") + + if (data.webSessionKey == null) { + data.error(TAG, ERROR_MOBIDZIENNIK_WEB_NO_SESSION_KEY) + return + } + if (data.webSessionValue == null) { + data.error(TAG, ERROR_MOBIDZIENNIK_WEB_NO_SESSION_VALUE) + return + } + if (data.webServerId == null) { + data.error(TAG, ERROR_MOBIDZIENNIK_WEB_NO_SERVER_ID) + return + } + + val callback = object : FileCallbackHandler(targetFile) { + override fun onSuccess(file: File?, response: Response?) { + if (file == null) { + data.error(ApiError(TAG, ERROR_FILE_DOWNLOAD) + .withResponse(response)) + return + } + + try { + onSuccess(file) + } catch (e: Exception) { + data.error(ApiError(tag, EXCEPTION_MOBIDZIENNIK_WEB_FILE_REQUEST) + .withResponse(response) + .withThrowable(e)) + } + } + + override fun onProgress(bytesWritten: Long, bytesTotal: Long) { + try { + onProgress(bytesWritten, bytesTotal) + } catch (e: Exception) { + data.error(ApiError(tag, EXCEPTION_MOBIDZIENNIK_WEB_FILE_REQUEST) + .withThrowable(e)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(TAG, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + data.app.cookieJar.set("${data.loginServerName}.mobidziennik.pl", data.webSessionKey, data.webSessionValue) + data.app.cookieJar.set("${data.loginServerName}.mobidziennik.pl", "SERVERID", data.webServerId) + + Request.builder() + .url(url) + .userAgent(MOBIDZIENNIK_USER_AGENT) + .callback(callback) + .build() + .enqueue() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApi.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApi.kt new file mode 100644 index 00000000..323aeb14 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApi.kt @@ -0,0 +1,55 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-11. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.api + +import pl.szczodrzynski.edziennik.data.api.ERROR_MOBIDZIENNIK_WEB_INVALID_RESPONSE +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.ENDPOINT_MOBIDZIENNIK_API_MAIN +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.MobidziennikWeb +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS + +class MobidziennikApi(override val data: DataMobidziennik, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : MobidziennikWeb(data, lastSync) { + companion object { + private const val TAG = "MobidziennikApi" + } + + init { + webGet(TAG, "/api/zrzutbazy") { text -> + if (!text.contains("T@B#LA")) { + data.error(ApiError(TAG, ERROR_MOBIDZIENNIK_WEB_INVALID_RESPONSE) + .withApiResponse(text)) + return@webGet + } + + val tables = text.split("T@B#LA") + tables.forEachIndexed { index, table -> + val rows = table.split("\n") + when (index) { + 0 -> MobidziennikApiUsers(data, rows) + 3 -> MobidziennikApiDates(data, rows) + 4 -> MobidziennikApiSubjects(data, rows) + 7 -> MobidziennikApiTeams(data, rows, null) + 8 -> MobidziennikApiStudent(data, rows) + 9 -> MobidziennikApiTeams(data, null, rows) + 14 -> MobidziennikApiGradeCategories(data, rows) + 15 -> MobidziennikApiLessons(data, rows) + //16 -> MobidziennikApiAttendance(data, rows) // disabled since the new web scrapper is used + 17 -> MobidziennikApiNotices(data, rows) + 18 -> MobidziennikApiGrades(data, rows) + 21 -> MobidziennikApiEvents(data, rows) + 23 -> MobidziennikApiHomework(data, rows) + 24 -> MobidziennikApiTimetable(data, rows) + } + } + + data.setSyncNext(ENDPOINT_MOBIDZIENNIK_API_MAIN, SYNC_ALWAYS) + onSuccess(ENDPOINT_MOBIDZIENNIK_API_MAIN) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiAttendance.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiAttendance.kt new file mode 100644 index 00000000..473b3691 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiAttendance.kt @@ -0,0 +1,81 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-11. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.api + +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.data.db.entity.Attendance.Companion.TYPE_ABSENT +import pl.szczodrzynski.edziennik.data.db.entity.Attendance.Companion.TYPE_ABSENT_EXCUSED +import pl.szczodrzynski.edziennik.data.db.entity.Attendance.Companion.TYPE_PRESENT +import pl.szczodrzynski.edziennik.data.db.entity.Attendance.Companion.TYPE_RELEASED +import pl.szczodrzynski.edziennik.data.db.entity.Metadata + +class MobidziennikApiAttendance(val data: DataMobidziennik, rows: List) { + init { run { + for (row in rows) { + if (row.isEmpty()) + continue + val cols = row.split("|") + + val studentId = cols[2].toInt() + if (studentId != data.studentId) + return@run + + val id = cols[0].toLong() + val lessonId = cols[1].toLong() + data.mobiLessons.singleOrNull { it.id == lessonId }?.let { lesson -> + val baseType = when (cols[4]) { + "2" -> TYPE_ABSENT + "5" -> TYPE_ABSENT_EXCUSED + "4" -> TYPE_RELEASED + else -> TYPE_PRESENT + } + val semester = data.profile?.dateToSemester(lesson.date) ?: 1 + + val typeName = when (baseType) { + TYPE_ABSENT -> "nieobecność" + TYPE_ABSENT_EXCUSED -> "nieobecność usprawiedliwiona" + TYPE_RELEASED -> "zwolnienie" + TYPE_PRESENT -> "obecność" + else -> "nieznany rodzaj" + } + val typeSymbol = when (baseType) { + TYPE_ABSENT -> "|" + TYPE_ABSENT_EXCUSED -> "+" + TYPE_RELEASED -> "z" + TYPE_PRESENT -> "." + else -> "?" + } + + val attendanceObject = Attendance( + profileId = data.profileId, + id = id, + baseType = baseType, + typeName = typeName, + typeShort = data.app.attendanceManager.getTypeShort(baseType), + typeSymbol = typeSymbol, + typeColor = null, + date = lesson.date, + startTime = lesson.startTime, + semester = semester, + teacherId = lesson.teacherId, + subjectId = lesson.subjectId + ).also { + it.lessonTopic = lesson.topic + } + + data.attendanceList.add(attendanceObject) + data.metadataList.add( + Metadata( + data.profileId, + Metadata.TYPE_ATTENDANCE, + id, + data.profile?.empty ?: false || baseType == Attendance.TYPE_PRESENT_CUSTOM || baseType == Attendance.TYPE_UNKNOWN, + data.profile?.empty ?: false || baseType == Attendance.TYPE_PRESENT_CUSTOM || baseType == Attendance.TYPE_UNKNOWN + )) + } + } + }} +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiDates.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiDates.kt new file mode 100644 index 00000000..a0b3dbc2 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiDates.kt @@ -0,0 +1,24 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-11. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.api + +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.utils.models.Date + +class MobidziennikApiDates(val data: DataMobidziennik, rows: List) { + init { + for (row in rows) { + if (row.isEmpty()) + continue + val cols = row.split("|") + + when (cols[1]) { + "semestr1_poczatek" -> data.profile?.dateSemester1Start = Date.fromYmd(cols[3]) + "semestr2_poczatek" -> data.profile?.dateSemester2Start = Date.fromYmd(cols[3]) + "koniec_roku_szkolnego" -> data.profile?.dateYearEnd = Date.fromYmd(cols[3]) + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiEvents.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiEvents.kt new file mode 100644 index 00000000..7a72d3de --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiEvents.kt @@ -0,0 +1,83 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-11. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.api + +import androidx.core.util.contains +import pl.szczodrzynski.edziennik.data.api.Regexes +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time +import java.text.ParseException +import java.text.SimpleDateFormat +import java.util.* + +class MobidziennikApiEvents(val data: DataMobidziennik, rows: List) { + init { + for (row in rows) { + if (row.isEmpty()) + continue + val cols = row.split("|") + + val teamId = cols[2].toLong() + if (data.teamList.contains(teamId)) { + + val id = cols[0].toLong() + val teacherId = cols[1].toLong() + val subjectId = cols[3].toLong() + var type = Event.TYPE_DEFAULT + var topic = cols[5].trim() + Regexes.MOBIDZIENNIK_EVENT_TYPE.find(topic)?.let { + val typeText = it.groupValues[1] + when (typeText) { + "sprawdzian" -> type = Event.TYPE_EXAM + "kartkówka" -> type = Event.TYPE_SHORT_QUIZ + } + topic = topic.replace("($typeText)", "").trim() + } + val eventDate = Date.fromYmd(cols[4]) + val startTime = Time.fromYmdHm(cols[6]) + val format = SimpleDateFormat("yyyyMMddHHmmss", Locale.US) + val addedDate = try { + format.parse(cols[7]).time + } catch (e: ParseException) { + e.printStackTrace() + System.currentTimeMillis() + } + + + val eventObject = Event( + profileId = data.profileId, + id = id, + date = eventDate, + time = startTime, + topic = topic, + color = null, + type = type, + teacherId = teacherId, + subjectId = subjectId, + teamId = teamId, + addedDate = addedDate + ) + + data.eventList.add(eventObject) + data.metadataList.add( + Metadata( + data.profileId, + Metadata.TYPE_EVENT, + id, + data.profile?.empty ?: false, + data.profile?.empty ?: false + )) + } + } + + data.toRemove.add(DataRemoveModel.Events.futureWithType(Event.TYPE_DEFAULT)) + data.toRemove.add(DataRemoveModel.Events.futureWithType(Event.TYPE_EXAM)) + data.toRemove.add(DataRemoveModel.Events.futureWithType(Event.TYPE_SHORT_QUIZ)) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiGradeCategories.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiGradeCategories.kt new file mode 100644 index 00000000..b3bb8177 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiGradeCategories.kt @@ -0,0 +1,41 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-7. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.api + +import android.graphics.Color +import androidx.core.util.contains +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.data.db.entity.GradeCategory + +class MobidziennikApiGradeCategories(val data: DataMobidziennik, rows: List) { + init { + for (row in rows) { + if (row.isEmpty()) + continue + val cols = row.split("|") + + val teamId = cols[1].toLong() + if (data.teamList.contains(teamId)) { + + val id = cols[0].toLong() + val weight = cols[3].toFloat() + val color = Color.parseColor("#" + cols[6]) + val category = cols[4] + val columns = cols[7].split(";") + + data.gradeCategories.put( + id, + GradeCategory( + data.profileId, + id, + weight, + color, + category + ).addColumns(columns) + ) + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiGrades.kt new file mode 100644 index 00000000..c3c1b449 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiGrades.kt @@ -0,0 +1,113 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-8. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.api + +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Grade +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_NORMAL +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_SEMESTER1_FINAL +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_SEMESTER1_PROPOSED +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_SEMESTER2_FINAL +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_SEMESTER2_PROPOSED +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_YEAR_FINAL +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_YEAR_PROPOSED +import pl.szczodrzynski.edziennik.data.db.entity.Metadata + +class MobidziennikApiGrades(val data: DataMobidziennik, rows: List) { + init { data.profile?.also { profile -> run { + data.db.gradeDao().getDetails( + data.profileId, + data.gradeAddedDates, + data.gradeAverages, + data.gradeColors + ) + var addedDate = System.currentTimeMillis() + for (row in rows) { + if (row.isEmpty()) + continue + val cols = row.split("|") + + val studentId = cols[1].toInt() + if (studentId != data.studentId) + return@run + + val id = cols[0].toLong() + val categoryId = cols[6].toLongOrNull() ?: -1 + val categoryColumn = cols[10].toIntOrNull() ?: 1 + val name = cols[7] + val value = cols[11].toFloat() + val semester = cols[5].toInt() + val teacherId = cols[2].toLong() + val subjectId = cols[3].toLong() + val type = when (cols[8]) { + "3" -> if (semester == 1) TYPE_SEMESTER1_PROPOSED else TYPE_SEMESTER2_PROPOSED + "1" -> if (semester == 1) TYPE_SEMESTER1_FINAL else TYPE_SEMESTER2_FINAL + "4" -> TYPE_YEAR_PROPOSED + "2" -> TYPE_YEAR_FINAL + else -> TYPE_NORMAL + } + + var weight = 0.0f + var category = "" + var description = "" + var color = -1 + data.gradeCategories.get(categoryId)?.let { gradeCategory -> + weight = gradeCategory.weight + category = gradeCategory.text + description = gradeCategory.columns[categoryColumn-1] + color = gradeCategory.color + } + + // fix for "0" value grades, so they're not counted in the average + if (value == 0.0f/* && data.app.appConfig.dontCountZeroToAverage*/) { + weight = 0.0f + } + + val gradeObject = Grade( + profileId = data.profileId, + id = id, + name = name, + type = type, + value = value, + weight = weight, + color = color, + category = category, + description = description, + comment = null, + semester = semester, + teacherId = teacherId, + subjectId = subjectId, + addedDate = addedDate + ) + + if (data.profile?.empty == true) { + addedDate = data.profile.dateSemester1Start.inMillis + } + + data.gradeList.add(gradeObject) + data.metadataList.add( + Metadata( + data.profileId, + Metadata.TYPE_GRADE, + id, + data.profile?.empty ?: false, + data.profile?.empty ?: false + )) + addedDate++ + } + data.toRemove.addAll(listOf( + TYPE_NORMAL, + TYPE_SEMESTER1_FINAL, + TYPE_SEMESTER2_FINAL, + TYPE_SEMESTER1_PROPOSED, + TYPE_SEMESTER2_PROPOSED, + TYPE_YEAR_FINAL, + TYPE_YEAR_PROPOSED + ).map { + DataRemoveModel.Grades.semesterWithType(profile.currentSemester, it) + }) + }}} +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiHomework.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiHomework.kt new file mode 100644 index 00000000..a79eaded --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiHomework.kt @@ -0,0 +1,60 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-11. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.api + +import androidx.core.util.contains +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.utils.html.BetterHtml +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time + +class MobidziennikApiHomework(val data: DataMobidziennik, rows: List) { + init { + for (row in rows) { + if (row.isEmpty()) + continue + val cols = row.split("|") + + val teamId = cols[5].toLong() + if (data.teamList.contains(teamId)) { + + val id = cols[0].toLong() + val teacherId = cols[7].toLong() + val subjectId = cols[6].toLong() + val topic = BetterHtml.fromHtml(context = null, cols[1]).toString().trim() + val eventDate = Date.fromYmd(cols[2]) + val startTime = Time.fromYmdHm(cols[3]) + + val eventObject = Event( + profileId = data.profileId, + id = id, + date = eventDate, + time = startTime, + topic = topic, + color = null, + type = Event.TYPE_HOMEWORK, + teacherId = teacherId, + subjectId = subjectId, + teamId = teamId + ) + + data.eventList.add(eventObject) + data.metadataList.add( + Metadata( + data.profileId, + Metadata.TYPE_HOMEWORK, + id, + data.profile?.empty ?: false, + data.profile?.empty ?: false + )) + } + } + + data.toRemove.add(DataRemoveModel.Events.futureWithType(Event.TYPE_HOMEWORK)) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiLessons.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiLessons.kt new file mode 100644 index 00000000..47ab7494 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiLessons.kt @@ -0,0 +1,49 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-7. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.api + +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time + +class MobidziennikApiLessons(val data: DataMobidziennik, rows: List) { + init { + data.mobiLessons.clear() + for (row in rows) { + if (row.isEmpty()) + continue + val cols = row.split("|") + + val id = cols[0].toLong() + val subjectId = cols[1].toLong() + val teacherId = cols[2].toLong() + val teamId = cols[3].toLong() + val topic = cols[4] + val date = Date.fromYmd(cols[5]) + val startTime = Time.fromYmdHm(cols[6]) + val endTime = Time.fromYmdHm(cols[7]) + val presentCount = cols[8].toInt() + val absentCount = cols[9].toInt() + val lessonNumber = cols[10].toInt() + val signed = cols[11] + + val lesson = DataMobidziennik.MobiLesson( + id, + subjectId, + teacherId, + teamId, + topic, + date, + startTime, + endTime, + presentCount, + absentCount, + lessonNumber, + signed + ) + data.mobiLessons.add(lesson) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiNotices.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiNotices.kt new file mode 100644 index 00000000..66bfe1fd --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiNotices.kt @@ -0,0 +1,58 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-11. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.api + +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.Notice +import pl.szczodrzynski.edziennik.utils.models.Date + +class MobidziennikApiNotices(val data: DataMobidziennik, rows: List) { + init { run { + for (row in rows) { + if (row.isEmpty()) + continue + val cols = row.split("|") + + val studentId = cols[2].toInt() + if (studentId != data.studentId) + return@run + + val id = cols[0].toLong() + val text = cols[4] + val semester = cols[6].toInt() + val type = when (cols[3]) { + "0" -> Notice.TYPE_NEGATIVE + "1" -> Notice.TYPE_POSITIVE + "3" -> Notice.TYPE_NEUTRAL + else -> Notice.TYPE_NEUTRAL + } + val teacherId = cols[5].toLong() + val addedDate = Date.fromYmd(cols[7]).inMillis + + val noticeObject = Notice( + profileId = data.profileId, + id = id, + type = type, + semester = semester, + text = text, + category = null, + points = null, + teacherId = teacherId, + addedDate = addedDate + ) + + data.noticeList.add(noticeObject) + data.metadataList.add( + Metadata( + data.profileId, + Metadata.TYPE_NOTICE, + id, + data.profile?.empty ?: false, + data.profile?.empty ?: false + )) + } + }} +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiStudent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiStudent.kt new file mode 100644 index 00000000..2435478e --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiStudent.kt @@ -0,0 +1,37 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-6. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.api + +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik + +class MobidziennikApiStudent(val data: DataMobidziennik, rows: List) { + init { run { + if (rows.size < 2) { + return@run + } + + val student1 = rows[0].split("|") + val student2 = rows[1].split("|") + + // FROM OLD Mobidziennik API - this information seems to be unused + /*students.clear(); + String[] student = table.split("\n"); + for (int i = 0; i < student.length; i++) { + if (student[i].isEmpty()) { + continue; + } + String[] student1 = student[i].split("\\|", Integer.MAX_VALUE); + String[] student2 = student[++i].split("\\|", Integer.MAX_VALUE); + students.put(strToInt(student1[0]), new Pair<>(student1, student2)); + } + Pair studentData = students.get(studentId); + try { + profile.setAttendancePercentage(Float.parseFloat(studentData.second[1])); + } + catch (Exception e) { + e.printStackTrace(); + }*/ + }} +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiSubjects.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiSubjects.kt new file mode 100644 index 00000000..ce635860 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiSubjects.kt @@ -0,0 +1,25 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-6. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.api + +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.data.db.entity.Subject + +class MobidziennikApiSubjects(val data: DataMobidziennik, rows: List) { + init { + for (row in rows) { + if (row.isEmpty()) + continue + val cols = row.split("|") + + val id = cols[0].toLong() + val longName = cols[1].trim() + val shortName = cols[2].trim() + + data.subjectsMap.put(id, longName) + data.subjectList.put(id, Subject(data.profileId, id, longName, shortName)) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiTeams.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiTeams.kt new file mode 100644 index 00000000..dbd1c03d --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiTeams.kt @@ -0,0 +1,62 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-11. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.api + +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.data.db.entity.Team +import pl.szczodrzynski.edziennik.ext.getById +import pl.szczodrzynski.edziennik.ext.values + +class MobidziennikApiTeams(val data: DataMobidziennik, tableTeams: List?, tableRelations: List?) { + init { + if (tableTeams != null) { + for (row in tableTeams) { + if (row.isEmpty()) + continue + val cols = row.split("|") + + val id = cols[0].toLong() + val name = cols[1]+cols[2] + val type = cols[3].toInt() + val code = data.loginServerName+":"+name + val teacherId = cols[4].toLongOrNull() ?: -1 + + val teamObject = Team( + data.profileId, + id, + name, + type, + code, + teacherId) + data.teamList.put(id, teamObject) + } + } + if (tableRelations != null) { + val allTeams = data.teamList.values() + + for (row in tableRelations) { + if (row.isEmpty()) + continue + val cols = row.split("|") + + val studentId = cols[1].toInt() + val teamId = cols[2].toLong() + val studentNumber = cols[4].toIntOrNull() ?: -1 + + if (studentId != data.studentId) + continue + val team = allTeams.getById(teamId) + if (team != null) { + if (team.type == 1) { + data.profile?.studentNumber = studentNumber + data.teamClass = team + data.profile?.studentClassName = team.name + } + data.teamList.put(teamId, team) + } + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiTimetable.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiTimetable.kt new file mode 100644 index 00000000..8e490832 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiTimetable.kt @@ -0,0 +1,130 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-11. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.api + +import android.util.SparseArray +import androidx.core.util.set +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Lesson +import pl.szczodrzynski.edziennik.data.db.entity.LessonRange +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.ext.fixName +import pl.szczodrzynski.edziennik.ext.keys +import pl.szczodrzynski.edziennik.ext.singleOrNull +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time + +class MobidziennikApiTimetable(val data: DataMobidziennik, rows: List) { + init { data.profile?.also { profile -> + val lessons = rows.filterNot { it.isEmpty() }.map { it.split("|") } + + val dataStart = Date.getToday() + val dataEnd = dataStart.clone().stepForward(0, 0, 7 + (6 - dataStart.weekDay)) + + data.toRemove.add(DataRemoveModel.Timetable.between(dataStart.clone(), dataEnd, isExtra = false)) + + val dataDays = mutableListOf() + while (dataStart <= dataEnd) { + dataDays += dataStart.value + dataStart.stepForward(0, 0, 1) + } + + val lessonRanges = SparseArray
    ")) -> { + items.remove(item) + i-- + } + + item.contains("(") && item.contains(")") -> { + classroomName = classroomRegex.find(item)?.get(1) + items[i] = item.replace("($classroomName)", "").trim() + } + classroomName != null && item.contains(classroomName) -> { + items[i] = item.replace("($classroomName)", "").trim() + } + + item.contains("class=\"wyjatek tooltip\"") -> { + items.remove(item) + i-- + } + } + // finally advance to the next item + i++ + } + } + + if (items.size == 2 && items[0].contains(" - ")) { + val parts = items[0].split(" - ") + teamName = parts[0] + teacherName = parts[1] + } + else if (items.size == 2 && typeName?.contains("odwołana") == true) { + teamName = items[0] + } + else if (items.size == 4) { + teamName = items[0] + teacherName = items[1] + } + + val type = when (typeName) { + "zastępstwo" -> Lesson.TYPE_CHANGE + "lekcja odwołana", "odwołana" -> Lesson.TYPE_CANCELLED + else -> Lesson.TYPE_NORMAL + } + val subject = subjectName?.let { data.getSubject(null, it) } + val teacher = teacherName?.let { data.getTeacherByLastFirst(it) } + val team = teamName?.let { data.getTeam( + id = null, + name = it, + schoolCode = data.loginServerName ?: return@let null, + isTeamClass = false + ) } + + Lesson(data.profileId, -1).also { + it.type = type + if (type == Lesson.TYPE_CANCELLED) { + it.oldDate = lessonDate + it.oldLessonNumber = lessonNumber + it.oldStartTime = startTime + it.oldEndTime = endTime + it.oldSubjectId = subject?.id ?: -1 + it.oldTeamId = team?.id ?: -1 + } + else { + it.date = lessonDate + it.lessonNumber = lessonNumber + it.startTime = startTime + it.endTime = endTime + it.subjectId = subject?.id ?: -1 + it.teacherId = teacher?.id ?: -1 + it.teamId = team?.id ?: -1 + it.classroom = classroomName + } + + it.id = it.buildId() + it.isExtra = isExtra + + val seen = profile?.empty == false || lessonDate < Date.getToday() + + if (it.type != Lesson.TYPE_NORMAL) { + data.metadataList.add( + Metadata( + data.profileId, + Metadata.TYPE_LESSON_CHANGE, + it.id, + seen, + seen + ) + ) + } + data.lessonList += it + } + } + + for (date in noLessonDays) { + data.lessonList += Lesson(data.profileId, date.value.toLong()).also { + it.type = Lesson.TYPE_NO_LESSONS + it.date = date + } + } + } +} + diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/firstlogin/MobidziennikFirstLogin.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/firstlogin/MobidziennikFirstLogin.kt new file mode 100644 index 00000000..91390c5c --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/firstlogin/MobidziennikFirstLogin.kt @@ -0,0 +1,93 @@ +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.firstlogin + +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.data.api.LOGIN_TYPE_MOBIDZIENNIK +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.MobidziennikWeb +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.login.MobidziennikLoginWeb +import pl.szczodrzynski.edziennik.data.api.events.FirstLoginFinishedEvent +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.fixName +import pl.szczodrzynski.edziennik.ext.set +import pl.szczodrzynski.edziennik.utils.models.Date + +class MobidziennikFirstLogin(val data: DataMobidziennik, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "MobidziennikFirstLogin" + } + + private val web = MobidziennikWeb(data, null) + private val profileList = mutableListOf() + + init { + val loginStoreId = data.loginStore.id + val loginStoreType = LOGIN_TYPE_MOBIDZIENNIK + var firstProfileId = loginStoreId + + MobidziennikLoginWeb(data) { + web.webGet(TAG, "/api/zrzutbazy") { text -> + val tables = text.split("T@B#LA") + + val accountNameLong = run { + tables[0] + .split("\n") + .map { it.split("|") } + .singleOrNull { it.getOrNull(1) != "*" } + ?.let { + "${it[4]} ${it[5]}".fixName() + } + } + + var dateSemester1Start: Date? = null + var dateSemester2Start: Date? = null + var dateYearEnd: Date? = null + for (row in tables[3].split("\n")) { + if (row.isEmpty()) + continue + val cols = row.split("|") + + when (cols[1]) { + "semestr1_poczatek" -> dateSemester1Start = Date.fromYmd(cols[3]) + "semestr2_poczatek" -> dateSemester2Start = Date.fromYmd(cols[3]) + "koniec_roku_szkolnego" -> dateYearEnd = Date.fromYmd(cols[3]) + } + } + + tables[8].split("\n").forEach { student -> + if (student.isEmpty()) + return@forEach + val student1 = student.split("|") + if (student1.size == 2) + return@forEach + + val studentNameLong = "${student1[2]} ${student1[4]}".fixName() + val studentNameShort = "${student1[2]} ${student1[4][0]}.".fixName() + val accountName = if (accountNameLong == studentNameLong) null else accountNameLong + + val profile = Profile( + firstProfileId++, + loginStoreId, + loginStoreType, + studentNameLong, + data.loginUsername, + studentNameLong, + studentNameShort, + accountName + ).apply { + studentData["studentId"] = student1[0].toInt() + } + dateSemester1Start?.let { + profile.dateSemester1Start = it + profile.studentSchoolYearStart = it.year + } + dateSemester2Start?.let { profile.dateSemester2Start = it } + dateYearEnd?.let { profile.dateYearEnd = it } + profileList.add(profile) + } + + EventBus.getDefault().postSticky(FirstLoginFinishedEvent(profileList, data.loginStore)) + onSuccess() + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/login/MobidziennikLogin.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/login/MobidziennikLogin.kt new file mode 100644 index 00000000..7bc79a7b --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/login/MobidziennikLogin.kt @@ -0,0 +1,59 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.login + +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_MOBIDZIENNIK_API2 +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_MOBIDZIENNIK_WEB +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.utils.Utils + +class MobidziennikLogin(val data: DataMobidziennik, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "MobidziennikLogin" + } + + private var cancelled = false + + init { + nextLoginMethod(onSuccess) + } + + private fun nextLoginMethod(onSuccess: () -> Unit) { + if (data.targetLoginMethodIds.isEmpty()) { + onSuccess() + return + } + if (cancelled) { + onSuccess() + return + } + useLoginMethod(data.targetLoginMethodIds.removeAt(0)) { usedMethodId -> + data.progress(data.progressStep) + if (usedMethodId != -1) + data.loginMethods.add(usedMethodId) + nextLoginMethod(onSuccess) + } + } + + private fun useLoginMethod(loginMethodId: Int, onSuccess: (usedMethodId: Int) -> Unit) { + // this should never be true + if (data.loginMethods.contains(loginMethodId)) { + onSuccess(-1) + return + } + Utils.d(TAG, "Using login method $loginMethodId") + when (loginMethodId) { + LOGIN_METHOD_MOBIDZIENNIK_WEB -> { + data.startProgress(R.string.edziennik_progress_login_mobidziennik_web) + MobidziennikLoginWeb(data) { onSuccess(loginMethodId) } + } + LOGIN_METHOD_MOBIDZIENNIK_API2 -> { + data.startProgress(R.string.edziennik_progress_login_mobidziennik_api2) + MobidziennikLoginApi2(data) { onSuccess(loginMethodId) } + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/login/MobidziennikLoginApi2.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/login/MobidziennikLoginApi2.kt new file mode 100644 index 00000000..9258886b --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/login/MobidziennikLoginApi2.kt @@ -0,0 +1,106 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-1-12. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.login + +import android.os.Build +import com.google.gson.JsonObject +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.callback.JsonCallbackHandler +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.JsonObject +import pl.szczodrzynski.edziennik.ext.getJsonObject +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty +import pl.szczodrzynski.edziennik.utils.Utils + +class MobidziennikLoginApi2(val data: DataMobidziennik, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "MobidziennikLoginApi2" + + fun getDevice(app: App) = JsonObject( + "available" to true, + "platform" to "Android", + "version" to Build.VERSION.RELEASE, + "uuid" to app.deviceId, + "cordova" to "7.1.2", + "model" to "${Build.MANUFACTURER} ${Build.MODEL}", + "manufacturer" to "Aplikacja Szkolny.eu", + "isVirtual" to false, + "serial" to try { System.getProperty("ro.serialno") ?: System.getProperty("ro.boot.serialno") } catch (_: Exception) { Build.UNKNOWN }, + "appVersion" to "10.6, 2020.01.09-12.15.53", + "pushRegistrationId" to app.config.sync.tokenMobidziennik + ) + } + + init { run { + if (data.isApi2LoginValid()) { + onSuccess() + } + else { + if (data.loginServerName.isNotNullNorEmpty() && data.loginEmail.isNotNullNorEmpty() && data.loginPassword.isNotNullNorEmpty()) { + loginWithCredentials() + } + else { + data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) + } + } + }} + + private fun loginWithCredentials() { + Utils.d(TAG, "Request: Mobidziennik/Login/Api2 - https://mobidziennik.pl/logowanie") + + val callback = object : JsonCallbackHandler() { + override fun onSuccess(json: JsonObject?, response: Response?) { + if (json == null) { + data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) + .withResponse(response)) + return + } + + json.getJsonObject("error")?.let { + val text = it.getString("type") ?: it.getString("message") + when (text) { + "LOGIN_ERROR" -> ERROR_LOGIN_MOBIDZIENNIK_API2_INVALID_LOGIN + // TODO other error types + else -> ERROR_LOGIN_MOBIDZIENNIK_API2_OTHER + }.let { errorCode -> + data.error(ApiError(TAG, errorCode) + .withApiResponse(text) + .withResponse(response)) + return + } + } + + data.loginEmail = json.getString("email") + data.globalId = json.getString("id_global") + data.loginId = json.getString("login") + onSuccess() + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(TAG, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + Request.builder() + .url("https://mobidziennik.pl/logowanie") + .userAgent(MOBIDZIENNIK_USER_AGENT) + .contentType("application/x-www-form-urlencoded; charset=UTF-8") + .addParameter("api2", true) + .addParameter("email", data.loginEmail) + .addParameter("haslo", data.loginPassword) + .addParameter("device", getDevice(data.app).toString()) + .post() + .callback(callback) + .build() + .enqueue() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/login/MobidziennikLoginWeb.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/login/MobidziennikLoginWeb.kt new file mode 100644 index 00000000..ce801a73 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/login/MobidziennikLoginWeb.kt @@ -0,0 +1,102 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.login + +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.callback.TextCallbackHandler +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.Mobidziennik +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.getUnixDate +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty +import pl.szczodrzynski.edziennik.utils.Utils.d + +class MobidziennikLoginWeb(val data: DataMobidziennik, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "MobidziennikLoginWeb" + } + + init { run { + if (data.isWebLoginValid()) { + onSuccess() + } + else { + if (data.loginServerName.isNotNullNorEmpty() && data.loginUsername.isNotNullNorEmpty() && data.loginPassword.isNotNullNorEmpty()) { + data.app.cookieJar.clear("${data.loginServerName}.mobidziennik.pl") + loginWithCredentials() + } + else { + data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) + } + } + }} + + private fun loginWithCredentials() { + d(TAG, "Request: Mobidziennik/Login/Web - https://${data.loginServerName}.mobidziennik.pl/api/") + + val callback = object : TextCallbackHandler() { + override fun onSuccess(text: String?, response: Response?) { + if (text != "ok") { + when { + text == "Nie jestes zalogowany" -> ERROR_LOGIN_MOBIDZIENNIK_WEB_INVALID_LOGIN + text == "ifun" -> ERROR_LOGIN_MOBIDZIENNIK_WEB_INVALID_DEVICE + text == "stare haslo" -> ERROR_LOGIN_MOBIDZIENNIK_WEB_OLD_PASSWORD + text == "Archiwum" -> ERROR_LOGIN_MOBIDZIENNIK_WEB_ARCHIVED + text == "Trwają prace techniczne lub pojawił się jakiś problem" -> ERROR_LOGIN_MOBIDZIENNIK_WEB_MAINTENANCE + text?.contains("Uuuups... nieprawidłowy adres") == true -> ERROR_LOGIN_MOBIDZIENNIK_WEB_INVALID_ADDRESS + text?.contains("przerwa techniczna") == true -> ERROR_LOGIN_MOBIDZIENNIK_WEB_MAINTENANCE + else -> ERROR_LOGIN_MOBIDZIENNIK_WEB_OTHER + }.let { errorCode -> + data.error(ApiError(TAG, errorCode) + .withApiResponse(text) + .withResponse(response)) + return + } + } + + val cookies = data.app.cookieJar.getAll("${data.loginServerName}.mobidziennik.pl") + val cookie = cookies.entries.firstOrNull { it.key.length > 32 } + val sessionKey = cookie?.key + val sessionId = cookie?.value + if (sessionId == null) { + data.error(ApiError(TAG, ERROR_LOGIN_MOBIDZIENNIK_WEB_NO_SESSION_ID) + .withResponse(response) + .withApiResponse(text)) + return + } + + data.webSessionKey = sessionKey + data.webSessionValue = sessionId + data.webServerId = data.app.cookieJar.get("${data.loginServerName}.mobidziennik.pl", "SERVERID") + data.webSessionIdExpiryTime = response.getUnixDate() + 45 * 60 /* 45min */ + onSuccess() + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(TAG, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + + Request.builder() + .url("https://${data.loginServerName}.mobidziennik.pl/api/") + .userAgent(MOBIDZIENNIK_USER_AGENT) + .contentType("application/x-www-form-urlencoded; charset=UTF-8") + .addParameter("wersja", "20") + .addParameter("ip", data.app.deviceId) + .addParameter("login", data.loginUsername) + .addParameter("haslo", data.loginPassword) + .addParameter("token", data.app.config.sync.tokenMobidziennik) + .addParameter("ta_api", Mobidziennik.API_KEY) + .post() + .callback(callback) + .build() + .enqueue() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/DataPodlasie.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/DataPodlasie.kt new file mode 100644 index 00000000..0a5cce84 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/DataPodlasie.kt @@ -0,0 +1,86 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-12 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie + +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_PODLASIE_API +import pl.szczodrzynski.edziennik.data.api.models.Data +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.crc32 +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty + +class DataPodlasie(app: App, profile: Profile?, loginStore: LoginStore) : Data(app, profile, loginStore) { + + fun isApiLoginValid() = apiToken.isNotNullNorEmpty() + + override fun satisfyLoginMethods() { + loginMethods.clear() + if (isApiLoginValid()) + loginMethods += LOGIN_METHOD_PODLASIE_API + } + + override fun generateUserCode(): String = "$schoolShortName:$loginShort:${studentId?.crc32()}" + + /* _ + /\ (_) + / \ _ __ _ + / /\ \ | '_ \| | + / ____ \| |_) | | + /_/ \_\ .__/|_| + | | + |*/ + private var mApiToken: String? = null + var apiToken: String? + get() { mApiToken = mApiToken ?: loginStore.getLoginData("apiToken", null); return mApiToken } + set(value) { loginStore.putLoginData("apiToken", value); mApiToken = value } + + private var mApiUrl: String? = null + var apiUrl: String? + get() { mApiUrl = mApiUrl ?: profile?.getStudentData("apiUrl", null); return mApiUrl } + set(value) { profile?.putStudentData("apiUrl", value) ?: return; mApiUrl = value } + + /* ____ _ _ + / __ \| | | | + | | | | |_| |__ ___ _ __ + | | | | __| '_ \ / _ \ '__| + | |__| | |_| | | | __/ | + \____/ \__|_| |_|\___|*/ + private var mStudentId: String? = null + var studentId: String? + get() { mStudentId = mStudentId ?: profile?.getStudentData("studentId", null); return mStudentId } + set(value) { profile?.putStudentData("studentId", value) ?: return; mStudentId = value } + + private var mStudentLogin: String? = null + var studentLogin: String? + get() { mStudentLogin = mStudentLogin ?: profile?.getStudentData("studentLogin", null); return mStudentLogin } + set(value) { profile?.putStudentData("studentLogin", value) ?: return; mStudentLogin = value } + + private var mSchoolName: String? = null + var schoolName: String? + get() { mSchoolName = mSchoolName ?: profile?.getStudentData("schoolName", null); return mSchoolName } + set(value) { profile?.putStudentData("schoolName", value) ?: return; mSchoolName = value } + + private var mClassName: String? = null + var className: String? + get() { mClassName = mClassName ?: profile?.getStudentData("className", null); return mClassName } + set(value) { profile?.putStudentData("className", value) ?: return; mClassName = value } + + private var mSchoolYear: String? = null + var schoolYear: String? + get() { mSchoolYear = mSchoolYear ?: profile?.getStudentData("schoolYear", null); return mSchoolYear } + set(value) { profile?.putStudentData("schoolYear", value) ?: return; mSchoolYear = value } + + private var mCurrentSemester: Int? = null + var currentSemester: Int + get() { mCurrentSemester = mCurrentSemester ?: profile?.getStudentData("currentSemester", 0); return mCurrentSemester ?: 0 } + set(value) { profile?.putStudentData("currentSemester", value) ?: return; mCurrentSemester = value } + + val schoolShortName: String? + get() = studentLogin?.split('@')?.get(1)?.replace(".podlaskie.pl", "") + + val loginShort: String? + get() = studentLogin?.split('@')?.get(0) +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/Podlasie.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/Podlasie.kt new file mode 100644 index 00000000..d7ec441f --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/Podlasie.kt @@ -0,0 +1,166 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-12 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie + +import com.google.gson.JsonObject +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.edziennik.helper.DownloadAttachment +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.data.PodlasieData +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.firstlogin.PodlasieFirstLogin +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.login.PodlasieLogin +import pl.szczodrzynski.edziennik.data.api.events.AttachmentGetEvent +import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikCallback +import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.api.podlasieLoginMethods +import pl.szczodrzynski.edziennik.data.api.prepare +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.data.db.full.AnnouncementFull +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.data.db.full.MessageFull +import pl.szczodrzynski.edziennik.utils.Utils +import java.io.File + +class Podlasie(val app: App, val profile: Profile?, val loginStore: LoginStore, val callback: EdziennikCallback) : EdziennikInterface { + companion object { + const val TAG = "Podlasie" + } + + val internalErrorList = mutableListOf() + val data: DataPodlasie + + init { + data = DataPodlasie(app, profile, loginStore).apply { + callback = wrapCallback(this@Podlasie.callback) + satisfyLoginMethods() + } + } + + private fun completed() { + data.saveData() + callback.onCompleted() + } + + /* _______ _ _ _ _ _ + |__ __| | /\ | | (_) | | | + | | | |__ ___ / \ | | __ _ ___ _ __ _| |_| |__ _ __ ___ + | | | '_ \ / _ \ / /\ \ | |/ _` |/ _ \| '__| | __| '_ \| '_ ` _ \ + | | | | | | __/ / ____ \| | (_| | (_) | | | | |_| | | | | | | | | + |_| |_| |_|\___| /_/ \_\_|\__, |\___/|_| |_|\__|_| |_|_| |_| |_| + __/ | + |__*/ + override fun sync(featureIds: List, viewId: Int?, onlyEndpoints: List?, arguments: JsonObject?) { + data.arguments = arguments + data.prepare(podlasieLoginMethods, PodlasieFeatures, featureIds, viewId, onlyEndpoints) + Utils.d(TAG, "LoginMethod IDs: ${data.targetLoginMethodIds}") + Utils.d(TAG, "Endpoint IDs: ${data.targetEndpointIds}") + PodlasieLogin(data) { + PodlasieData(data) { + completed() + } + } + } + + override fun getMessage(message: MessageFull) { + + } + + override fun sendMessage(recipients: List, subject: String, text: String) { + + } + + override fun markAllAnnouncementsAsRead() { + + } + + override fun getAnnouncement(announcement: AnnouncementFull) { + + } + + override fun getAttachment(owner: Any, attachmentId: Long, attachmentName: String) { + val fileUrl = attachmentName.substringAfter(":") + DownloadAttachment(fileUrl, + onSuccess = { file -> + val event = AttachmentGetEvent( + data.profileId, + owner, + attachmentId, + AttachmentGetEvent.TYPE_FINISHED, + file.absolutePath + ) + + val attachmentDataFile = File(Utils.getStorageDir(), ".${data.profileId}_${event.ownerId}_${event.attachmentId}") + Utils.writeStringToFile(attachmentDataFile, event.fileName) + + EventBus.getDefault().postSticky(event) + + completed() + }, + onProgress = { written, _ -> + val event = AttachmentGetEvent( + data.profileId, + owner, + attachmentId, + AttachmentGetEvent.TYPE_PROGRESS, + bytesWritten = written + ) + + EventBus.getDefault().postSticky(event) + }, + onError = { apiError -> + data.error(apiError) + }) + } + + override fun getRecipientList() { + + } + + override fun getEvent(eventFull: EventFull) { + + } + + override fun firstLogin() { + PodlasieFirstLogin(data) { + completed() + } + } + + override fun cancel() { + Utils.d(TAG, "Cancelled") + data.cancel() + } + + private fun wrapCallback(callback: EdziennikCallback): EdziennikCallback { + return object : EdziennikCallback { + override fun onCompleted() { + callback.onCompleted() + } + + override fun onProgress(step: Float) { + callback.onProgress(step) + } + + override fun onStartProgress(stringRes: Int) { + callback.onStartProgress(stringRes) + } + + override fun onError(apiError: ApiError) { + // TODO Error handling + when (apiError.errorCode) { + in internalErrorList -> { + // finish immediately if the same error occurs twice during the same sync + callback.onError(apiError) + } + else -> callback.onError(apiError) + } + } + + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/PodlasieFeatures.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/PodlasieFeatures.kt new file mode 100644 index 00000000..82c6f659 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/PodlasieFeatures.kt @@ -0,0 +1,18 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-12 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie + +import pl.szczodrzynski.edziennik.data.api.FEATURE_ALWAYS_NEEDED +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_PODLASIE_API +import pl.szczodrzynski.edziennik.data.api.LOGIN_TYPE_PODLASIE +import pl.szczodrzynski.edziennik.data.api.models.Feature + +const val ENDPOINT_PODLASIE_API_MAIN = 1001 + +val PodlasieFeatures = listOf( + Feature(LOGIN_TYPE_PODLASIE, FEATURE_ALWAYS_NEEDED, listOf( + ENDPOINT_PODLASIE_API_MAIN to LOGIN_METHOD_PODLASIE_API + ), listOf(LOGIN_METHOD_PODLASIE_API)) +) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/PodlasieApi.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/PodlasieApi.kt new file mode 100644 index 00000000..726b851a --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/PodlasieApi.kt @@ -0,0 +1,108 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-12 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.data + +import com.google.gson.JsonObject +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.RequestParams +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.callback.JsonCallbackHandler +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.DataPodlasie +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.getInt +import pl.szczodrzynski.edziennik.ext.getJsonObject +import pl.szczodrzynski.edziennik.ext.toHexString +import pl.szczodrzynski.edziennik.utils.Utils +import java.security.MessageDigest +import java.text.SimpleDateFormat +import java.util.* + +open class PodlasieApi(open val data: DataPodlasie, open val lastSync: Long?) { + companion object { + const val TAG = "PodlasieApi" + } + + val profileId + get() = data.profile?.id ?: -1 + + val profile + get() = data.profile + + fun apiGet(tag: String, endpoint: String, onSuccess: (json: JsonObject) -> Unit) { + val url = PODLASIE_API_URL + endpoint + + Utils.d(tag, "Request: Podlasie/Api - $url") + + if (data.apiToken == null) { + data.error(tag, ERROR_PODLASIE_API_NO_TOKEN) + return + } + + val callback = object : JsonCallbackHandler() { + override fun onSuccess(json: JsonObject?, response: Response?) { + if (json == null || response == null) { + data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) + .withResponse(response)) + return + } + + val error = json.getJsonObject("system_message")?.getInt("code") + + error?.let { code -> + when (code) { + 0 -> ERROR_PODLASIE_API_DATA_MISSING + 4 -> ERROR_LOGIN_PODLASIE_API_DEVICE_LIMIT + 5 -> ERROR_LOGIN_PODLASIE_API_INVALID_TOKEN + 200 -> null // Not an error + else -> ERROR_PODLASIE_API_OTHER + }?.let { errorCode -> + data.error(ApiError(tag, errorCode) + .withApiResponse(json) + .withResponse(response)) + return@onSuccess + } + } + + try { + onSuccess(json) + } catch (e: Exception) { + data.error(ApiError(tag, EXCEPTION_PODLASIE_API_REQUEST) + .withResponse(response) + .withThrowable(e) + .withApiResponse(json)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(tag, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + Request.builder() + .url(url) + .userAgent(SYSTEM_USER_AGENT) + .requestParams(RequestParams(mapOf( + "token" to data.apiToken, + "securityToken" to getSecurityToken(), + "mobileId" to data.app.deviceId, + "ver" to PODLASIE_API_VERSION + ))) + .callback(callback) + .build() + .enqueue() + } + + private fun getSecurityToken(): String { + val format = SimpleDateFormat("yyyy-MM-dd HH", Locale.ENGLISH) + .also { it.timeZone = TimeZone.getTimeZone("Europe/Warsaw") }.format(System.currentTimeMillis()) + val instance = MessageDigest.getInstance("SHA-256") + val digest = instance.digest("-EYlwYu8u16miVd8tT?oO7cvoUVQrQN0vr!$format".toByteArray()).toHexString() + val digest2 = instance.digest((data.apiToken ?: "").toByteArray()).toHexString() + return instance.digest("$digest$digest2".toByteArray()).toHexString() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/PodlasieData.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/PodlasieData.kt new file mode 100644 index 00000000..ce1197b8 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/PodlasieData.kt @@ -0,0 +1,49 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-12 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.data + +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.DataPodlasie +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.ENDPOINT_PODLASIE_API_MAIN +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.data.api.PodlasieApiMain +import pl.szczodrzynski.edziennik.utils.Utils + +class PodlasieData(val data: DataPodlasie, val onSuccess: () -> Unit) { + companion object { + const val TAG = "PodlasieData" + } + + init { + nextEndpoint(onSuccess) + } + + private fun nextEndpoint(onSuccess: () -> Unit) { + if (data.targetEndpointIds.isEmpty()) { + onSuccess() + return + } + if (data.cancelled) { + onSuccess() + return + } + val id = data.targetEndpointIds.firstKey() + val lastSync = data.targetEndpointIds.remove(id) + useEndpoint(id, lastSync) { + data.progress(data.progressStep) + nextEndpoint(onSuccess) + } + } + + private fun useEndpoint(endpointId: Int, lastSync: Long?, onSuccess: (endpointId: Int) -> Unit) { + Utils.d(TAG, "Using endpoint $endpointId. Last sync time = $lastSync") + when (endpointId) { + ENDPOINT_PODLASIE_API_MAIN -> { + data.startProgress(R.string.edziennik_progress_endpoint_data) + PodlasieApiMain(data, lastSync, onSuccess) + } + else -> onSuccess(endpointId) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiEvents.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiEvents.kt new file mode 100644 index 00000000..f51c7477 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiEvents.kt @@ -0,0 +1,76 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-13 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.data.api + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.DataPodlasie +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.ext.getLong +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time +import java.util.* + +class PodlasieApiEvents(val data: DataPodlasie, val rows: List) { + init { + rows.forEach { event -> + val id = event.getLong("ExternalId") ?: return@forEach + val date = event.getString("DateFrom")?.let { Date.fromY_m_d(it) } ?: return@forEach + val time = event.getString("DateFrom")?.let { Time.fromY_m_d_H_m_s(it) } + ?: return@forEach + + val name = event.getString("Name")?.replace(""", "\"") ?: "" + val description = event.getString("Description")?.replace(""", "\"") ?: "" + + val type = when (event.getString("Category")?.lowercase()) { + "klasówka" -> Event.TYPE_EXAM + "praca domowa" -> Event.TYPE_HOMEWORK + "wycieczka" -> Event.TYPE_EXCURSION + else -> Event.TYPE_DEFAULT + } + + val teacherFirstName = event.getString("PersonEnteringDataFirstName") ?: return@forEach + val teacherLastName = event.getString("PersonEnteringDataLastName") ?: return@forEach + val teacher = data.getTeacher(teacherFirstName, teacherLastName) + + val lessonList = data.db.timetableDao().getAllForDateNow(data.profileId, date) + val lesson = lessonList.firstOrNull { it.startTime == time } + + val addedDate = event.getString("CreateDate")?.let { Date.fromIso(it) } + ?: System.currentTimeMillis() + + val eventObject = Event( + profileId = data.profileId, + id = id, + date = date, + time = time, + topic = name, + color = null, + type = type, + teacherId = teacher.id, + subjectId = lesson?.subjectId ?: -1, + teamId = data.teamClass?.id ?: -1, + addedDate = addedDate + ).apply { + homeworkBody = description + isDownloaded = true + } + + data.eventList.add(eventObject) + data.metadataList.add( + Metadata( + data.profileId, + if (type == Event.TYPE_HOMEWORK) Metadata.TYPE_HOMEWORK else Metadata.TYPE_EVENT, + id, + data.profile?.empty ?: false, + data.profile?.empty ?: false + )) + } + + data.toRemove.add(DataRemoveModel.Events.future()) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiFinalGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiFinalGrades.kt new file mode 100644 index 00000000..94dadfc8 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiFinalGrades.kt @@ -0,0 +1,121 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-13 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.data.api + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.DataPodlasie +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Grade +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_SEMESTER1_FINAL +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_SEMESTER1_PROPOSED +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_SEMESTER2_FINAL +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_SEMESTER2_PROPOSED +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_YEAR_FINAL +import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_YEAR_PROPOSED +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.ext.getLong +import pl.szczodrzynski.edziennik.ext.getString + +class PodlasieApiFinalGrades(val data: DataPodlasie, val rows: List) { + init { data.profile?.also { profile -> + rows.forEach { grade -> + val id = grade.getLong("ExternalId") ?: return@forEach + val mark = grade.getString("Mark") ?: return@forEach + val proposedMark = grade.getString("ProposedMark") ?: "0" + val name = data.app.gradesManager.getGradeNumberName(mark) + val value = data.app.gradesManager.getGradeValue(name) + val semester = grade.getString("TermShortcut")?.length ?: return@forEach + + val typeName = grade.getString("Type") ?: return@forEach + val type = when (typeName) { + "S" -> if (semester == 1) TYPE_SEMESTER1_FINAL else TYPE_SEMESTER2_FINAL + "Y", "R" -> TYPE_YEAR_FINAL + else -> return@forEach + } + + val subjectName = grade.getString("SchoolSubject") ?: return@forEach + val subject = data.getSubject(null, subjectName) + + val addedDate = if (profile.empty) profile.getSemesterStart(semester).inMillis + else System.currentTimeMillis() + + val gradeObject = Grade( + profileId = data.profileId, + id = id, + name = name, + type = type, + value = value, + weight = 0f, + color = -1, + category = null, + description = null, + comment = null, + semester = semester, + teacherId = -1, + subjectId = subject.id, + addedDate = addedDate + ) + + data.gradeList.add(gradeObject) + data.metadataList.add( + Metadata( + data.profileId, + Metadata.TYPE_GRADE, + id, + profile.empty, + profile.empty + )) + + if (proposedMark != "0") { + val proposedName = data.app.gradesManager.getGradeNumberName(proposedMark) + val proposedValue = data.app.gradesManager.getGradeValue(proposedName) + + val proposedType = when (typeName) { + "S" -> if (semester == 1) TYPE_SEMESTER1_PROPOSED else TYPE_SEMESTER2_PROPOSED + "Y", "R" -> TYPE_YEAR_PROPOSED + else -> return@forEach + } + + val proposedGradeObject = Grade( + profileId = data.profileId, + id = id * (-1), + name = proposedName, + type = proposedType, + value = proposedValue, + weight = 0f, + color = -1, + category = null, + description = null, + comment = null, + semester = semester, + teacherId = -1, + subjectId = subject.id, + addedDate = addedDate + ) + + data.gradeList.add(proposedGradeObject) + data.metadataList.add( + Metadata( + data.profileId, + Metadata.TYPE_GRADE, + proposedGradeObject.id, + profile.empty, + profile.empty + )) + } + } + + data.toRemove.addAll(listOf( + TYPE_SEMESTER1_FINAL, + TYPE_SEMESTER1_PROPOSED, + TYPE_SEMESTER2_FINAL, + TYPE_SEMESTER2_PROPOSED, + TYPE_YEAR_FINAL, + TYPE_YEAR_PROPOSED + ).map { + DataRemoveModel.Grades.allWithType(it) + }) + }} +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiGrades.kt new file mode 100644 index 00000000..4aa749ef --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiGrades.kt @@ -0,0 +1,72 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-13 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.data.api + +import android.graphics.Color +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.DataPodlasie +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Grade +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.ext.getFloat +import pl.szczodrzynski.edziennik.ext.getInt +import pl.szczodrzynski.edziennik.ext.getLong +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.utils.models.Date + +class PodlasieApiGrades(val data: DataPodlasie, val rows: List) { + init { + rows.forEach { grade -> + val id = grade.getLong("ExternalId") ?: return@forEach + val name = grade.getString("Mark") ?: return@forEach + val value = data.app.gradesManager.getGradeValue(name) + val weight = grade.getFloat("Weight") ?: 0f + val includeToAverage = grade.getInt("IncludeToAverage") != 0 + val color = grade.getString("Color")?.let { Color.parseColor(it) } ?: -1 + val category = grade.getString("Category") ?: "" + val comment = grade.getString("Comment") ?: "" + val semester = grade.getString("TermShortcut")?.length ?: data.currentSemester + + val teacherFirstName = grade.getString("TeacherFirstName") ?: return@forEach + val teacherLastName = grade.getString("TeacherLastName") ?: return@forEach + val teacher = data.getTeacher(teacherFirstName, teacherLastName) + + val subjectName = grade.getString("SchoolSubject") ?: return@forEach + val subject = data.getSubject(null, subjectName) + + val addedDate = grade.getString("ReceivedDate")?.let { Date.fromY_m_d(it).inMillis } + ?: System.currentTimeMillis() + + val gradeObject = Grade( + profileId = data.profileId, + id = id, + name = name, + type = Grade.TYPE_NORMAL, + value = value, + weight = if (includeToAverage) weight else 0f, + color = color, + category = category, + description = null, + comment = comment, + semester = semester, + teacherId = teacher.id, + subjectId = subject.id, + addedDate = addedDate + ) + + data.gradeList.add(gradeObject) + data.metadataList.add( + Metadata( + data.profileId, + Metadata.TYPE_GRADE, + id, + data.profile?.empty ?: false, + data.profile?.empty ?: false + )) + } + + data.toRemove.add(DataRemoveModel.Grades.allWithType(Grade.TYPE_NORMAL)) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiHomework.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiHomework.kt new file mode 100644 index 00000000..be2fd062 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiHomework.kt @@ -0,0 +1,65 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-14 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.data.api + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.DataPodlasie +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.ext.crc32 +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.utils.models.Date + +class PodlasieApiHomework(val data: DataPodlasie, val rows: List) { + init { + rows.reversed().forEach { homework -> + val id = homework.getString("ExternalId")?.crc32() ?: return@forEach + val topic = homework.getString("Title")?.replace(""", "\"") ?: "" + val description = homework.getString("Message")?.replace(""", "\"") ?: "" + val date = Date.getToday() + val addedDate = System.currentTimeMillis() + + val eventObject = Event( + profileId = data.profileId, + id = id, + date = date, + time = null, + topic = topic, + color = null, + type = Event.TYPE_HOMEWORK, + teacherId = -1, + subjectId = -1, + teamId = data.teamClass?.id ?: -1, + addedDate = addedDate + ).apply { + homeworkBody = description + isDownloaded = true + } + + eventObject.attachmentIds = mutableListOf() + eventObject.attachmentNames = mutableListOf() + homework.getString("Attachments")?.split(',')?.onEach { url -> + val filename = "&filename=(.*?)&".toRegex().find(url)?.get(1) ?: return@onEach + val ext = "&ext=(.*?)&".toRegex().find(url)?.get(1) ?: return@onEach + eventObject.attachmentIds?.add(url.crc32()) + eventObject.attachmentNames?.add("$filename.$ext:$url") + } + + data.eventList.add(eventObject) + data.metadataList.add( + Metadata( + data.profileId, + Metadata.TYPE_HOMEWORK, + id, + data.profile?.empty ?: false, + data.profile?.empty ?: false + )) + } + + data.toRemove.add(DataRemoveModel.Events.futureWithType(Event.TYPE_HOMEWORK)) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiLuckyNumber.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiLuckyNumber.kt new file mode 100644 index 00000000..725ec727 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiLuckyNumber.kt @@ -0,0 +1,30 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-13 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.data.api + +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.DataPodlasie +import pl.szczodrzynski.edziennik.data.db.entity.LuckyNumber +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.utils.models.Date + +class PodlasieApiLuckyNumber(val data: DataPodlasie, val luckyNumber: Int) { + init { + val luckyNumberObject = LuckyNumber( + profileId = data.profileId, + date = Date.getToday(), + number = luckyNumber + ) + + data.luckyNumberList.add(luckyNumberObject) + data.metadataList.add( + Metadata( + data.profileId, + Metadata.TYPE_LUCKY_NUMBER, + luckyNumberObject.date.value.toLong(), + true, + data.profile?.empty ?: false + )) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiMain.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiMain.kt new file mode 100644 index 00000000..bf9379b3 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiMain.kt @@ -0,0 +1,45 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-12 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.data.api + +import pl.szczodrzynski.edziennik.data.api.PODLASIE_API_USER_ENDPOINT +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.DataPodlasie +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.ENDPOINT_PODLASIE_API_MAIN +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.data.PodlasieApi +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.asJsonObjectList +import pl.szczodrzynski.edziennik.ext.getInt +import pl.szczodrzynski.edziennik.ext.getJsonArray + +class PodlasieApiMain(override val data: DataPodlasie, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit) : PodlasieApi(data, lastSync) { + companion object { + const val TAG = "PodlasieApiTimetable" + } + + init { + apiGet(TAG, PODLASIE_API_USER_ENDPOINT) { json -> + // Save the class team when it doesn't exist. + data.getTeam( + id = null, + name = data.className ?: "", + schoolCode = data.schoolShortName ?: "", + isTeamClass = true + ) + + json.getInt("LuckyNumber")?.let { PodlasieApiLuckyNumber(data, it) } + json.getJsonArray("Teacher")?.asJsonObjectList()?.let { PodlasieApiTeachers(data, it) } + json.getJsonArray("Timetable")?.asJsonObjectList()?.let { PodlasieApiTimetable(data, it) } + json.getJsonArray("Marks")?.asJsonObjectList()?.let { PodlasieApiGrades(data, it) } + json.getJsonArray("MarkFinal")?.asJsonObjectList()?.let { PodlasieApiFinalGrades(data, it) } + json.getJsonArray("News")?.asJsonObjectList()?.let { PodlasieApiEvents(data, it) } + json.getJsonArray("Tasks")?.asJsonObjectList()?.let { PodlasieApiHomework(data, it) } + + data.setSyncNext(ENDPOINT_PODLASIE_API_MAIN, SYNC_ALWAYS) + onSuccess(ENDPOINT_PODLASIE_API_MAIN) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiTeachers.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiTeachers.kt new file mode 100644 index 00000000..f4769169 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiTeachers.kt @@ -0,0 +1,40 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-13 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.data.api + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.DataPodlasie +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.ext.getInt +import pl.szczodrzynski.edziennik.ext.getLong +import pl.szczodrzynski.edziennik.ext.getString + +class PodlasieApiTeachers(val data: DataPodlasie, val rows: List) { + init { + rows.forEach { teacher -> + val id = teacher.getLong("ExternalId") ?: return@forEach + val firstName = teacher.getString("FirstName") ?: return@forEach + val lastName = teacher.getString("LastName") ?: return@forEach + val isEducator = teacher.getInt("Educator") == 1 + + val teacherObject = Teacher( + profileId = data.profileId, + id = id, + name = firstName, + surname = lastName, + loginId = null + ) + + data.teacherList.put(id, teacherObject) + + val teamClass = data.teamClass + if (isEducator && teamClass != null) { + data.teamList.put(teamClass.id, teamClass.apply { + teacherId = id + }) + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiTimetable.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiTimetable.kt new file mode 100644 index 00000000..8c95d054 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/data/api/PodlasieApiTimetable.kt @@ -0,0 +1,96 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-12 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.data.api + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.DataPodlasie +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Lesson +import pl.szczodrzynski.edziennik.ext.getInt +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time +import pl.szczodrzynski.edziennik.utils.models.Week + +class PodlasieApiTimetable(val data: DataPodlasie, rows: List) { + init { + val currentWeekStart = Week.getWeekStart() + + if (Date.getToday().weekDay > 4) { + currentWeekStart.stepForward(0, 0, 7) + } + + val getDate = data.arguments?.getString("weekStart") ?: currentWeekStart.stringY_m_d + + val weekStart = Date.fromY_m_d(getDate) + val weekEnd = weekStart.clone().stepForward(0, 0, 6) + + val days = mutableListOf() + var startDate: Date? = null + var endDate: Date? = null + + rows.forEach { lesson -> + val date = lesson.getString("Date")?.let { Date.fromY_m_d(it) } ?: return@forEach + + if ((date > weekEnd || date < weekStart) && data.profile?.empty != true) return@forEach + if (startDate == null) startDate = date.clone() + endDate = date.clone() + if (date.value !in days) days += date.value + + val lessonNumber = lesson.getInt("LessonNumber") ?: return@forEach + val startTime = lesson.getString("TimeFrom")?.let { Time.fromH_m_s(it) } + ?: return@forEach + val endTime = lesson.getString("TimeTo")?.let { Time.fromH_m_s(it) } ?: return@forEach + val subject = lesson.getString("SchoolSubject")?.let { data.getSubject(null, it) } + ?: return@forEach + + val teacherFirstName = lesson.getString("TeacherFirstName") ?: return@forEach + val teacherLastName = lesson.getString("TeacherLastName") ?: return@forEach + val teacher = data.getTeacher(teacherFirstName, teacherLastName) + + val team = lesson.getString("Group")?.let { + data.getTeam( + id = null, + name = it, + schoolCode = data.schoolShortName ?: "", + isTeamClass = it == "cała klasa" + ) + } ?: return@forEach + val classroom = lesson.getString("Room") + + Lesson(data.profileId, -1).also { + it.type = Lesson.TYPE_NORMAL + it.date = date + it.lessonNumber = lessonNumber + it.startTime = startTime + it.endTime = endTime + it.subjectId = subject.id + it.teacherId = teacher.id + it.teamId = team.id + it.classroom = classroom + + it.id = it.buildId() + data.lessonList += it + } + } + + if (startDate != null && endDate != null) { + if (weekEnd > endDate!!) endDate = weekEnd + + while (startDate!! <= endDate!!) { + if (startDate!!.value !in days) { + val lessonDate = startDate!!.clone() + data.lessonList += Lesson(data.profileId, lessonDate.value.toLong()).apply { + type = Lesson.TYPE_NO_LESSONS + date = lessonDate + } + } + startDate!!.stepForward(0, 0, 1) + } + } + + data.toRemove.add(DataRemoveModel.Timetable.between(weekStart, weekEnd)) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/firstlogin/PodlasieFirstLogin.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/firstlogin/PodlasieFirstLogin.kt new file mode 100644 index 00000000..a99ea2ee --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/firstlogin/PodlasieFirstLogin.kt @@ -0,0 +1,87 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-12 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.firstlogin + +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.data.api.LOGIN_TYPE_PODLASIE +import pl.szczodrzynski.edziennik.data.api.PODLASIE_API_LOGOUT_DEVICES_ENDPOINT +import pl.szczodrzynski.edziennik.data.api.PODLASIE_API_USER_ENDPOINT +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.DataPodlasie +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.data.PodlasieApi +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.login.PodlasieLoginApi +import pl.szczodrzynski.edziennik.data.api.events.FirstLoginFinishedEvent +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.fixName +import pl.szczodrzynski.edziennik.ext.getShortName +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.ext.set + +class PodlasieFirstLogin(val data: DataPodlasie, val onSuccess: () -> Unit) { + companion object { + const val TAG = "PodlasieFirstLogin" + } + + private val api = PodlasieApi(data, null) + + init { + PodlasieLoginApi(data) { + doLogin() + } + } + + private fun doLogin() { + val loginStoreId = data.loginStore.id + val loginStoreType = LOGIN_TYPE_PODLASIE + + if (data.loginStore.getLoginData("logoutDevices", false)) { + data.loginStore.removeLoginData("logoutDevices") + api.apiGet(TAG, PODLASIE_API_LOGOUT_DEVICES_ENDPOINT) { + doLogin() + } + return + } + + api.apiGet(TAG, PODLASIE_API_USER_ENDPOINT) { json -> + val uuid = json.getString("Uuid") + val login = json.getString("Login") + val firstName = json.getString("FirstName") + val lastName = json.getString("LastName") + val studentNameLong = "$firstName $lastName".fixName() + val studentNameShort = studentNameLong.getShortName() + val schoolName = json.getString("SchoolName") + val className = json.getString("SchoolClass") + val schoolYear = json.getString("ActualSchoolYear")?.replace(' ', '/') + val semester = json.getString("ActualTermShortcut")?.length + val apiUrl = json.getString("URL") + + val profile = Profile( + loginStoreId, + loginStoreId, + loginStoreType, + studentNameLong, + login, + studentNameLong, + studentNameShort, + null + ).apply { + studentData["studentId"] = uuid + studentData["studentLogin"] = login + studentData["schoolName"] = schoolName + studentData["className"] = className + studentData["schoolYear"] = schoolYear + studentData["currentSemester"] = semester ?: 1 + studentData["apiUrl"] = apiUrl + + schoolYear?.split('/')?.get(0)?.toInt()?.let { + studentSchoolYearStart = it + } + studentClassName = className + } + + EventBus.getDefault().postSticky(FirstLoginFinishedEvent(listOf(profile), data.loginStore)) + onSuccess() + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/login/PodlasieLogin.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/login/PodlasieLogin.kt new file mode 100644 index 00000000..406bb997 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/login/PodlasieLogin.kt @@ -0,0 +1,54 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-12 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.login + +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_PODLASIE_API +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.DataPodlasie +import pl.szczodrzynski.edziennik.utils.Utils + +class PodlasieLogin(val data: DataPodlasie, val onSuccess: () -> Unit) { + companion object { + const val TAG = "PodlasieLogin" + } + + private var cancelled = false + + init { + nextLoginMethod(onSuccess) + } + + private fun nextLoginMethod(onSuccess: () -> Unit) { + if (data.targetLoginMethodIds.isEmpty()) { + onSuccess() + return + } + if (cancelled) { + onSuccess() + return + } + useLoginMethod(data.targetLoginMethodIds.removeAt(0)) { usedMethodId -> + data.progress(data.progressStep) + if (usedMethodId != -1) + data.loginMethods.add(usedMethodId) + nextLoginMethod(onSuccess) + } + } + + private fun useLoginMethod(loginMethodId: Int, onSuccess: (usedMethodId: Int) -> Unit) { + // this should never be true + if (data.loginMethods.contains(loginMethodId)) { + onSuccess(-1) + return + } + Utils.d(TAG, "Using login method $loginMethodId") + when (loginMethodId) { + LOGIN_METHOD_PODLASIE_API -> { + data.startProgress(R.string.edziennik_progress_login_podlasie_api) + PodlasieLoginApi(data) { onSuccess(loginMethodId) } + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/login/PodlasieLoginApi.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/login/PodlasieLoginApi.kt new file mode 100644 index 00000000..6eb70d06 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/login/PodlasieLoginApi.kt @@ -0,0 +1,23 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-5-12 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.login + +import pl.szczodrzynski.edziennik.data.api.ERROR_LOGIN_DATA_MISSING +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.DataPodlasie +import pl.szczodrzynski.edziennik.data.api.models.ApiError + +class PodlasieLoginApi(val data: DataPodlasie, val onSuccess: () -> Unit) { + companion object { + const val TAG = "PodlasieLoginApi" + } + + init { run { + if (data.isApiLoginValid()) { + onSuccess() + } else { + data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) + } + }} +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/DataTemplate.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/DataTemplate.kt new file mode 100644 index 00000000..17644978 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/DataTemplate.kt @@ -0,0 +1,71 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.template + +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_TEMPLATE_API +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_TEMPLATE_WEB +import pl.szczodrzynski.edziennik.data.api.models.Data +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.currentTimeUnix +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty + +/** + * Use http://patorjk.com/software/taag/#p=display&f=Big for the ascii art + * + * Use https://codepen.io/kubasz/pen/RwwwbGN to easily generate the student data getters/setters + */ +class DataTemplate(app: App, profile: Profile?, loginStore: LoginStore) : Data(app, profile, loginStore) { + + fun isWebLoginValid() = webExpiryTime-30 > currentTimeUnix() && webCookie.isNotNullNorEmpty() + fun isApiLoginValid() = apiExpiryTime-30 > currentTimeUnix() && apiToken.isNotNullNorEmpty() + + override fun satisfyLoginMethods() { + loginMethods.clear() + if (isWebLoginValid()) { + loginMethods += LOGIN_METHOD_TEMPLATE_WEB + app.cookieJar.set("eregister.example.com", "AuthCookie", webCookie) + } + if (isApiLoginValid()) + loginMethods += LOGIN_METHOD_TEMPLATE_API + } + + override fun generateUserCode() = "TEMPLATE:DO_NOT_USE" + + /* __ __ _ + \ \ / / | | + \ \ /\ / /__| |__ + \ \/ \/ / _ \ '_ \ + \ /\ / __/ |_) | + \/ \/ \___|_._*/ + private var mWebCookie: String? = null + var webCookie: String? + get() { mWebCookie = mWebCookie ?: profile?.getStudentData("webCookie", null); return mWebCookie } + set(value) { profile?.putStudentData("webCookie", value) ?: return; mWebCookie = value } + + private var mWebExpiryTime: Long? = null + var webExpiryTime: Long + get() { mWebExpiryTime = mWebExpiryTime ?: profile?.getStudentData("webExpiryTime", 0L); return mWebExpiryTime ?: 0L } + set(value) { profile?.putStudentData("webExpiryTime", value) ?: return; mWebExpiryTime = value } + + /* _ + /\ (_) + / \ _ __ _ + / /\ \ | '_ \| | + / ____ \| |_) | | + /_/ \_\ .__/|_| + | | + |*/ + private var mApiToken: String? = null + var apiToken: String? + get() { mApiToken = mApiToken ?: profile?.getStudentData("apiToken", null); return mApiToken } + set(value) { profile?.putStudentData("apiToken", value) ?: return; mApiToken = value } + + private var mApiExpiryTime: Long? = null + var apiExpiryTime: Long + get() { mApiExpiryTime = mApiExpiryTime ?: profile?.getStudentData("apiExpiryTime", 0L); return mApiExpiryTime ?: 0L } + set(value) { profile?.putStudentData("apiExpiryTime", value) ?: return; mApiExpiryTime = value } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/Template.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/Template.kt new file mode 100644 index 00000000..843d36e9 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/Template.kt @@ -0,0 +1,135 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.template + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.CODE_INTERNAL_LIBRUS_ACCOUNT_410 +import pl.szczodrzynski.edziennik.data.api.edziennik.template.data.TemplateData +import pl.szczodrzynski.edziennik.data.api.edziennik.template.firstlogin.TemplateFirstLogin +import pl.szczodrzynski.edziennik.data.api.edziennik.template.login.TemplateLogin +import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikCallback +import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.api.prepare +import pl.szczodrzynski.edziennik.data.api.templateLoginMethods +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.data.db.full.AnnouncementFull +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.data.db.full.MessageFull +import pl.szczodrzynski.edziennik.utils.Utils.d + +class Template(val app: App, val profile: Profile?, val loginStore: LoginStore, val callback: EdziennikCallback) : EdziennikInterface { + companion object { + private const val TAG = "Template" + } + + val internalErrorList = mutableListOf() + val data: DataTemplate + + init { + data = DataTemplate(app, profile, loginStore).apply { + callback = wrapCallback(this@Template.callback) + satisfyLoginMethods() + } + } + + private fun completed() { + data.saveData() + callback.onCompleted() + } + + /* _______ _ _ _ _ _ + |__ __| | /\ | | (_) | | | + | | | |__ ___ / \ | | __ _ ___ _ __ _| |_| |__ _ __ ___ + | | | '_ \ / _ \ / /\ \ | |/ _` |/ _ \| '__| | __| '_ \| '_ ` _ \ + | | | | | | __/ / ____ \| | (_| | (_) | | | | |_| | | | | | | | | + |_| |_| |_|\___| /_/ \_\_|\__, |\___/|_| |_|\__|_| |_|_| |_| |_| + __/ | + |__*/ + override fun sync(featureIds: List, viewId: Int?, onlyEndpoints: List?, arguments: JsonObject?) { + data.arguments = arguments + data.prepare(templateLoginMethods, TemplateFeatures, featureIds, viewId, onlyEndpoints) + d(TAG, "LoginMethod IDs: ${data.targetLoginMethodIds}") + d(TAG, "Endpoint IDs: ${data.targetEndpointIds}") + TemplateLogin(data) { + TemplateData(data) { + completed() + } + } + } + + override fun getMessage(message: MessageFull) { + + } + + override fun sendMessage(recipients: List, subject: String, text: String) { + + } + + override fun markAllAnnouncementsAsRead() { + + } + + override fun getAnnouncement(announcement: AnnouncementFull) { + + } + + override fun getAttachment(owner: Any, attachmentId: Long, attachmentName: String) { + + } + + override fun getRecipientList() { + + } + + override fun getEvent(eventFull: EventFull) { + + } + + override fun firstLogin() { + TemplateFirstLogin(data) { + completed() + } + } + + override fun cancel() { + d(TAG, "Cancelled") + data.cancel() + } + + private fun wrapCallback(callback: EdziennikCallback): EdziennikCallback { + return object : EdziennikCallback { + override fun onCompleted() { + callback.onCompleted() + } + + override fun onProgress(step: Float) { + callback.onProgress(step) + } + + override fun onStartProgress(stringRes: Int) { + callback.onStartProgress(stringRes) + } + + override fun onError(apiError: ApiError) { + when (apiError.errorCode) { + in internalErrorList -> { + // finish immediately if the same error occurs twice during the same sync + callback.onError(apiError) + } + CODE_INTERNAL_LIBRUS_ACCOUNT_410 -> { + internalErrorList.add(apiError.errorCode) + loginStore.removeLoginData("refreshToken") // force a clean login + //loginLibrus() + } + else -> callback.onError(apiError) + } + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/TemplateFeatures.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/TemplateFeatures.kt new file mode 100644 index 00000000..c12e2bcc --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/TemplateFeatures.kt @@ -0,0 +1,24 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-11. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.template + +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.models.Feature + +const val ENDPOINT_TEMPLATE_WEB_SAMPLE = 9991 +const val ENDPOINT_TEMPLATE_WEB_SAMPLE_2 = 9992 +const val ENDPOINT_TEMPLATE_API_SAMPLE = 9993 + +val TemplateFeatures = listOf( + Feature(LOGIN_TYPE_TEMPLATE, FEATURE_STUDENT_INFO, listOf( + ENDPOINT_TEMPLATE_WEB_SAMPLE to LOGIN_METHOD_TEMPLATE_WEB + ), listOf(LOGIN_METHOD_TEMPLATE_WEB)), + Feature(LOGIN_TYPE_TEMPLATE, FEATURE_SCHOOL_INFO, listOf( + ENDPOINT_TEMPLATE_WEB_SAMPLE_2 to LOGIN_METHOD_TEMPLATE_WEB + ), listOf(LOGIN_METHOD_TEMPLATE_WEB)), + Feature(LOGIN_TYPE_TEMPLATE, FEATURE_GRADES, listOf( + ENDPOINT_TEMPLATE_API_SAMPLE to LOGIN_METHOD_TEMPLATE_API + ), listOf(LOGIN_METHOD_TEMPLATE_API)) +) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/TemplateApi.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/TemplateApi.kt new file mode 100644 index 00000000..69e8f654 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/TemplateApi.kt @@ -0,0 +1,46 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.template.data + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.data.api.ERROR_TEMPLATE_WEB_OTHER +import pl.szczodrzynski.edziennik.data.api.GET +import pl.szczodrzynski.edziennik.data.api.edziennik.template.DataTemplate +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.currentTimeUnix + +open class TemplateApi(open val data: DataTemplate, open val lastSync: Long?) { + companion object { + private const val TAG = "TemplateApi" + } + + val profileId + get() = data.profile?.id ?: -1 + + val profile + get() = data.profile + + /** + * This will be used by all TemplateApi* endpoints. + * + * You can customize this method's parameters to best fit the implemented e-register. + * Just make sure that [tag] and [onSuccess] is present. + */ + @Suppress("UNUSED_PARAMETER") + fun apiGet(tag: String, endpoint: String, method: Int = GET, payload: JsonObject? = null, onSuccess: (json: JsonObject?) -> Unit) { + val json = JsonObject() + json.addProperty("foo", "bar") + json.addProperty("sample", "text") + + if (currentTimeUnix() % 4L == 0L) { + // let's set a 25% chance of error, just as a test + data.error(ApiError(tag, ERROR_TEMPLATE_WEB_OTHER) + .withApiResponse("404 Not Found - this is the text returned by the API")) + return + } + + onSuccess(json) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/TemplateData.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/TemplateData.kt new file mode 100644 index 00000000..3489555f --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/TemplateData.kt @@ -0,0 +1,61 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.template.data + +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.api.edziennik.template.DataTemplate +import pl.szczodrzynski.edziennik.data.api.edziennik.template.ENDPOINT_TEMPLATE_API_SAMPLE +import pl.szczodrzynski.edziennik.data.api.edziennik.template.ENDPOINT_TEMPLATE_WEB_SAMPLE +import pl.szczodrzynski.edziennik.data.api.edziennik.template.ENDPOINT_TEMPLATE_WEB_SAMPLE_2 +import pl.szczodrzynski.edziennik.data.api.edziennik.template.data.api.TemplateApiSample +import pl.szczodrzynski.edziennik.data.api.edziennik.template.data.web.TemplateWebSample +import pl.szczodrzynski.edziennik.data.api.edziennik.template.data.web.TemplateWebSample2 +import pl.szczodrzynski.edziennik.utils.Utils + +class TemplateData(val data: DataTemplate, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "TemplateData" + } + + init { + nextEndpoint(onSuccess) + } + + private fun nextEndpoint(onSuccess: () -> Unit) { + if (data.targetEndpointIds.isEmpty()) { + onSuccess() + return + } + if (data.cancelled) { + onSuccess() + return + } + val id = data.targetEndpointIds.firstKey() + val lastSync = data.targetEndpointIds.remove(id) + useEndpoint(id, lastSync) { endpointId -> + data.progress(data.progressStep) + nextEndpoint(onSuccess) + } + } + + private fun useEndpoint(endpointId: Int, lastSync: Long?, onSuccess: (endpointId: Int) -> Unit) { + Utils.d(TAG, "Using endpoint $endpointId. Last sync time = $lastSync") + when (endpointId) { + ENDPOINT_TEMPLATE_WEB_SAMPLE -> { + data.startProgress(R.string.edziennik_progress_endpoint_student_info) + TemplateWebSample(data, lastSync, onSuccess) + } + ENDPOINT_TEMPLATE_WEB_SAMPLE_2 -> { + data.startProgress(R.string.edziennik_progress_endpoint_school_info) + TemplateWebSample2(data, lastSync, onSuccess) + } + ENDPOINT_TEMPLATE_API_SAMPLE -> { + data.startProgress(R.string.edziennik_progress_endpoint_grades) + TemplateApiSample(data, lastSync, onSuccess) + } + else -> onSuccess(endpointId) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/TemplateWeb.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/TemplateWeb.kt new file mode 100644 index 00000000..2db8c41b --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/TemplateWeb.kt @@ -0,0 +1,46 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.template.data + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.data.api.ERROR_TEMPLATE_WEB_OTHER +import pl.szczodrzynski.edziennik.data.api.GET +import pl.szczodrzynski.edziennik.data.api.edziennik.template.DataTemplate +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.currentTimeUnix + +open class TemplateWeb(open val data: DataTemplate, open val lastSync: Long?) { + companion object { + private const val TAG = "TemplateWeb" + } + + val profileId + get() = data.profile?.id ?: -1 + + val profile + get() = data.profile + + /** + * This will be used by all TemplateWeb* endpoints. + * + * You can customize this method's parameters to best fit the implemented e-register. + * Just make sure that [tag] and [onSuccess] is present. + */ + @Suppress("UNUSED_PARAMETER") + fun webGet(tag: String, endpoint: String, method: Int = GET, payload: JsonObject? = null, onSuccess: (json: JsonObject?) -> Unit) { + val json = JsonObject() + json.addProperty("foo", "bar") + json.addProperty("sample", "text") + + if (currentTimeUnix() % 4L == 0L) { + // let's set a 25% chance of error, just as a test + data.error(ApiError(tag, ERROR_TEMPLATE_WEB_OTHER) + .withApiResponse("404 Not Found - this is the text returned by the API")) + return + } + + onSuccess(json) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/api/TemplateApiSample.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/api/TemplateApiSample.kt new file mode 100644 index 00000000..d61dc8f9 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/api/TemplateApiSample.kt @@ -0,0 +1,41 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.template.data.api + +import pl.szczodrzynski.edziennik.MainActivity +import pl.szczodrzynski.edziennik.data.api.edziennik.template.DataTemplate +import pl.szczodrzynski.edziennik.data.api.edziennik.template.ENDPOINT_TEMPLATE_API_SAMPLE +import pl.szczodrzynski.edziennik.data.api.edziennik.template.data.TemplateApi +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.DAY + +class TemplateApiSample(override val data: DataTemplate, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : TemplateApi(data, lastSync) { + companion object { + private const val TAG = "TemplateApiSample" + } + + init { + apiGet(TAG, "/api/v3/getData.php") { _ -> + // here you can access and update any fields of the `data` object + + // ================ + // schedule a sync: + + // not sooner than two days later + data.setSyncNext(ENDPOINT_TEMPLATE_API_SAMPLE, 2 * DAY) + // in two days OR on explicit "grades" sync + data.setSyncNext(ENDPOINT_TEMPLATE_API_SAMPLE, 2 * DAY, MainActivity.DRAWER_ITEM_GRADES) + // only if sync is executed on Home view + data.setSyncNext(ENDPOINT_TEMPLATE_API_SAMPLE, syncIn = null, viewId = MainActivity.DRAWER_ITEM_HOME) + // always, in every sync + data.setSyncNext(ENDPOINT_TEMPLATE_API_SAMPLE, SYNC_ALWAYS) + + onSuccess(ENDPOINT_TEMPLATE_API_SAMPLE) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/web/TemplateWebSample.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/web/TemplateWebSample.kt new file mode 100644 index 00000000..0732710a --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/web/TemplateWebSample.kt @@ -0,0 +1,42 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.template.data.web + +import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_GRADES +import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_HOME +import pl.szczodrzynski.edziennik.data.api.edziennik.template.DataTemplate +import pl.szczodrzynski.edziennik.data.api.edziennik.template.ENDPOINT_TEMPLATE_WEB_SAMPLE +import pl.szczodrzynski.edziennik.data.api.edziennik.template.data.TemplateWeb +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.DAY + +class TemplateWebSample(override val data: DataTemplate, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : TemplateWeb(data, lastSync) { + companion object { + private const val TAG = "TemplateWebSample" + } + + init { + webGet(TAG, "/api/v3/getData.php") { + // here you can access and update any fields of the `data` object + + // ================ + // schedule a sync: + + // not sooner than two days later + data.setSyncNext(ENDPOINT_TEMPLATE_WEB_SAMPLE, 2 * DAY) + // in two days OR on explicit "grades" sync + data.setSyncNext(ENDPOINT_TEMPLATE_WEB_SAMPLE, 2 * DAY, DRAWER_ITEM_GRADES) + // only if sync is executed on Home view + data.setSyncNext(ENDPOINT_TEMPLATE_WEB_SAMPLE, syncIn = null, viewId = DRAWER_ITEM_HOME) + // always, in every sync + data.setSyncNext(ENDPOINT_TEMPLATE_WEB_SAMPLE, SYNC_ALWAYS) + + onSuccess(ENDPOINT_TEMPLATE_WEB_SAMPLE) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/web/TemplateWebSample2.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/web/TemplateWebSample2.kt new file mode 100644 index 00000000..ecf41b64 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/data/web/TemplateWebSample2.kt @@ -0,0 +1,41 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.template.data.web + +import pl.szczodrzynski.edziennik.MainActivity +import pl.szczodrzynski.edziennik.data.api.edziennik.template.DataTemplate +import pl.szczodrzynski.edziennik.data.api.edziennik.template.ENDPOINT_TEMPLATE_WEB_SAMPLE_2 +import pl.szczodrzynski.edziennik.data.api.edziennik.template.data.TemplateWeb +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.DAY + +class TemplateWebSample2(override val data: DataTemplate, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : TemplateWeb(data, lastSync) { + companion object { + private const val TAG = "TemplateWebSample2" + } + + init { + webGet(TAG, "/api/v3/getData.php") { + // here you can access and update any fields of the `data` object + + // ================ + // schedule a sync: + + // not sooner than two days later + data.setSyncNext(ENDPOINT_TEMPLATE_WEB_SAMPLE_2, 2 * DAY) + // in two days OR on explicit "grades" sync + data.setSyncNext(ENDPOINT_TEMPLATE_WEB_SAMPLE_2, 2 * DAY, MainActivity.DRAWER_ITEM_GRADES) + // only if sync is executed on Home view + data.setSyncNext(ENDPOINT_TEMPLATE_WEB_SAMPLE_2, syncIn = null, viewId = MainActivity.DRAWER_ITEM_HOME) + // always, in every sync + data.setSyncNext(ENDPOINT_TEMPLATE_WEB_SAMPLE_2, SYNC_ALWAYS) + + onSuccess(ENDPOINT_TEMPLATE_WEB_SAMPLE_2) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/firstlogin/TemplateFirstLogin.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/firstlogin/TemplateFirstLogin.kt new file mode 100644 index 00000000..48cc6f18 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/firstlogin/TemplateFirstLogin.kt @@ -0,0 +1,31 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-27. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.template.firstlogin + +import pl.szczodrzynski.edziennik.data.api.edziennik.template.DataTemplate +import pl.szczodrzynski.edziennik.data.api.edziennik.template.data.TemplateApi +import pl.szczodrzynski.edziennik.data.api.edziennik.template.data.TemplateWeb +import pl.szczodrzynski.edziennik.data.db.entity.Profile + +class TemplateFirstLogin(val data: DataTemplate, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "TemplateFirstLogin" + } + + private val web = TemplateWeb(data, null) + private val api = TemplateApi(data, null) + private val profileList = mutableListOf() + + init { + /*TemplateLoginWeb(data) { + web.webGet(TAG, "get all accounts") { text -> + //val accounts = json.getJsonArray("accounts") + + EventBus.getDefault().post(FirstLoginFinishedEvent(profileList, data.loginStore)) + onSuccess() + } + }*/ + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/login/TemplateLogin.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/login/TemplateLogin.kt new file mode 100644 index 00000000..b11eef13 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/login/TemplateLogin.kt @@ -0,0 +1,59 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.template.login + +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_TEMPLATE_API +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_TEMPLATE_WEB +import pl.szczodrzynski.edziennik.data.api.edziennik.template.DataTemplate +import pl.szczodrzynski.edziennik.utils.Utils + +class TemplateLogin(val data: DataTemplate, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "TemplateLogin" + } + + private var cancelled = false + + init { + nextLoginMethod(onSuccess) + } + + private fun nextLoginMethod(onSuccess: () -> Unit) { + if (data.targetLoginMethodIds.isEmpty()) { + onSuccess() + return + } + if (cancelled) { + onSuccess() + return + } + useLoginMethod(data.targetLoginMethodIds.removeAt(0)) { usedMethodId -> + data.progress(data.progressStep) + if (usedMethodId != -1) + data.loginMethods.add(usedMethodId) + nextLoginMethod(onSuccess) + } + } + + private fun useLoginMethod(loginMethodId: Int, onSuccess: (usedMethodId: Int) -> Unit) { + // this should never be true + if (data.loginMethods.contains(loginMethodId)) { + onSuccess(-1) + return + } + Utils.d(TAG, "Using login method $loginMethodId") + when (loginMethodId) { + LOGIN_METHOD_TEMPLATE_WEB -> { + data.startProgress(R.string.edziennik_progress_login_template_web) + TemplateLoginWeb(data) { onSuccess(loginMethodId) } + } + LOGIN_METHOD_TEMPLATE_API -> { + data.startProgress(R.string.edziennik_progress_login_template_api) + TemplateLoginApi(data) { onSuccess(loginMethodId) } + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/login/TemplateLoginApi.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/login/TemplateLoginApi.kt new file mode 100644 index 00000000..f49e433a --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/login/TemplateLoginApi.kt @@ -0,0 +1,45 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.template.login + +import pl.szczodrzynski.edziennik.data.api.ERROR_LOGIN_DATA_MISSING +import pl.szczodrzynski.edziennik.data.api.ERROR_PROFILE_MISSING +import pl.szczodrzynski.edziennik.data.api.edziennik.template.DataTemplate +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.HOUR +import pl.szczodrzynski.edziennik.ext.currentTimeUnix + +class TemplateLoginApi(val data: DataTemplate, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "TemplateLoginApi" + } + + init { run { + if (data.profile == null) { + data.error(ApiError(TAG, ERROR_PROFILE_MISSING)) + return@run + } + + if (data.isApiLoginValid()) { + onSuccess() + } + else { + if (/*data.webLogin != null && data.webPassword != null && */true) { + loginWithCredentials() + } + else { + data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) + } + } + }} + + fun loginWithCredentials() { + // succeed immediately + + data.apiToken = "ThisIsAVeryLongToken" + data.apiExpiryTime = currentTimeUnix() + 24 * HOUR + onSuccess() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/login/TemplateLoginWeb.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/login/TemplateLoginWeb.kt new file mode 100644 index 00000000..2f5b72c6 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/template/login/TemplateLoginWeb.kt @@ -0,0 +1,46 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-5. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.template.login + +import pl.szczodrzynski.edziennik.data.api.ERROR_LOGIN_DATA_MISSING +import pl.szczodrzynski.edziennik.data.api.ERROR_PROFILE_MISSING +import pl.szczodrzynski.edziennik.data.api.edziennik.template.DataTemplate +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.currentTimeUnix + +class TemplateLoginWeb(val data: DataTemplate, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "TemplateLoginWeb" + } + + init { run { + if (data.profile == null) { + data.error(ApiError(TAG, ERROR_PROFILE_MISSING)) + return@run + } + + if (data.isWebLoginValid()) { + data.app.cookieJar.set("eregister.example.com", "AuthCookie", data.webCookie) + onSuccess() + } + else { + data.app.cookieJar.clear("eregister.example.com") + if (/*data.webLogin != null && data.webPassword != null && */true) { + loginWithCredentials() + } + else { + data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) + } + } + }} + + fun loginWithCredentials() { + // succeed immediately + + data.webCookie = "ThisIsACookie" + data.webExpiryTime = currentTimeUnix() + 45 * 60 /* 45min */ + onSuccess() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/DataVulcan.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/DataVulcan.kt new file mode 100644 index 00000000..c6d797fa --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/DataVulcan.kt @@ -0,0 +1,320 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-6. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_VULCAN_HEBE +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_VULCAN_WEB_MAIN +import pl.szczodrzynski.edziennik.data.api.models.Data +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.crc16 +import pl.szczodrzynski.edziennik.ext.currentTimeUnix +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty +import pl.szczodrzynski.fslogin.realm.RealmData + +class DataVulcan(app: App, profile: Profile?, loginStore: LoginStore) : Data(app, profile, loginStore) { + fun isWebMainLoginValid() = symbol.isNotNullNorEmpty() + && (webExpiryTime[symbol]?.toLongOrNull() ?: 0) - 30 > currentTimeUnix() + && webAuthCookie[symbol].isNotNullNorEmpty() + && webRealmData != null + fun isHebeLoginValid() = hebePublicKey.isNotNullNorEmpty() + && hebePrivateKey.isNotNullNorEmpty() + && symbol.isNotNullNorEmpty() + + override fun satisfyLoginMethods() { + loginMethods.clear() + if (isWebMainLoginValid()) { + loginMethods += LOGIN_METHOD_VULCAN_WEB_MAIN + } + if (isHebeLoginValid()) { + loginMethods += LOGIN_METHOD_VULCAN_HEBE + } + } + + override fun generateUserCode() = "$schoolCode:$studentId" + + fun buildDeviceId(): String { + val deviceId = app.deviceId.padStart(16, '0') + val loginStoreId = loginStore.id.toString(16).padStart(4, '0') + val symbol = symbol?.crc16()?.toString(16)?.take(2) ?: "00" + return deviceId.substring(0..7) + + "-" + deviceId.substring(8..11) + + "-" + deviceId.substring(12..15) + + "-" + loginStoreId + + "-" + symbol + "6f72616e7a" + } + + /** + * A UONET+ client symbol. + * + * Present in the URL: https://uonetplus-uczen.vulcan.net.pl/[symbol]/[schoolSymbol]/ + * + * e.g. "poznan" + */ + private var mSymbol: String? = null + var symbol: String? + get() { mSymbol = mSymbol ?: profile?.getStudentData("symbol", null); return mSymbol } + set(value) { profile?.putStudentData("symbol", value); mSymbol = value } + + /** + * Group symbol/number of the student's school. + * + * Present in the URL: https://uonetplus-uczen.vulcan.net.pl/[symbol]/[schoolSymbol]/ + * + * ListaUczniow/JednostkaSprawozdawczaSymbol, e.g. "000088" + */ + private var mSchoolSymbol: String? = null + var schoolSymbol: String? + get() { mSchoolSymbol = mSchoolSymbol ?: profile?.getStudentData("schoolSymbol", null); return mSchoolSymbol } + set(value) { profile?.putStudentData("schoolSymbol", value) ?: return; mSchoolSymbol = value } + + /** + * Short name of the school, used in some places. + * + * ListaUczniow/JednostkaSprawozdawczaSkrot, e.g. "SP Wilkow" + */ + private var mSchoolShort: String? = null + var schoolShort: String? + get() { mSchoolShort = mSchoolShort ?: profile?.getStudentData("schoolShort", null); return mSchoolShort } + set(value) { profile?.putStudentData("schoolShort", value) ?: return; mSchoolShort = value } + + /** + * A school code consisting of the [symbol] and [schoolSymbol]. + * + * [symbol]_[schoolSymbol] + * + * e.g. "poznan_000088" + */ + private var mSchoolCode: String? = null + var schoolCode: String? + get() { mSchoolCode = mSchoolCode ?: profile?.getStudentData("schoolName", null); return mSchoolCode } + set(value) { profile?.putStudentData("schoolName", value) ?: return; mSchoolCode = value } + + /** + * ID of the student. + * + * ListaUczniow/Id, e.g. 42632 + */ + private var mStudentId: Int? = null + var studentId: Int + get() { mStudentId = mStudentId ?: profile?.getStudentData("studentId", 0); return mStudentId ?: 0 } + set(value) { profile?.putStudentData("studentId", value) ?: return; mStudentId = value } + + /** + * ID of the student's account. + * + * ListaUczniow/UzytkownikLoginId, e.g. 1709 + */ + private var mStudentLoginId: Int? = null + var studentLoginId: Int + get() { mStudentLoginId = mStudentLoginId ?: profile?.getStudentData("studentLoginId", 0); return mStudentLoginId ?: 0 } + set(value) { profile?.putStudentData("studentLoginId", value) ?: return; mStudentLoginId = value } + + /** + * ID of the student's class. + * + * ListaUczniow/IdOddzial, e.g. 35 + */ + private var mStudentClassId: Int? = null + var studentClassId: Int + get() { mStudentClassId = mStudentClassId ?: profile?.getStudentData("studentClassId", 0); return mStudentClassId ?: 0 } + set(value) { profile?.putStudentData("studentClassId", value) ?: return; mStudentClassId = value } + + /** + * ListaUczniow/IdOkresKlasyfikacyjny, e.g. 321 + */ + private var mStudentSemesterId: Int? = null + var studentSemesterId: Int + get() { mStudentSemesterId = mStudentSemesterId ?: profile?.getStudentData("studentSemesterId", 0); return mStudentSemesterId ?: 0 } + set(value) { profile?.putStudentData("studentSemesterId", value) ?: return; mStudentSemesterId = value } + + private var mStudentUnitId: Int? = null + var studentUnitId: Int + get() { mStudentUnitId = mStudentUnitId ?: profile?.getStudentData("studentUnitId", 0); return mStudentUnitId ?: 0 } + set(value) { profile?.putStudentData("studentUnitId", value) ?: return; mStudentUnitId = value } + + private var mStudentConstituentId: Int? = null + var studentConstituentId: Int + get() { mStudentConstituentId = mStudentConstituentId ?: profile?.getStudentData("studentConstituentId", 0); return mStudentConstituentId ?: 0 } + set(value) { profile?.putStudentData("studentConstituentId", value) ?: return; mStudentConstituentId = value } + + private var mSemester1Id: Int? = null + var semester1Id: Int + get() { mSemester1Id = mSemester1Id ?: profile?.getStudentData("semester1Id", 0); return mSemester1Id ?: 0 } + set(value) { profile?.putStudentData("semester1Id", value) ?: return; mSemester1Id = value } + private var mSemester2Id: Int? = null + var semester2Id: Int + get() { mSemester2Id = mSemester2Id ?: profile?.getStudentData("semester2Id", 0); return mSemester2Id ?: 0 } + set(value) { profile?.putStudentData("semester2Id", value) ?: return; mSemester2Id = value } + + /** + * ListaUczniow/OkresNumer, e.g. 1 or 2 + */ + private var mStudentSemesterNumber: Int? = null + var studentSemesterNumber: Int + get() { mStudentSemesterNumber = mStudentSemesterNumber ?: profile?.getStudentData("studentSemesterNumber", 0); return mStudentSemesterNumber ?: 0 } + set(value) { profile?.putStudentData("studentSemesterNumber", value) ?: return; mStudentSemesterNumber = value } + + /** + * Date of the end of the current semester ([studentSemesterNumber]). + * + * After this date, an API refresh of student list is required. + */ + private var mCurrentSemesterEndDate: Long? = null + var currentSemesterEndDate: Long + get() { mCurrentSemesterEndDate = mCurrentSemesterEndDate ?: profile?.getStudentData("currentSemesterEndDate", 0L); return mCurrentSemesterEndDate ?: 0L } + set(value) { profile?.putStudentData("currentSemesterEndDate", value) ?: return; mCurrentSemesterEndDate = value } + + /* _____ _____ ____ + /\ | __ \_ _| |___ \ + / \ | |__) || | __ ____) | + / /\ \ | ___/ | | \ \ / /__ < + / ____ \| | _| |_ \ V /___) | + /_/ \_\_| |_____| \_/|___*/ + /** + * A mobile API registration token. + * + * After first login only 3 first characters are stored here. + * This is later used to determine the API URL address. + */ + private var mApiToken: Map? = null + var apiToken: Map = mapOf() + get() { mApiToken = mApiToken ?: loginStore.getLoginData("apiToken", null)?.let { app.gson.fromJson(it, field.toMutableMap()::class.java) }; return mApiToken ?: mapOf() } + set(value) { loginStore.putLoginData("apiToken", app.gson.toJson(value)); mApiToken = value } + + /** + * A mobile API registration PIN. + * + * After first login, this is removed and/or set to null. + */ + private var mApiPin: Map? = null + var apiPin: Map = mapOf() + get() { mApiPin = mApiPin ?: loginStore.getLoginData("apiPin", null)?.let { app.gson.fromJson(it, field.toMutableMap()::class.java) }; return mApiPin ?: mapOf() } + set(value) { loginStore.putLoginData("apiPin", app.gson.toJson(value)); mApiPin = value } + + /* _ _ _ _____ _____ + | | | | | | /\ | __ \_ _| + | |__| | ___| |__ ___ / \ | |__) || | + | __ |/ _ \ '_ \ / _ \ / /\ \ | ___/ | | + | | | | __/ |_) | __/ / ____ \| | _| |_ + |_| |_|\___|_.__/ \___| /_/ \_\_| |____*/ + private var mHebePublicKey: String? = null + var hebePublicKey: String? + get() { mHebePublicKey = mHebePublicKey ?: loginStore.getLoginData("hebePublicKey", null); return mHebePublicKey } + set(value) { loginStore.putLoginData("hebePublicKey", value); mHebePublicKey = value } + + private var mHebePrivateKey: String? = null + var hebePrivateKey: String? + get() { mHebePrivateKey = mHebePrivateKey ?: loginStore.getLoginData("hebePrivateKey", null); return mHebePrivateKey } + set(value) { loginStore.putLoginData("hebePrivateKey", value); mHebePrivateKey = value } + + private var mHebePublicHash: String? = null + var hebePublicHash: String? + get() { mHebePublicHash = mHebePublicHash ?: loginStore.getLoginData("hebePublicHash", null); return mHebePublicHash } + set(value) { loginStore.putLoginData("hebePublicHash", value); mHebePublicHash = value } + + private var mHebeContext: String? = null + var hebeContext: String? + get() { mHebeContext = mHebeContext ?: profile?.getStudentData("hebeContext", null); return mHebeContext } + set(value) { profile?.putStudentData("hebeContext", value) ?: return; mHebeContext = value } + + private var mSenderAddressHash: String? = null + var senderAddressHash: String? + get() { mSenderAddressHash = mSenderAddressHash ?: profile?.getStudentData("senderAddressHash", null); return mSenderAddressHash } + set(value) { profile?.putStudentData("senderAddressHash", value) ?: return; mSenderAddressHash = value } + + private var mSenderAddressName: String? = null + var senderAddressName: String? + get() { mSenderAddressName = mSenderAddressName ?: profile?.getStudentData("senderAddressName", null); return mSenderAddressName } + set(value) { profile?.putStudentData("senderAddressName", value) ?: return; mSenderAddressName = value } + + val apiUrl: String? + get() { + val url = when (apiToken[symbol]?.substring(0, 3)) { + "3S1" -> "https://lekcjaplus.vulcan.net.pl" + "TA1" -> "https://uonetplus-komunikacja.umt.tarnow.pl" + "OP1" -> "https://uonetplus-komunikacja.eszkola.opolskie.pl" + "RZ1" -> "https://uonetplus-komunikacja.resman.pl" + "GD1" -> "https://uonetplus-komunikacja.edu.gdansk.pl" + "KA1" -> "https://uonetplus-komunikacja.mcuw.katowice.eu" + "KA2" -> "https://uonetplus-komunikacja-test.mcuw.katowice.eu" + "LU1" -> "https://uonetplus-komunikacja.edu.lublin.eu" + "LU2" -> "https://test-uonetplus-komunikacja.edu.lublin.eu" + "P03" -> "https://efeb-komunikacja-pro-efebmobile.pro.vulcan.pl" + "P01" -> "http://efeb-komunikacja.pro-hudson.win.vulcan.pl" + "P02" -> "http://efeb-komunikacja.pro-hudsonrc.win.vulcan.pl" + "P90" -> "http://efeb-komunikacja-pro-mwujakowska.neo.win.vulcan.pl" + "KO1" -> "https://uonetplus-komunikacja.eduportal.koszalin.pl" + "FK1", "FS1" -> "http://api.fakelog.cf" + "SZ9" -> "http://hack.szkolny.eu" + else -> null + } + return if (url != null) "$url/$symbol/" else loginStore.getLoginData("apiUrl", null) + } + + val fullApiUrl: String + get() { + return "$apiUrl$schoolSymbol/" + } + + /* __ __ _ ______ _____ _ _ + \ \ / / | | | ____/ ____| | | (_) + \ \ /\ / /__| |__ | |__ | (___ | | ___ __ _ _ _ __ + \ \/ \/ / _ \ '_ \ | __| \___ \ | | / _ \ / _` | | '_ \ + \ /\ / __/ |_) | | | ____) | | |___| (_) | (_| | | | | | + \/ \/ \___|_.__/ |_| |_____/ |______\___/ \__, |_|_| |_| + __/ | + |__*/ + var webRealmData: RealmData? + get() { mWebRealmData = mWebRealmData ?: loginStore.getLoginData("webRealmData", JsonObject()).let { + app.gson.fromJson(it, RealmData::class.java) + }; return mWebRealmData } + set(value) { loginStore.putLoginData("webRealmData", app.gson.toJsonTree(value) as JsonObject); mWebRealmData = value } + private var mWebRealmData: RealmData? = null + + val webHost + get() = webRealmData?.host + + var webEmail: String? + get() { mWebEmail = mWebEmail ?: loginStore.getLoginData("webEmail", null); return mWebEmail } + set(value) { loginStore.putLoginData("webEmail", value); mWebEmail = value } + private var mWebEmail: String? = null + var webUsername: String? + get() { mWebUsername = mWebUsername ?: loginStore.getLoginData("webUsername", null); return mWebUsername } + set(value) { loginStore.putLoginData("webUsername", value); mWebUsername = value } + private var mWebUsername: String? = null + var webPassword: String? + get() { mWebPassword = mWebPassword ?: loginStore.getLoginData("webPassword", null); return mWebPassword } + set(value) { loginStore.putLoginData("webPassword", value); mWebPassword = value } + private var mWebPassword: String? = null + + /** + * Expiry time of a certificate POSTed to a LoginEndpoint of the specific symbol. + * If the time passes, the certificate needs to be POSTed again (if valid) + * or re-generated. + */ + var webExpiryTime: Map = mapOf() + get() { mWebExpiryTime = mWebExpiryTime ?: loginStore.getLoginData("webExpiryTime", null)?.let { app.gson.fromJson(it, field.toMutableMap()::class.java) }; return mWebExpiryTime ?: mapOf() } + set(value) { loginStore.putLoginData("webExpiryTime", app.gson.toJson(value)); mWebExpiryTime = value } + private var mWebExpiryTime: Map? = null + + /** + * EfebSsoAuthCookie retrieved after posting a certificate + */ + var webAuthCookie: Map = mapOf() + get() { mWebAuthCookie = mWebAuthCookie ?: loginStore.getLoginData("webAuthCookie", null)?.let { app.gson.fromJson(it, field.toMutableMap()::class.java) }; return mWebAuthCookie ?: mapOf() } + set(value) { loginStore.putLoginData("webAuthCookie", app.gson.toJson(value)); mWebAuthCookie = value } + private var mWebAuthCookie: Map? = null + + /** + * Permissions needed to get JSONs from home page + */ + var webPermissions: Map = mapOf() + get() { mWebPermissions = mWebPermissions ?: loginStore.getLoginData("webPermissions", null)?.let { app.gson.fromJson(it, field.toMutableMap()::class.java) }; return mWebPermissions ?: mapOf() } + set(value) { loginStore.putLoginData("webPermissions", app.gson.toJson(value)); mWebPermissions = value } + private var mWebPermissions: Map? = null +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/Vulcan.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/Vulcan.kt new file mode 100644 index 00000000..64c87bf6 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/Vulcan.kt @@ -0,0 +1,197 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-6. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan + +import com.google.gson.JsonObject +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.helper.OneDriveDownloadAttachment +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanData +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe.VulcanHebeMessagesChangeStatus +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe.VulcanHebeSendMessage +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.firstlogin.VulcanFirstLogin +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.login.VulcanLogin +import pl.szczodrzynski.edziennik.data.api.events.AttachmentGetEvent +import pl.szczodrzynski.edziennik.data.api.events.EventGetEvent +import pl.szczodrzynski.edziennik.data.api.events.MessageGetEvent +import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikCallback +import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.data.db.full.AnnouncementFull +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.data.db.full.MessageFull +import pl.szczodrzynski.edziennik.utils.Utils +import pl.szczodrzynski.edziennik.utils.Utils.d +import java.io.File + +class Vulcan(val app: App, val profile: Profile?, val loginStore: LoginStore, val callback: EdziennikCallback) : EdziennikInterface { + companion object { + private const val TAG = "Vulcan" + } + + val internalErrorList = mutableListOf() + val data: DataVulcan + private var afterLogin: (() -> Unit)? = null + + init { + data = DataVulcan(app, profile, loginStore).apply { + callback = wrapCallback(this@Vulcan.callback) + satisfyLoginMethods() + } + } + + private fun completed() { + data.saveData() + callback.onCompleted() + } + + /* _______ _ _ _ _ _ + |__ __| | /\ | | (_) | | | + | | | |__ ___ / \ | | __ _ ___ _ __ _| |_| |__ _ __ ___ + | | | '_ \ / _ \ / /\ \ | |/ _` |/ _ \| '__| | __| '_ \| '_ ` _ \ + | | | | | | __/ / ____ \| | (_| | (_) | | | | |_| | | | | | | | | + |_| |_| |_|\___| /_/ \_\_|\__, |\___/|_| |_|\__|_| |_|_| |_| |_| + __/ | + |__*/ + override fun sync(featureIds: List, viewId: Int?, onlyEndpoints: List?, arguments: JsonObject?) { + data.arguments = arguments + data.prepare(vulcanLoginMethods, VulcanFeatures, featureIds, viewId, onlyEndpoints) + login() + } + + private fun login(loginMethodId: Int? = null, afterLogin: (() -> Unit)? = null) { + if (data.loginStore.mode == LOGIN_MODE_VULCAN_API) { + data.error(TAG, ERROR_VULCAN_API_DEPRECATED) + return + } + + d(TAG, "Trying to login with ${data.targetLoginMethodIds}") + if (internalErrorList.isNotEmpty()) { + d(TAG, " - Internal errors:") + internalErrorList.forEach { d(TAG, " - code $it") } + } + loginMethodId?.let { data.prepareFor(vulcanLoginMethods, it) } + afterLogin?.let { this.afterLogin = it } + VulcanLogin(data) { + data() + } + } + + private fun data() { + d(TAG, "Endpoint IDs: ${data.targetEndpointIds}") + if (internalErrorList.isNotEmpty()) { + d(TAG, " - Internal errors:") + internalErrorList.forEach { d(TAG, " - code $it") } + } + afterLogin?.invoke() ?: VulcanData(data) { + completed() + } + } + + override fun getMessage(message: MessageFull) { + login(LOGIN_METHOD_VULCAN_HEBE) { + if (message.seen) { + EventBus.getDefault().postSticky(MessageGetEvent(message)) + completed() + return@login + } + VulcanHebeMessagesChangeStatus(data, message) { + completed() + } + } + } + + override fun sendMessage(recipients: List, subject: String, text: String) { + login(LOGIN_METHOD_VULCAN_HEBE) { + VulcanHebeSendMessage(data, recipients, subject, text) { + completed() + } + } + } + + override fun markAllAnnouncementsAsRead() {} + override fun getAnnouncement(announcement: AnnouncementFull) {} + override fun getRecipientList() {} + + override fun getAttachment(owner: Any, attachmentId: Long, attachmentName: String) { + val fileUrl = attachmentName.substringAfter(":") + if (attachmentName == fileUrl) { + data.error(ApiError(TAG, ERROR_ONEDRIVE_DOWNLOAD)) + return + } + + OneDriveDownloadAttachment( + app, + fileUrl, + onSuccess = { file -> + val event = AttachmentGetEvent( + data.profileId, + owner, + attachmentId, + AttachmentGetEvent.TYPE_FINISHED, + file.absolutePath + ) + + val attachmentDataFile = File(Utils.getStorageDir(), ".${data.profileId}_${event.ownerId}_${event.attachmentId}") + Utils.writeStringToFile(attachmentDataFile, event.fileName) + + EventBus.getDefault().postSticky(event) + + completed() + }, + onProgress = { written, _ -> + val event = AttachmentGetEvent( + data.profileId, + owner, + attachmentId, + AttachmentGetEvent.TYPE_PROGRESS, + bytesWritten = written + ) + + EventBus.getDefault().postSticky(event) + }, + onError = { apiError -> + data.error(apiError) + } + ) + } + + override fun getEvent(eventFull: EventFull) { + eventFull.homeworkBody = "" + eventFull.isDownloaded = true + + EventBus.getDefault().postSticky(EventGetEvent(eventFull)) + completed() + } + + override fun firstLogin() { VulcanFirstLogin(data) { completed() } } + override fun cancel() { + d(TAG, "Cancelled") + data.cancel() + } + + private fun wrapCallback(callback: EdziennikCallback): EdziennikCallback { + return object : EdziennikCallback { + override fun onCompleted() { callback.onCompleted() } + override fun onProgress(step: Float) { callback.onProgress(step) } + override fun onStartProgress(stringRes: Int) { callback.onStartProgress(stringRes) } + override fun onError(apiError: ApiError) { + if (apiError.errorCode in internalErrorList) { + // finish immediately if the same error occurs twice during the same sync + callback.onError(apiError) + return + } + internalErrorList.add(apiError.errorCode) + when (apiError.errorCode) { + else -> callback.onError(apiError) + } + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/VulcanFeatures.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/VulcanFeatures.kt new file mode 100644 index 00000000..924d7ced --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/VulcanFeatures.kt @@ -0,0 +1,90 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-6. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan + +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.models.Feature + +const val ENDPOINT_VULCAN_WEB_LUCKY_NUMBERS = 2010 + +const val ENDPOINT_VULCAN_HEBE_MAIN = 3000 +const val ENDPOINT_VULCAN_HEBE_PUSH_CONFIG = 3005 +const val ENDPOINT_VULCAN_HEBE_ADDRESSBOOK = 3010 +const val ENDPOINT_VULCAN_HEBE_TIMETABLE = 3020 +const val ENDPOINT_VULCAN_HEBE_EXAMS = 3030 +const val ENDPOINT_VULCAN_HEBE_GRADES = 3040 +const val ENDPOINT_VULCAN_HEBE_GRADE_SUMMARY = 3050 +const val ENDPOINT_VULCAN_HEBE_HOMEWORK = 3060 +const val ENDPOINT_VULCAN_HEBE_NOTICES = 3070 +const val ENDPOINT_VULCAN_HEBE_ATTENDANCE = 3080 +const val ENDPOINT_VULCAN_HEBE_MESSAGES_INBOX = 3090 +const val ENDPOINT_VULCAN_HEBE_MESSAGES_SENT = 3100 +const val ENDPOINT_VULCAN_HEBE_TEACHERS = 3110 +const val ENDPOINT_VULCAN_HEBE_LUCKY_NUMBER = 3200 + +val VulcanFeatures = listOf( + // timetable + Feature(LOGIN_TYPE_VULCAN, FEATURE_TIMETABLE, listOf( + ENDPOINT_VULCAN_HEBE_TIMETABLE to LOGIN_METHOD_VULCAN_HEBE + ), listOf(LOGIN_METHOD_VULCAN_HEBE)), + // agenda + Feature(LOGIN_TYPE_VULCAN, FEATURE_AGENDA, listOf( + ENDPOINT_VULCAN_HEBE_EXAMS to LOGIN_METHOD_VULCAN_HEBE + ), listOf(LOGIN_METHOD_VULCAN_HEBE)), + // grades + Feature(LOGIN_TYPE_VULCAN, FEATURE_GRADES, listOf( + ENDPOINT_VULCAN_HEBE_GRADES to LOGIN_METHOD_VULCAN_HEBE, + ENDPOINT_VULCAN_HEBE_GRADE_SUMMARY to LOGIN_METHOD_VULCAN_HEBE + ), listOf(LOGIN_METHOD_VULCAN_HEBE)), + // homework + Feature(LOGIN_TYPE_VULCAN, FEATURE_HOMEWORK, listOf( + ENDPOINT_VULCAN_HEBE_HOMEWORK to LOGIN_METHOD_VULCAN_HEBE + ), listOf(LOGIN_METHOD_VULCAN_HEBE)), + // behaviour + Feature(LOGIN_TYPE_VULCAN, FEATURE_BEHAVIOUR, listOf( + ENDPOINT_VULCAN_HEBE_NOTICES to LOGIN_METHOD_VULCAN_HEBE + ), listOf(LOGIN_METHOD_VULCAN_HEBE)), + // attendance + Feature(LOGIN_TYPE_VULCAN, FEATURE_ATTENDANCE, listOf( + ENDPOINT_VULCAN_HEBE_ATTENDANCE to LOGIN_METHOD_VULCAN_HEBE + ), listOf(LOGIN_METHOD_VULCAN_HEBE)), + // messages + Feature(LOGIN_TYPE_VULCAN, FEATURE_MESSAGES_INBOX, listOf( + ENDPOINT_VULCAN_HEBE_MESSAGES_INBOX to LOGIN_METHOD_VULCAN_HEBE + ), listOf(LOGIN_METHOD_VULCAN_HEBE)), + Feature(LOGIN_TYPE_VULCAN, FEATURE_MESSAGES_SENT, listOf( + ENDPOINT_VULCAN_HEBE_MESSAGES_SENT to LOGIN_METHOD_VULCAN_HEBE + ), listOf(LOGIN_METHOD_VULCAN_HEBE)), + + // push config + Feature(LOGIN_TYPE_VULCAN, FEATURE_PUSH_CONFIG, listOf( + ENDPOINT_VULCAN_HEBE_PUSH_CONFIG to LOGIN_METHOD_VULCAN_HEBE + ), listOf(LOGIN_METHOD_VULCAN_HEBE)).withShouldSync { data -> + !data.app.config.sync.tokenVulcanList.contains(data.profileId) + }, + + /** + * Lucky number - using WEB Main. + */ + Feature(LOGIN_TYPE_VULCAN, FEATURE_LUCKY_NUMBER, listOf( + ENDPOINT_VULCAN_WEB_LUCKY_NUMBERS to LOGIN_METHOD_VULCAN_WEB_MAIN + ), listOf(LOGIN_METHOD_VULCAN_WEB_MAIN)) + .withShouldSync { data -> data.shouldSyncLuckyNumber() } + .withPriority(2), + /** + * Lucky number - using Hebe API + */ + Feature(LOGIN_TYPE_VULCAN, FEATURE_LUCKY_NUMBER, listOf( + ENDPOINT_VULCAN_HEBE_LUCKY_NUMBER to LOGIN_METHOD_VULCAN_HEBE + ), listOf(LOGIN_METHOD_VULCAN_HEBE)) + .withShouldSync { data -> data.shouldSyncLuckyNumber() } + .withPriority(1), + + Feature(LOGIN_TYPE_VULCAN, FEATURE_ALWAYS_NEEDED, listOf( + ENDPOINT_VULCAN_HEBE_MAIN to LOGIN_METHOD_VULCAN_HEBE, + ENDPOINT_VULCAN_HEBE_ADDRESSBOOK to LOGIN_METHOD_VULCAN_HEBE, + ENDPOINT_VULCAN_HEBE_TEACHERS to LOGIN_METHOD_VULCAN_HEBE + ), listOf(LOGIN_METHOD_VULCAN_HEBE)) +) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/VulcanData.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/VulcanData.kt new file mode 100644 index 00000000..6170d817 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/VulcanData.kt @@ -0,0 +1,157 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-6. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data + +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.* +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe.* +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.web.VulcanWebLuckyNumber +import pl.szczodrzynski.edziennik.data.db.entity.Message +import pl.szczodrzynski.edziennik.utils.Utils + +class VulcanData(val data: DataVulcan, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "VulcanData" + } + + private var firstSemesterSync = false + private val firstSemesterSyncExclude = listOf( + ENDPOINT_VULCAN_HEBE_MAIN, + ENDPOINT_VULCAN_HEBE_PUSH_CONFIG, + ENDPOINT_VULCAN_HEBE_ADDRESSBOOK, + ENDPOINT_VULCAN_HEBE_TIMETABLE, + ENDPOINT_VULCAN_HEBE_EXAMS, + ENDPOINT_VULCAN_HEBE_HOMEWORK, + ENDPOINT_VULCAN_HEBE_NOTICES, + ENDPOINT_VULCAN_HEBE_MESSAGES_INBOX, + ENDPOINT_VULCAN_HEBE_MESSAGES_SENT, + ENDPOINT_VULCAN_HEBE_TEACHERS, + ENDPOINT_VULCAN_HEBE_LUCKY_NUMBER + ) + + init { + if (data.studentSemesterNumber == 2 && data.profile?.empty != false) { + firstSemesterSync = true + // set to sync 1st semester first + data.studentSemesterId = data.semester1Id + data.studentSemesterNumber = 1 + } + nextEndpoint { + if (firstSemesterSync) { + // at the end, set back 2nd semester + data.studentSemesterId = data.semester2Id + data.studentSemesterNumber = 2 + } + onSuccess() + } + } + + private fun nextEndpoint(onSuccess: () -> Unit) { + if (data.targetEndpointIds.isEmpty()) { + onSuccess() + return + } + if (data.cancelled) { + onSuccess() + return + } + val id = data.targetEndpointIds.firstKey() + val lastSync = data.targetEndpointIds.remove(id) + useEndpoint(id, lastSync) { + if (firstSemesterSync && id !in firstSemesterSyncExclude) { + // sync 2nd semester after every endpoint + data.studentSemesterId = data.semester2Id + data.studentSemesterNumber = 2 + useEndpoint(id, lastSync) { + // set 1st semester back for the next endpoint + data.studentSemesterId = data.semester1Id + data.studentSemesterNumber = 1 + // progress further + data.progress(data.progressStep) + nextEndpoint(onSuccess) + } + return@useEndpoint + } + data.progress(data.progressStep) + nextEndpoint(onSuccess) + } + } + + private fun useEndpoint(endpointId: Int, lastSync: Long?, onSuccess: (endpointId: Int) -> Unit) { + Utils.d(TAG, "Using endpoint $endpointId. Last sync time = $lastSync") + when (endpointId) { + ENDPOINT_VULCAN_WEB_LUCKY_NUMBERS -> { + data.startProgress(R.string.edziennik_progress_endpoint_lucky_number) + VulcanWebLuckyNumber(data, lastSync, onSuccess) + } + ENDPOINT_VULCAN_HEBE_MAIN -> { + if (data.profile == null) { + onSuccess(ENDPOINT_VULCAN_HEBE_MAIN) + return + } + data.startProgress(R.string.edziennik_progress_endpoint_student_info) + VulcanHebeMain(data, lastSync).getStudents( + profile = data.profile, + profileList = null + ) { + onSuccess(ENDPOINT_VULCAN_HEBE_MAIN) + } + } + ENDPOINT_VULCAN_HEBE_PUSH_CONFIG -> { + data.startProgress(R.string.edziennik_progress_endpoint_push_config) + VulcanHebePushConfig(data, lastSync, onSuccess) + } + ENDPOINT_VULCAN_HEBE_ADDRESSBOOK -> { + data.startProgress(R.string.edziennik_progress_endpoint_addressbook) + VulcanHebeAddressbook(data, lastSync, onSuccess) + } + ENDPOINT_VULCAN_HEBE_TEACHERS -> { + data.startProgress(R.string.edziennik_progress_endpoint_teachers) + VulcanHebeTeachers(data, lastSync, onSuccess) + } + ENDPOINT_VULCAN_HEBE_TIMETABLE -> { + data.startProgress(R.string.edziennik_progress_endpoint_timetable) + VulcanHebeTimetable(data, lastSync, onSuccess) + } + ENDPOINT_VULCAN_HEBE_EXAMS -> { + data.startProgress(R.string.edziennik_progress_endpoint_exams) + VulcanHebeExams(data, lastSync, onSuccess) + } + ENDPOINT_VULCAN_HEBE_GRADES -> { + data.startProgress(R.string.edziennik_progress_endpoint_grades) + VulcanHebeGrades(data, lastSync, onSuccess) + } + ENDPOINT_VULCAN_HEBE_GRADE_SUMMARY -> { + data.startProgress(R.string.edziennik_progress_endpoint_proposed_grades) + VulcanHebeGradeSummary(data, lastSync, onSuccess) + } + ENDPOINT_VULCAN_HEBE_HOMEWORK -> { + data.startProgress(R.string.edziennik_progress_endpoint_homework) + VulcanHebeHomework(data, lastSync, onSuccess) + } + ENDPOINT_VULCAN_HEBE_NOTICES -> { + data.startProgress(R.string.edziennik_progress_endpoint_notices) + VulcanHebeNotices(data, lastSync, onSuccess) + } + ENDPOINT_VULCAN_HEBE_ATTENDANCE -> { + data.startProgress(R.string.edziennik_progress_endpoint_attendance) + VulcanHebeAttendance(data, lastSync, onSuccess) + } + ENDPOINT_VULCAN_HEBE_MESSAGES_INBOX -> { + data.startProgress(R.string.edziennik_progress_endpoint_messages_inbox) + VulcanHebeMessages(data, lastSync, onSuccess).getMessages(Message.TYPE_RECEIVED) + } + ENDPOINT_VULCAN_HEBE_MESSAGES_SENT -> { + data.startProgress(R.string.edziennik_progress_endpoint_messages_outbox) + VulcanHebeMessages(data, lastSync, onSuccess).getMessages(Message.TYPE_SENT) + } + ENDPOINT_VULCAN_HEBE_LUCKY_NUMBER -> { + data.startProgress(R.string.edziennik_progress_endpoint_lucky_number) + VulcanHebeLuckyNumber(data, lastSync, onSuccess) + } + else -> onSuccess(endpointId) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/VulcanHebe.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/VulcanHebe.kt new file mode 100644 index 00000000..457306c2 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/VulcanHebe.kt @@ -0,0 +1,406 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-20. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data + +import android.os.Build +import androidx.core.util.set +import com.google.gson.JsonArray +import com.google.gson.JsonElement +import com.google.gson.JsonObject +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.body.MediaTypeUtils +import im.wangchao.mhttp.callback.JsonCallbackHandler +import io.github.wulkanowy.signer.hebe.getSignatureHeaders +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe.HebeFilterType +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.db.entity.LessonRange +import pl.szczodrzynski.edziennik.data.db.entity.Subject +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.Utils.d +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time +import java.net.HttpURLConnection +import java.net.URLEncoder +import java.time.Instant +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter +import java.util.* + +open class VulcanHebe(open val data: DataVulcan, open val lastSync: Long?) { + companion object { + const val TAG = "VulcanHebe" + } + + val profileId + get() = data.profile?.id ?: -1 + + val profile + get() = data.profile + + fun getDateTime( + json: JsonObject?, + key: String, + default: Long = System.currentTimeMillis() + ): Long { + val date = json.getJsonObject(key) + return date.getLong("Timestamp") ?: return default + } + + fun getDate(json: JsonObject?, key: String): Date? { + val date = json.getJsonObject(key) + return date.getString("Date")?.let { Date.fromY_m_d(it) } + } + + fun getTeacherId(json: JsonObject?, key: String): Long? { + val teacher = json.getJsonObject(key) + val teacherId = teacher.getLong("Id") ?: return null + if (data.teacherList[teacherId] == null) { + data.teacherList[teacherId] = Teacher( + data.profileId, + teacherId, + teacher.getString("Name") ?: "", + teacher.getString("Surname") ?: "" + ) + } + return teacherId + } + + fun getSubjectId(json: JsonObject?, key: String): Long? { + val subject = json.getJsonObject(key) + val subjectId = subject.getLong("Id") ?: return null + if (data.subjectList[subjectId] == null) { + data.subjectList[subjectId] = Subject( + data.profileId, + subjectId, + subject.getString("Name") ?: "", + subject.getString("Kod") ?: "" + ) + } + return subjectId + } + + fun getTeamId(json: JsonObject?, key: String): Long? { + val team = json.getJsonObject(key) + val teamId = team.getLong("Id") + var teamName = team.getString("Shortcut") + ?: team.getString("Name") + ?: "" + teamName = "${profile?.studentClassName ?: ""} $teamName" + return data.getTeam( + id = teamId, + name = teamName, + schoolCode = data.schoolCode ?: "", + isTeamClass = false, + ).id + } + + fun getClassId(json: JsonObject?, key: String): Long? { + val team = json.getJsonObject(key) + val teamId = team.getLong("Id") + val teamName = data.profile?.studentClassName + ?: team.getString("Name") + ?: "" + return data.getTeam( + id = teamId, + name = teamName, + schoolCode = data.schoolCode ?: "", + isTeamClass = true, + ).id + } + + fun getLessonRange(json: JsonObject?, key: String): LessonRange? { + val timeslot = json.getJsonObject(key) + val position = timeslot.getInt("Position") ?: return null + val start = timeslot.getString("Start") ?: return null + val end = timeslot.getString("End") ?: return null + val lessonRange = LessonRange( + data.profileId, + position, + Time.fromH_m(start), + Time.fromH_m(end) + ) + data.lessonRanges[position] = lessonRange + return lessonRange + } + + fun getSemester(json: JsonObject?): Int { + val periodId = json.getInt("PeriodId") ?: return 1 + return if (periodId == data.semester1Id) + 1 + else + 2 + } + + fun isCurrentYear(date: Date): Boolean { + return profile?.let { profile -> + return@let date >= profile.dateSemester1Start + } ?: false + } + + fun isCurrentYear(dateTime: Long): Boolean { + return profile?.let { profile -> + return@let dateTime >= profile.dateSemester1Start.inMillis + } ?: false + } + + inline fun apiRequest( + tag: String, + endpoint: String, + method: Int = GET, + payload: JsonElement? = null, + baseUrl: Boolean = false, + firebaseToken: String? = null, + crossinline onSuccess: (json: T, response: Response?) -> Unit + ) { + val url = "${if (baseUrl) data.apiUrl else data.fullApiUrl}$endpoint" + + d(tag, "Request: Vulcan/Hebe - $url") + + val privateKey = data.hebePrivateKey + val publicHash = data.hebePublicHash + + if (privateKey == null || publicHash == null) { + data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) + return + } + + val timestamp = ZonedDateTime.now(ZoneId.of("GMT")) + val timestampMillis = timestamp.toInstant().toEpochMilli() + val timestampIso = timestamp.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")) + + val finalPayload = if (payload != null) { + JsonObject( + "AppName" to VULCAN_HEBE_APP_NAME, + "AppVersion" to VULCAN_HEBE_APP_VERSION, + "CertificateId" to publicHash, + "Envelope" to payload, + "FirebaseToken" to (firebaseToken ?: data.app.config.sync.tokenVulcanHebe), + "API" to 1, + "RequestId" to UUID.randomUUID().toString(), + "Timestamp" to timestampMillis, + "TimestampFormatted" to timestampIso + ) + } else null + val jsonString = finalPayload?.toString() + + val headers = getSignatureHeaders( + publicHash, + privateKey, + jsonString, + endpoint, + timestamp + ) + + val callback = object : JsonCallbackHandler() { + override fun onSuccess(json: JsonObject?, response: Response?) { + if (json == null) { + data.error( + ApiError(TAG, ERROR_RESPONSE_EMPTY) + .withResponse(response) + ) + return + } + + val status = json.getJsonObject("Status") + val statusCode = status?.getInt("Code") ?: 0 + if (statusCode != 0) { + val statusMessage = status?.getString("Message") + val errorCode = when (statusCode) { + -1 -> ERROR_VULCAN_HEBE_SERVER_ERROR + 100 -> ERROR_VULCAN_HEBE_SIGNATURE_ERROR + 101 -> ERROR_VULCAN_HEBE_INVALID_PAYLOAD + 106 -> ERROR_VULCAN_HEBE_FIREBASE_ERROR + 108 -> ERROR_VULCAN_HEBE_CERTIFICATE_GONE + 200 -> when (true) { + statusMessage?.contains("Class") -> ERROR_LOGIN_VULCAN_NO_PUPILS + statusMessage?.contains("Token") -> ERROR_LOGIN_VULCAN_INVALID_TOKEN + else -> ERROR_VULCAN_HEBE_ENTITY_NOT_FOUND + } + 201 -> ERROR_LOGIN_VULCAN_EXPIRED_TOKEN + 203 -> when (json.getJsonObject("Envelope").getInt("AvailableRetries")) { + 2 -> ERROR_LOGIN_VULCAN_INVALID_PIN_2_REMAINING + 1 -> ERROR_LOGIN_VULCAN_INVALID_PIN_1_REMAINING + else -> ERROR_LOGIN_VULCAN_INVALID_PIN_0_REMAINING + } + 204 -> ERROR_LOGIN_VULCAN_INVALID_PIN_0_REMAINING + else -> ERROR_VULCAN_HEBE_OTHER + } + data.error( + ApiError(tag, errorCode) + .withResponse(response) + .withApiResponse(json.toString()) + ) + return + } + + val envelope = if (json.get("Envelope").isJsonNull && null is T) + null as T + else when (T::class.java) { + JsonObject::class.java -> json.getJsonObject("Envelope") as T + JsonArray::class.java -> json.getJsonArray("Envelope") as T + java.lang.Boolean::class.java -> json.getBoolean("Envelope") as T + else -> { + data.error( + ApiError(tag, ERROR_RESPONSE_EMPTY) + .withResponse(response) + .withApiResponse(json) + ) + return + } + } + + try { + onSuccess(envelope, response) + } catch (e: Exception) { + data.error( + ApiError(tag, EXCEPTION_VULCAN_HEBE_REQUEST) + .withResponse(response) + .withThrowable(e) + .withApiResponse(json) + ) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error( + ApiError(tag, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable) + ) + } + } + + Request.builder() + .url(url) + .userAgent(VULCAN_HEBE_USER_AGENT) + .addHeader("vOS", "Android") + .addHeader("vDeviceModel", Build.MODEL) + .addHeader("vAPI", "1") + .apply { + if (data.hebeContext != null) + addHeader("vContext", data.hebeContext) + headers.forEach { + addHeader(it.key, it.value) + } + when (method) { + GET -> get() + POST -> { + post() + setTextBody(jsonString, MediaTypeUtils.APPLICATION_JSON) + } + } + } + .allowErrorCode(HttpURLConnection.HTTP_BAD_REQUEST) + .allowErrorCode(HttpURLConnection.HTTP_FORBIDDEN) + .allowErrorCode(HttpURLConnection.HTTP_UNAUTHORIZED) + .allowErrorCode(HttpURLConnection.HTTP_UNAVAILABLE) + .callback(callback) + .build() + .enqueue() + } + + inline fun apiGet( + tag: String, + endpoint: String, + query: Map = mapOf(), + baseUrl: Boolean = false, + firebaseToken: String? = null, + crossinline onSuccess: (json: T, response: Response?) -> Unit + ) { + val queryPath = query.map { + it.key + "=" + URLEncoder.encode(it.value, "UTF-8").replace("+", "%20") + }.join("&") + apiRequest( + tag, + if (query.isNotEmpty()) "$endpoint?$queryPath" else endpoint, + baseUrl = baseUrl, + firebaseToken = firebaseToken, + onSuccess = onSuccess + ) + } + + inline fun apiPost( + tag: String, + endpoint: String, + payload: JsonElement, + baseUrl: Boolean = false, + firebaseToken: String? = null, + crossinline onSuccess: (json: T, response: Response?) -> Unit + ) { + apiRequest( + tag, + endpoint, + method = POST, + payload, + baseUrl = baseUrl, + firebaseToken = firebaseToken, + onSuccess = onSuccess + ) + } + + fun apiGetList( + tag: String, + endpoint: String, + filterType: HebeFilterType? = null, + dateFrom: Date? = null, + dateTo: Date? = null, + lastSync: Long? = null, + folder: Int? = null, + params: Map = mapOf(), + includeFilterType: Boolean = true, + onSuccess: (data: List, response: Response?) -> Unit + ) { + val url = if (includeFilterType && filterType != null) + "$endpoint/${filterType.endpoint}" + else endpoint + + val query = params.toMutableMap() + + when (filterType) { + HebeFilterType.BY_PUPIL -> { + query["unitId"] = data.studentUnitId.toString() + query["pupilId"] = data.studentId.toString() + query["periodId"] = data.studentSemesterId.toString() + } + HebeFilterType.BY_PERSON -> { + query["loginId"] = data.studentLoginId.toString() + } + HebeFilterType.BY_PERIOD -> { + query["periodId"] = data.studentSemesterId.toString() + query["pupilId"] = data.studentId.toString() + } + } + + if (dateFrom != null) + query["dateFrom"] = dateFrom.stringY_m_d + if (dateTo != null) + query["dateTo"] = dateTo.stringY_m_d + + if (folder != null) + query["folder"] = folder.toString() + + val semester1Start = profile?.dateSemester1Start?.inMillis + + query["lastId"] = "-2147483648" // don't ask, it's just Vulcan + query["pageSize"] = "500" + query["lastSyncDate"] = LocalDateTime + .ofInstant( + Instant.ofEpochMilli(lastSync ?: semester1Start ?: 0), + ZoneId.systemDefault() + ) + .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + + apiGet(tag, url, query) { json: JsonArray, response -> + onSuccess(json.map { it.asJsonObject }, response) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/VulcanWebMain.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/VulcanWebMain.kt new file mode 100644 index 00000000..e1cc52e6 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/VulcanWebMain.kt @@ -0,0 +1,326 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-17. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data + +import com.google.gson.JsonArray +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import im.wangchao.mhttp.callback.TextCallbackHandler +import pl.droidsonroids.jspoon.Jspoon +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.login.CufsCertificate +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.Utils +import pl.szczodrzynski.edziennik.utils.models.Date +import java.io.File +import java.net.HttpURLConnection + +open class VulcanWebMain(open val data: DataVulcan, open val lastSync: Long?) { + companion object { + const val TAG = "VulcanWebMain" + const val WEB_MAIN = 0 + const val WEB_OLD = 1 + const val WEB_NEW = 2 + const val WEB_MESSAGES = 3 + const val STATE_SUCCESS = 0 + const val STATE_NO_REGISTER = 1 + const val STATE_LOGGED_OUT = 2 + } + + val profileId + get() = data.profile?.id ?: -1 + + val profile + get() = data.profile + + private val certificateAdapter by lazy { + Jspoon.create().adapter(CufsCertificate::class.java) + } + + fun saveCertificate(xml: String) { + val file = File(data.app.filesDir, "cert_"+(data.webUsername ?: data.webEmail)+".xml") + file.writeText(xml) + } + + fun readCertificate(): String? { + val file = File(data.app.filesDir, "cert_"+(data.webUsername ?: data.webEmail)+".xml") + if (file.canRead()) + return file.readText() + return null + } + + fun parseCertificate(xml: String): CufsCertificate { + val xmlParsed = xml + .replace("<[a-z]+?:".toRegex(), "<") + .replace(" Unit): Boolean { + // check if the certificate is valid + if (Date.fromIso(certificate.expiryDate) < System.currentTimeMillis()) + return false + + val callback = object : TextCallbackHandler() { + override fun onSuccess(text: String?, response: Response?) { + if (response?.headers()?.get("Location")?.contains("LoginEndpoint.aspx") == true + || response?.headers()?.get("Location")?.contains("?logout=true") == true) { + onResult(symbol, STATE_LOGGED_OUT) + return + } + if (text?.contains("LoginEndpoint.aspx?logout=true") == true) { + onResult(symbol, STATE_NO_REGISTER) + return + } + if (!validateCallback(symbol, text, response, jsonResponse = false)) { + return + } + data.webExpiryTime = data.webExpiryTime.toMutableMap().also { map -> + map[symbol] = (Date.fromIso(certificate.expiryDate) / 1000L).toString() + } + onResult(symbol, STATE_SUCCESS) + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(TAG, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + Request.builder() + .url("https://uonetplus.${data.webHost}/$symbol/LoginEndpoint.aspx") + .withClient(data.app.httpLazy) + .userAgent(SYSTEM_USER_AGENT) + .post() + .addParameter("wa", "wsignin1.0") + .addParameter("wctx", certificate.targetUrl) + .addParameter("wresult", certificate.xml) + .allowErrorCode(HttpURLConnection.HTTP_BAD_REQUEST) + .allowErrorCode(HttpURLConnection.HTTP_FORBIDDEN) + .allowErrorCode(HttpURLConnection.HTTP_UNAUTHORIZED) + .allowErrorCode(HttpURLConnection.HTTP_UNAVAILABLE) + .allowErrorCode(429) + .callback(callback) + .build() + .enqueue() + + return true + } + + fun getStartPage(symbol: String = data.symbol ?: "default", postErrors: Boolean = true, onSuccess: (html: String, schoolSymbols: List) -> Unit) { + val callback = object : TextCallbackHandler() { + override fun onSuccess(text: String?, response: Response?) { + if (!validateCallback(symbol, text, response, jsonResponse = false) || text == null) { + return + } + + if (postErrors) { + when { + text.contains("status absolwenta") -> ERROR_VULCAN_WEB_GRADUATE_ACCOUNT + else -> null + }?.let { errorCode -> + data.error(ApiError(TAG, errorCode) + .withResponse(response) + .withApiResponse(text)) + return + } + } + + val schoolSymbols = mutableListOf() + val clientUrl = "://uonetplus-uczen.${data.webHost}/$symbol/" + var clientIndex = text.indexOf(clientUrl) + var count = 0 + while (clientIndex != -1 && count < 100) { + val startIndex = clientIndex + clientUrl.length + val endIndex = text.indexOfAny(charArrayOf('"', '/'), startIndex = startIndex) + val schoolSymbol = text.substring(startIndex, endIndex) + schoolSymbols += schoolSymbol + clientIndex = text.indexOf(clientUrl, startIndex = endIndex) + count++ + } + schoolSymbols.removeAll { + it.lowercase() == "default" + || !it.matches(Regexes.VULCAN_WEB_SYMBOL_VALIDATE) + } + + if (postErrors && schoolSymbols.isEmpty()) { + data.error(ApiError(TAG, ERROR_VULCAN_WEB_NO_SCHOOLS) + .withResponse(response) + .withApiResponse(text)) + return + } + + data.webPermissions = data.webPermissions.toMutableMap().also { map -> + val permissions = Regexes.VULCAN_WEB_PERMISSIONS.find(text)?.let { it[1] } + if (permissions?.isNotBlank() == true) { + val json = permissions.split("|") + .getOrNull(0) + ?.base64DecodeToString() + ?.toJsonObject() + val unitIds = json + ?.getJsonArray("Units") + ?.asJsonObjectList() + ?.filter { unit -> + unit.getString("Symbol") in schoolSymbols + } + ?.mapNotNull { it.getInt("Id") } ?: emptyList() + val studentId = json + ?.getJsonArray("AuthInfos") + ?.asJsonObjectList() + ?.filter { authInfo -> + authInfo.getInt("JednostkaSprawozdawczaId") in unitIds + } + ?.flatMap { authInfo -> + authInfo.getJsonArray("UczenIds") + ?.map { it.asInt } + ?: listOf() + } + ?.firstOrNull() + ?.toString() + data.app.cookieJar.set( + data.webHost ?: "vulcan.net.pl", + "idBiezacyUczen", + studentId + ) + } + map[symbol] = permissions + } + + onSuccess(text, schoolSymbols) + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(TAG, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + Request.builder() + .url("https://uonetplus.${data.webHost}/$symbol/Start.mvc/Index") + .userAgent(SYSTEM_USER_AGENT) + .get() + .allowErrorCode(HttpURLConnection.HTTP_BAD_REQUEST) + .allowErrorCode(HttpURLConnection.HTTP_FORBIDDEN) + .allowErrorCode(HttpURLConnection.HTTP_UNAUTHORIZED) + .allowErrorCode(HttpURLConnection.HTTP_UNAVAILABLE) + .allowErrorCode(429) + .callback(callback) + .build() + .enqueue() + } + + private fun validateCallback(symbol: String, text: String?, response: Response?, jsonResponse: Boolean = true): Boolean { + if (text == null) { + data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) + .withResponse(response)) + return false + } + + if (response?.code() !in 200..302 || (jsonResponse && !text.startsWith("{"))) { + when { + text.contains("The custom error module") -> ERROR_VULCAN_WEB_429 + else -> ERROR_VULCAN_WEB_OTHER + }.let { errorCode -> + data.error(ApiError(TAG, errorCode) + .withApiResponse(text) + .withResponse(response)) + return false + } + } + + val cookies = data.app.cookieJar.getAll(data.webHost ?: "vulcan.net.pl") + val authCookie = cookies["EfebSsoAuthCookie"] + if ((authCookie == null || authCookie == "null") && data.webAuthCookie[symbol] != null) { + data.app.cookieJar.set(data.webHost ?: "vulcan.net.pl", "EfebSsoAuthCookie", data.webAuthCookie[symbol]) + } + else if (authCookie.isNotNullNorBlank() && authCookie != "null" && authCookie != data.webAuthCookie[symbol]) { + data.webAuthCookie = data.webAuthCookie.toMutableMap().also { map -> + map[symbol] = authCookie + } + } + return true + } + + fun webGetJson( + tag: String, + webType: Int, + endpoint: String, + method: Int = POST, + parameters: Map = emptyMap(), + onSuccess: (json: JsonObject, response: Response?) -> Unit + ) { + val url = "https://" + when (webType) { + WEB_MAIN -> "uonetplus" + WEB_OLD -> "uonetplus-opiekun" + WEB_NEW -> "uonetplus-uczen" + WEB_MESSAGES -> "uonetplus-uzytkownik" + else -> "uonetplus" + } + ".${data.webHost}/${data.symbol}/$endpoint" + + Utils.d(tag, "Request: Vulcan/WebMain - $url") + + val payload = JsonObject() + parameters.map { (name, value) -> + when (value) { + is JsonObject -> payload.add(name, value) + is JsonArray -> payload.add(name, value) + is String -> payload.addProperty(name, value) + is Int -> payload.addProperty(name, value) + is Long -> payload.addProperty(name, value) + is Float -> payload.addProperty(name, value) + is Char -> payload.addProperty(name, value) + is Boolean -> payload.addProperty(name, value) + } + } + + val callback = object : TextCallbackHandler() { + override fun onSuccess(text: String?, response: Response?) { + if (!validateCallback(data.symbol ?: "default", text, response)) + return + + try { + val json = JsonParser.parseString(text).asJsonObject + onSuccess(json, response) + } catch (e: Exception) { + data.error(ApiError(tag, EXCEPTION_VULCAN_WEB_REQUEST) + .withResponse(response) + .withThrowable(e) + .withApiResponse(text)) + } + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + data.error(ApiError(tag, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } + } + + Request.builder() + .url(url) + .userAgent(SYSTEM_USER_AGENT) + .apply { + when (method) { + GET -> get() + POST -> post() + } + } + .setJsonBody(payload) + .allowErrorCode(429) + .callback(callback) + .build() + .enqueue() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/HebeFilterType.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/HebeFilterType.kt new file mode 100644 index 00000000..a4ea84b1 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/HebeFilterType.kt @@ -0,0 +1,11 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-20. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +enum class HebeFilterType(val endpoint: String) { + BY_PUPIL("byPupil"), + BY_PERSON("byPerson"), + BY_PERIOD("byPeriod") +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeAddressbook.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeAddressbook.kt new file mode 100644 index 00000000..13eeb8db --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeAddressbook.kt @@ -0,0 +1,122 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-21. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import androidx.core.util.set +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_ADDRESSBOOK +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_HEBE_ADDRESSBOOK +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.data.db.entity.Teacher.Companion.TYPE_EDUCATOR +import pl.szczodrzynski.edziennik.data.db.entity.Teacher.Companion.TYPE_OTHER +import pl.szczodrzynski.edziennik.data.db.entity.Teacher.Companion.TYPE_PARENT +import pl.szczodrzynski.edziennik.data.db.entity.Teacher.Companion.TYPE_PARENTS_COUNCIL +import pl.szczodrzynski.edziennik.data.db.entity.Teacher.Companion.TYPE_STUDENT +import pl.szczodrzynski.edziennik.data.db.entity.Teacher.Companion.TYPE_TEACHER +import pl.szczodrzynski.edziennik.ext.* + +class VulcanHebeAddressbook( + override val data: DataVulcan, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : VulcanHebe(data, lastSync) { + companion object { + const val TAG = "VulcanHebeAddressbook" + } + + private fun String.removeUnitName(unitName: String?): String { + return (unitName ?: data.schoolShort)?.let { + this.replace("($it)", "").trim() + } ?: this + } + + init { + apiGetList( + TAG, + VULCAN_HEBE_ENDPOINT_ADDRESSBOOK, + HebeFilterType.BY_PERSON, + lastSync = lastSync, + includeFilterType = false + ) { list, _ -> + list.forEach { person -> + val id = person.getString("Id") ?: return@forEach + val loginId = person.getString("LoginId") ?: return@forEach + + val idType = id.split("-") + .getOrNull(0) + val idLong = id.split("-") + .getOrNull(1) + ?.toLongOrNull() + ?: return@forEach + + val typeBase = when (idType) { + "e" -> TYPE_TEACHER + "c" -> TYPE_PARENT + "p" -> TYPE_STUDENT + else -> TYPE_OTHER + } + + val name = person.getString("Name") ?: "" + val surname = person.getString("Surname") ?: "" + val namePrefix = "$surname $name - " + + val teacher = data.teacherList[idLong] ?: Teacher( + data.profileId, + idLong, + name, + surname, + loginId + ).also { + data.teacherList[idLong] = it + } + + person.getJsonArray("Roles")?.asJsonObjectList()?.onEach { role -> + var roleText: String? = null + val unitName = role.getString("ConstituentUnitSymbol") + + val personType = when (role.getInt("RoleOrder")) { + 0 -> { /* Wychowawca */ + roleText = role.getString("ClassSymbol") + ?.removeUnitName(unitName) + TYPE_EDUCATOR + } + 1 -> TYPE_TEACHER /* Nauczyciel */ + 2 -> return@onEach /* Pracownik */ + 3 -> { /* Rada rodziców */ + roleText = role.getString("Address") + ?.removeUnitName(unitName) + ?.removePrefix(namePrefix) + ?.trim() + TYPE_PARENTS_COUNCIL + } + 5 -> { + roleText = role.getString("RoleName") + ?.plus(" - ") + ?.plus( + role.getString("Address") + ?.removeUnitName(unitName) + ?.removePrefix(namePrefix) + ?.trim() + ) + TYPE_STUDENT + } + else -> TYPE_OTHER + } + + teacher.setTeacherType(personType) + teacher.typeDescription = roleText + } + + if (teacher.type == 0) + teacher.setTeacherType(typeBase) + } + + data.setSyncNext(ENDPOINT_VULCAN_HEBE_ADDRESSBOOK, 2 * DAY) + onSuccess(ENDPOINT_VULCAN_HEBE_ADDRESSBOOK) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeAttendance.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeAttendance.kt new file mode 100644 index 00000000..9f3dcaea --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeAttendance.kt @@ -0,0 +1,145 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2021-2-21 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_ATTENDANCE +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_HEBE_ATTENDANCE +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* + +class VulcanHebeAttendance( + override val data: DataVulcan, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : VulcanHebe(data, lastSync) { + + companion object { + const val TAG = "VulcanHebeAttendance" + } + + init { + val semesterNumber = data.studentSemesterNumber + val startDate = profile?.getSemesterStart(semesterNumber) + val endDate = profile?.getSemesterEnd(semesterNumber) + + apiGetList( + TAG, + VULCAN_HEBE_ENDPOINT_ATTENDANCE, + HebeFilterType.BY_PUPIL, + dateFrom = startDate, + dateTo = endDate, + lastSync = lastSync + ) { list, _ -> + list.forEach { attendance -> + val id = attendance.getLong("Id") ?: return@forEach + val type = attendance.getJsonObject("PresenceType") ?: return@forEach + val baseType = getBaseType(type) + val typeName = type.getString("Name") ?: return@forEach + val typeCategoryId = type.getLong("CategoryId") ?: return@forEach + val typeSymbol = type.getString("Symbol") ?: return@forEach + val typeShort = when (typeCategoryId.toInt()) { + 6, 8 -> typeSymbol + else -> data.app.attendanceManager.getTypeShort(baseType) + } + val typeColor = when (typeCategoryId.toInt()) { + 1 -> 0xffffffff // obecność + 2 -> 0xffffa687 // nieobecność + 3 -> 0xfffcc150 // nieobecność usprawiedliwiona + 4 -> 0xffede049 // spóźnienie + 5 -> 0xffbbdd5f // spóźnienie usprawiedliwione + 6 -> 0xffa9c9fd // nieobecny z przyczyn szkolnych + 7 -> 0xffddbbe5 // zwolniony + 8 -> 0xffffffff // usunięty wpis + else -> null + }?.toInt() + val date = getDate(attendance, "Day") ?: return@forEach + val lessonRange = getLessonRange(attendance, "TimeSlot") + val startTime = lessonRange?.startTime + val semester = profile?.dateToSemester(date) ?: return@forEach + val teacherId = attendance.getJsonObject("TeacherPrimary")?.getLong("Id") ?: -1 + val subjectId = attendance.getJsonObject("Subject")?.getLong("Id") ?: -1 + val addedDate = getDateTime(attendance, "DateModify") + val lessonNumber = lessonRange?.lessonNumber + val isCounted = attendance.getBoolean("CalculatePresence") + ?: (baseType != Attendance.TYPE_RELEASED) + + val attendanceObject = Attendance( + profileId = profileId, + id = id, + baseType = baseType, + typeName = typeName, + typeShort = typeShort, + typeSymbol = typeSymbol, + typeColor = typeColor, + date = date, + startTime = startTime, + semester = semester, + teacherId = teacherId, + subjectId = subjectId, + addedDate = addedDate + ).also { + it.lessonTopic = attendance.getString("Topic") + it.lessonNumber = lessonNumber + it.isCounted = isCounted + } + + data.attendanceList.add(attendanceObject) + if (baseType != Attendance.TYPE_PRESENT) { + data.metadataList.add( + Metadata( + profileId, + Metadata.TYPE_ATTENDANCE, + attendanceObject.id, + profile?.empty ?: true + || baseType == Attendance.TYPE_PRESENT_CUSTOM + || baseType == Attendance.TYPE_UNKNOWN, + profile?.empty ?: true + || baseType == Attendance.TYPE_PRESENT_CUSTOM + || baseType == Attendance.TYPE_UNKNOWN + ) + ) + } + } + + data.setSyncNext(ENDPOINT_VULCAN_HEBE_ATTENDANCE, SYNC_ALWAYS) + onSuccess(ENDPOINT_VULCAN_HEBE_ATTENDANCE) + } + } + + fun getBaseType(attendanceType: JsonObject): Int { + val absent = attendanceType.getBoolean("Absence") ?: false + val excused = attendanceType.getBoolean("AbsenceJustified") ?: false + return if (absent) { + if (excused) + Attendance.TYPE_ABSENT_EXCUSED + else + Attendance.TYPE_ABSENT + } else { + val belated = attendanceType.getBoolean("Late") ?: false + val released = attendanceType.getBoolean("LegalAbsence") ?: false + val present = attendanceType.getBoolean("Presence") ?: true + if (belated) + if (excused) + Attendance.TYPE_BELATED_EXCUSED + else + Attendance.TYPE_BELATED + else if (released) + Attendance.TYPE_RELEASED + else if (present) + if (attendanceType.getInt("CategoryId") != 1) + Attendance.TYPE_PRESENT_CUSTOM + else + Attendance.TYPE_PRESENT + else + Attendance.TYPE_UNKNOWN + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeExams.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeExams.kt new file mode 100644 index 00000000..308a3e26 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeExams.kt @@ -0,0 +1,86 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-21. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_EXAMS +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_HEBE_EXAMS +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.getLong +import pl.szczodrzynski.edziennik.ext.getString + +class VulcanHebeExams( + override val data: DataVulcan, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : VulcanHebe(data, lastSync) { + companion object { + const val TAG = "VulcanHebeExams" + } + + init { + apiGetList( + TAG, + VULCAN_HEBE_ENDPOINT_EXAMS, + HebeFilterType.BY_PUPIL, + lastSync = lastSync + ) { list, _ -> + list.forEach { exam -> + val id = exam.getLong("Id") ?: return@forEach + val eventDate = getDate(exam, "Deadline") ?: return@forEach + val subjectId = getSubjectId(exam, "Subject") ?: -1 + val teacherId = getTeacherId(exam, "Creator") ?: -1 + val teamId = getTeamId(exam, "Distribution") + ?: getClassId(exam, "Class") + ?: data.teamClass?.id + ?: -1 + val topic = exam.getString("Content")?.trim() ?: "" + + if (!isCurrentYear(eventDate)) return@forEach + + val lessonList = data.db.timetableDao().getAllForDateNow(profileId, eventDate) + val startTime = lessonList.firstOrNull { it.subjectId == subjectId }?.startTime + + val type = when (exam.getString("Type")) { + "Praca klasowa", + "Sprawdzian" -> Event.TYPE_EXAM + "Kartkówka" -> Event.TYPE_SHORT_QUIZ + else -> Event.TYPE_DEFAULT + } + + val eventObject = Event( + profileId = profileId, + id = id, + date = eventDate, + time = startTime, + topic = topic, + color = null, + type = type, + teacherId = teacherId, + subjectId = subjectId, + teamId = teamId + ) + + data.eventList.add(eventObject) + data.metadataList.add( + Metadata( + profileId, + Metadata.TYPE_EVENT, + id, + profile?.empty ?: true, + profile?.empty ?: true + ) + ) + } + + data.setSyncNext(ENDPOINT_VULCAN_HEBE_EXAMS, SYNC_ALWAYS) + onSuccess(ENDPOINT_VULCAN_HEBE_EXAMS) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeGradeSummary.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeGradeSummary.kt new file mode 100644 index 00000000..390b0383 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeGradeSummary.kt @@ -0,0 +1,88 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-22. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_GRADE_SUMMARY +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_HEBE_GRADE_SUMMARY +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.db.entity.Grade +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.ext.DAY +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.utils.Utils + +class VulcanHebeGradeSummary( + override val data: DataVulcan, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : VulcanHebe(data, lastSync) { + companion object { + const val TAG = "VulcanHebeGradeSummary" + } + + init { + val entries = mapOf( + "Entry_1" to + if (data.studentSemesterNumber == 1) + Grade.TYPE_SEMESTER1_PROPOSED + else Grade.TYPE_SEMESTER2_PROPOSED, + "Entry_2" to + if (data.studentSemesterNumber == 1) + Grade.TYPE_SEMESTER1_FINAL + else Grade.TYPE_SEMESTER2_FINAL + ) + + apiGetList( + TAG, + VULCAN_HEBE_ENDPOINT_GRADE_SUMMARY, + HebeFilterType.BY_PUPIL, + lastSync = lastSync + ) { list, _ -> + list.forEach { grade -> + val subjectId = getSubjectId(grade, "Subject") ?: return@forEach + val addedDate = getDateTime(grade, "DateModify") + + entries.onEach { (key, type) -> + val id = subjectId * -100 - type + val entry = grade.getString(key) ?: return@onEach + val value = Utils.getGradeValue(entry) + val color = Utils.getVulcanGradeColor(entry) + + val gradeObject = Grade( + profileId = profileId, + id = id, + name = entry, + type = type, + value = value, + weight = 0f, + color = color, + category = "", + description = null, + comment = null, + semester = data.studentSemesterNumber, + teacherId = -1, + subjectId = subjectId, + addedDate = addedDate + ) + + data.gradeList.add(gradeObject) + data.metadataList.add( + Metadata( + profileId, + Metadata.TYPE_GRADE, + id, + profile?.empty ?: true, + profile?.empty ?: true + ) + ) + } + } + + data.setSyncNext(ENDPOINT_VULCAN_HEBE_GRADE_SUMMARY, 1 * DAY) + onSuccess(ENDPOINT_VULCAN_HEBE_GRADE_SUMMARY) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeGrades.kt new file mode 100644 index 00000000..f345b9e5 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeGrades.kt @@ -0,0 +1,126 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-20. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_GRADES +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_HEBE_GRADES +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.db.entity.Grade +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* +import java.text.DecimalFormat +import kotlin.math.roundToInt + +class VulcanHebeGrades( + override val data: DataVulcan, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : VulcanHebe(data, lastSync) { + companion object { + const val TAG = "VulcanHebeGrades" + } + + init { + apiGetList( + TAG, + VULCAN_HEBE_ENDPOINT_GRADES, + HebeFilterType.BY_PUPIL, + lastSync = lastSync + ) { list, _ -> + list.forEach { grade -> + val id = grade.getLong("Id") ?: return@forEach + + val column = grade.getJsonObject("Column") + val category = column.getJsonObject("Category") + val categoryText = category.getString("Name") + + val teacherId = getTeacherId(grade, "Creator") ?: -1 + val subjectId = getSubjectId(column, "Subject") ?: -1 + + val description = column.getString("Name") + val comment = grade.getString("Comment") + var value = grade.getFloat("Value") + var weight = column.getFloat("Weight") ?: 0.0f + val numerator = grade.getFloat("Numerator ") + val denominator = grade.getFloat("Denominator") + val addedDate = getDateTime(grade, "DateModify") + + var finalDescription = "" + + var name = when (numerator != null && denominator != null) { + true -> { + value = numerator / denominator + finalDescription += DecimalFormat("#.##").format(numerator) + + "/" + DecimalFormat("#.##").format(denominator) + weight = 0.0f + (value * 100).roundToInt().toString() + "%" + } + else -> { + if (value == null) weight = 0.0f + + grade.getString("Content") ?: "" + } + } + + comment?.also { + if (name == "") name = it + else finalDescription = (if (finalDescription == "") "" else " ") + it + } + + description?.also { + finalDescription = (if (finalDescription == "") "" else " - ") + it + } + + val columnColor = column.getInt("Color") ?: 0 + val color = if (columnColor == 0) + when (name) { + "1-", "1", "1+" -> 0xffd65757 + "2-", "2", "2+" -> 0xff9071b3 + "3-", "3", "3+" -> 0xffd2ab24 + "4-", "4", "4+" -> 0xff50b6d6 + "5-", "5", "5+" -> 0xff2cbd92 + "6-", "6", "6+" -> 0xff91b43c + else -> 0xff3D5F9C + }.toInt() + else + columnColor + + val gradeObject = Grade( + profileId = profileId, + id = id, + name = name, + type = Grade.TYPE_NORMAL, + value = value ?: 0.0f, + weight = weight, + color = color, + category = categoryText, + description = finalDescription, + comment = null, + semester = getSemester(column), + teacherId = teacherId, + subjectId = subjectId, + addedDate = addedDate + ) + + data.gradeList.add(gradeObject) + data.metadataList.add( + Metadata( + profileId, + Metadata.TYPE_GRADE, + id, + profile?.empty ?: true, + profile?.empty ?: true + ) + ) + } + + data.setSyncNext(ENDPOINT_VULCAN_HEBE_GRADES, SYNC_ALWAYS) + onSuccess(ENDPOINT_VULCAN_HEBE_GRADES) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeHomework.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeHomework.kt new file mode 100644 index 00000000..06eea284 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeHomework.kt @@ -0,0 +1,94 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-21. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_HOMEWORK +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_HEBE_HOMEWORK +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.asJsonObjectList +import pl.szczodrzynski.edziennik.ext.getJsonArray +import pl.szczodrzynski.edziennik.ext.getLong +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.utils.Utils + +class VulcanHebeHomework( + override val data: DataVulcan, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : VulcanHebe(data, lastSync) { + companion object { + const val TAG = "VulcanHebeHomework" + } + + init { + apiGetList( + TAG, + VULCAN_HEBE_ENDPOINT_HOMEWORK, + HebeFilterType.BY_PUPIL, + lastSync = lastSync + ) { list, _ -> + list.forEach { exam -> + val id = exam.getLong("IdHomework") ?: return@forEach + val eventDate = getDate(exam, "Deadline") ?: return@forEach + val subjectId = getSubjectId(exam, "Subject") ?: -1 + val teacherId = getTeacherId(exam, "Creator") ?: -1 + val teamId = data.teamClass?.id ?: -1 + val topic = exam.getString("Content")?.trim() ?: "" + + if (!isCurrentYear(eventDate)) return@forEach + + val lessonList = data.db.timetableDao().getAllForDateNow(profileId, eventDate) + val startTime = lessonList.firstOrNull { it.subjectId == subjectId }?.startTime + + val eventObject = Event( + profileId = profileId, + id = id, + date = eventDate, + time = startTime, + topic = topic, + color = null, + type = Event.TYPE_HOMEWORK, + teacherId = teacherId, + subjectId = subjectId, + teamId = teamId + ) + + val attachments = exam.getJsonArray("Attachments") + ?.asJsonObjectList() + ?: return@forEach + + for (attachment in attachments) { + val fileName = attachment.getString("Name") ?: continue + val url = attachment.getString("Link") ?: continue + val attachmentName = "$fileName:$url" + val attachmentId = Utils.crc32(attachmentName.toByteArray()) + + eventObject.addAttachment( + id = attachmentId, + name = attachmentName + ) + } + + data.eventList.add(eventObject) + data.metadataList.add( + Metadata( + profileId, + Metadata.TYPE_HOMEWORK, + id, + profile?.empty ?: true, + profile?.empty ?: true + ) + ) + } + + data.setSyncNext(ENDPOINT_VULCAN_HEBE_HOMEWORK, SYNC_ALWAYS) + onSuccess(ENDPOINT_VULCAN_HEBE_HOMEWORK) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeLuckyNumber.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeLuckyNumber.kt new file mode 100644 index 00000000..bfa07399 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeLuckyNumber.kt @@ -0,0 +1,72 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-22. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_LUCKY_NUMBER +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_HEBE_LUCKY_NUMBER +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.db.entity.LuckyNumber +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.getInt +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time +import pl.szczodrzynski.edziennik.utils.models.Week + +class VulcanHebeLuckyNumber( + override val data: DataVulcan, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : VulcanHebe(data, lastSync) { + companion object { + const val TAG = "VulcanHebeLuckyNumber" + } + + init { + apiGet( + TAG, + VULCAN_HEBE_ENDPOINT_LUCKY_NUMBER, + query = mapOf( + "constituentId" to data.studentConstituentId.toString(), + "day" to Date.getToday().stringY_m_d + ) + ) { lucky: JsonObject?, _ -> + // sync tomorrow if lucky number set or is weekend or afternoon + var nextSync = Date.getToday().stepForward(0, 0, 1).inMillis + if (lucky == null) { + if (Date.getToday().weekDay <= Week.FRIDAY && Time.getNow().hour < 12) { + // working days morning, sync always + nextSync = SYNC_ALWAYS + } + } + else { + val luckyNumberDate = Date.fromY_m_d(lucky.getString("Day")) ?: Date.getToday() + val luckyNumber = lucky.getInt("Number") ?: -1 + val luckyNumberObject = LuckyNumber( + profileId = profileId, + date = luckyNumberDate, + number = luckyNumber + ) + + data.luckyNumberList.add(luckyNumberObject) + data.metadataList.add( + Metadata( + profileId, + Metadata.TYPE_LUCKY_NUMBER, + luckyNumberObject.date.value.toLong(), + true, + profile?.empty ?: false + ) + ) + } + + data.setSyncNext(ENDPOINT_VULCAN_HEBE_LUCKY_NUMBER, syncAt = nextSync) + onSuccess(ENDPOINT_VULCAN_HEBE_LUCKY_NUMBER) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeMain.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeMain.kt new file mode 100644 index 00000000..ea093d14 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeMain.kt @@ -0,0 +1,180 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-20. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import com.google.gson.JsonArray +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.LOGIN_TYPE_VULCAN +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_MAIN +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_HEBE_MAIN +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.models.Date + +class VulcanHebeMain( + override val data: DataVulcan, + override val lastSync: Long? = null +) : VulcanHebe(data, lastSync) { + companion object { + const val TAG = "VulcanHebeMain" + } + + fun getStudents( + profile: Profile?, + profileList: MutableList?, + loginStoreId: Int? = null, + firstProfileId: Int? = null, + onEmpty: (() -> Unit)? = null, + onSuccess: () -> Unit + ) { + if (profile == null && (profileList == null || loginStoreId == null || firstProfileId == null)) + throw IllegalArgumentException() + + apiGet( + TAG, + VULCAN_HEBE_ENDPOINT_MAIN, + query = mapOf("lastSyncDate" to "null"), + baseUrl = profile == null + ) { students: JsonArray, _ -> + if (students.isEmpty()) { + if (onEmpty != null) + onEmpty() + else + onSuccess() + return@apiGet + } + + // safe to assume this will be non-null when creating a profile + var profileId = firstProfileId ?: loginStoreId ?: 1 + + students.forEach { studentEl -> + val student = studentEl.asJsonObject + + val pupil = student.getJsonObject("Pupil") + val studentId = pupil.getInt("Id") ?: return@forEach + + // check the student ID in case of not first login + if (profile != null && data.studentId != studentId) + return@forEach + + val unit = student.getJsonObject("Unit") + val constituentUnit = student.getJsonObject("ConstituentUnit") + val login = student.getJsonObject("Login") + val periods = student.getJsonArray("Periods")?.map { + it.asJsonObject + } ?: listOf() + + val period = periods.firstOrNull { + it.getBoolean("Current", false) + } ?: return@forEach + + val periodLevel = period.getInt("Level") ?: return@forEach + val semester1 = periods.firstOrNull { + it.getInt("Level") == periodLevel && it.getInt("Number") == 1 + } + val semester2 = periods.firstOrNull { + it.getInt("Level") == periodLevel && it.getInt("Number") == 2 + } + + val schoolSymbol = unit.getString("Symbol") ?: return@forEach + val schoolShort = constituentUnit.getString("Short") ?: return@forEach + val schoolCode = "${data.symbol}_$schoolSymbol" + + val studentUnitId = unit.getInt("Id") ?: return@forEach + val studentConstituentId = constituentUnit.getInt("Id") ?: return@forEach + val studentLoginId = login.getInt("Id") ?: return@forEach + //val studentClassId = student.getInt("IdOddzial") ?: return@forEach + val studentClassName = student.getString("ClassDisplay") ?: return@forEach + val studentFirstName = pupil.getString("FirstName") ?: "" + val studentLastName = pupil.getString("Surname") ?: "" + val studentNameLong = "$studentFirstName $studentLastName".fixName() + val studentNameShort = "$studentFirstName ${studentLastName[0]}.".fixName() + val userLogin = login.getString("Value") ?: "" + + val studentSemesterId = period.getInt("Id") ?: return@forEach + val studentSemesterNumber = period.getInt("Number") ?: return@forEach + + val senderEntry = student.getJsonObject("SenderEntry") + val senderAddressName = senderEntry.getString("Address") + val senderAddressHash = senderEntry.getString("AddressHash") + + val hebeContext = student.getString("Context") + + val isParent = login.getString("LoginRole").equals("opiekun", ignoreCase = true) + val accountName = if (isParent) + login.getString("DisplayName")?.fixName() + else null + + val dateSemester1Start = semester1 + ?.getJsonObject("Start") + ?.getString("Date") + ?.let { Date.fromY_m_d(it) } + val dateSemester2Start = semester2 + ?.getJsonObject("Start") + ?.getString("Date") + ?.let { Date.fromY_m_d(it) } + val dateYearEnd = semester2 + ?.getJsonObject("End") + ?.getString("Date") + ?.let { Date.fromY_m_d(it) } + + val newProfile = profile ?: Profile( + profileId++, + loginStoreId!!, + LOGIN_TYPE_VULCAN, + studentNameLong, + userLogin, + studentNameLong, + studentNameShort, + accountName + ) + + newProfile.apply { + this.studentClassName = studentClassName + studentData["symbol"] = data.symbol + + studentData["studentId"] = studentId + studentData["studentUnitId"] = studentUnitId + studentData["studentConstituentId"] = studentConstituentId + studentData["studentLoginId"] = studentLoginId + studentData["studentSemesterId"] = studentSemesterId + studentData["studentSemesterNumber"] = studentSemesterNumber + studentData["semester1Id"] = semester1?.getInt("Id") ?: 0 + studentData["semester2Id"] = semester2?.getInt("Id") ?: 0 + studentData["schoolSymbol"] = schoolSymbol + studentData["schoolShort"] = schoolShort + studentData["schoolName"] = schoolCode + studentData["senderAddressName"] = senderAddressName + studentData["senderAddressHash"] = senderAddressHash + studentData["hebeContext"] = hebeContext + + // create the default TeamClass + data.getTeam( + id = null, + name = studentClassName, + schoolCode = schoolCode, + isTeamClass = true, + profileId = this.id, + ) + } + dateSemester1Start?.let { + newProfile.dateSemester1Start = it + newProfile.studentSchoolYearStart = it.year + } + dateSemester2Start?.let { newProfile.dateSemester2Start = it } + dateYearEnd?.let { newProfile.dateYearEnd = it } + + if (profile != null) + data.setSyncNext(ENDPOINT_VULCAN_HEBE_MAIN, 1 * DAY) + + profileList?.add(newProfile) + } + + onSuccess() + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeMessages.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeMessages.kt new file mode 100644 index 00000000..5d6e5da4 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeMessages.kt @@ -0,0 +1,151 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-21. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import androidx.core.util.set +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_MESSAGES +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_MESSAGES +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_HEBE_MESSAGES_INBOX +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_HEBE_MESSAGES_SENT +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.db.entity.* +import pl.szczodrzynski.edziennik.data.db.entity.Message.Companion.TYPE_DELETED +import pl.szczodrzynski.edziennik.data.db.entity.Message.Companion.TYPE_RECEIVED +import pl.szczodrzynski.edziennik.data.db.entity.Message.Companion.TYPE_SENT +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.Utils +import pl.szczodrzynski.navlib.crc16 + +class VulcanHebeMessages( + override val data: DataVulcan, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : VulcanHebe(data, lastSync) { + companion object { + const val TAG = "VulcanHebeMessagesInbox" + } + + private fun getPersonId(json: JsonObject): Long { + val senderLoginId = json.getInt("LoginId") ?: return -1 + /*if (senderLoginId == data.studentLoginId) + return -1*/ + + val senderName = json.getString("Address") ?: return -1 + val senderNameSplit = senderName.splitName() + val senderLoginIdStr = senderLoginId.toString() + val teacher = data.teacherList.singleOrNull { it.loginId == senderLoginIdStr } + ?: Teacher( + profileId, + -1 * crc16(senderName).toLong(), + senderNameSplit?.second ?: "", + senderNameSplit?.first ?: "", + senderLoginIdStr + ).also { + it.setTeacherType(Teacher.TYPE_OTHER) + data.teacherList[it.id] = it + } + return teacher.id + } + + fun getMessages(messageType: Int) { + val folder = when (messageType) { + TYPE_RECEIVED -> 1 + TYPE_SENT -> 2 + TYPE_DELETED -> 3 + else -> 1 + } + val endpointId = when (messageType) { + TYPE_RECEIVED -> ENDPOINT_VULCAN_HEBE_MESSAGES_INBOX + TYPE_SENT -> ENDPOINT_VULCAN_HEBE_MESSAGES_SENT + else -> ENDPOINT_VULCAN_HEBE_MESSAGES_INBOX + } + apiGetList( + TAG, + VULCAN_HEBE_ENDPOINT_MESSAGES, + HebeFilterType.BY_PERSON, + folder = folder, + lastSync = lastSync + ) { list, _ -> + list.forEach { message -> + val id = message.getLong("Id") ?: return@forEach + val subject = message.getString("Subject") ?: return@forEach + val body = message.getString("Content") ?: return@forEach + + val sender = message.getJsonObject("Sender") ?: return@forEach + + val sentDate = getDateTime(message, "DateSent") + val readDate = getDateTime(message, "DateRead", default = 0) + + if (!isCurrentYear(sentDate)) return@forEach + + val messageObject = Message( + profileId = profileId, + id = id, + type = messageType, + subject = subject, + body = body.replace("\n", "
    "), + senderId = if (messageType == TYPE_RECEIVED) getPersonId(sender) else null, + addedDate = sentDate + ) + + val receivers = message.getJsonArray("Receiver") + ?.asJsonObjectList() + ?: return@forEach + val receiverReadDate = + if (receivers.size == 1) readDate + else -1 + + for (receiver in receivers) { + val messageRecipientObject = MessageRecipient( + profileId, + if (messageType == TYPE_SENT) getPersonId(receiver) else -1, + -1, + receiverReadDate, + id + ) + data.messageRecipientList.add(messageRecipientObject) + } + + val attachments = message.getJsonArray("Attachments") + ?.asJsonObjectList() + ?: return@forEach + + for (attachment in attachments) { + val fileName = attachment.getString("Name") ?: continue + val url = attachment.getString("Link") ?: continue + val attachmentName = "$fileName:$url" + val attachmentId = Utils.crc32(attachmentName.toByteArray()) + + messageObject.addAttachment( + id = attachmentId, + name = attachmentName, + size = -1 + ) + } + + data.messageList.add(messageObject) + data.setSeenMetadataList.add( + Metadata( + profileId, + Metadata.TYPE_MESSAGE, + id, + readDate > 0 || messageType == TYPE_SENT, + readDate > 0 || messageType == TYPE_SENT + ) + ) + } + + data.setSyncNext( + endpointId, + if (messageType == TYPE_RECEIVED) SYNC_ALWAYS else 1 * DAY, + if (messageType == TYPE_RECEIVED) null else DRAWER_ITEM_MESSAGES + ) + onSuccess(endpointId) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeMessagesChangeStatus.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeMessagesChangeStatus.kt new file mode 100644 index 00000000..bd86cfce --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeMessagesChangeStatus.kt @@ -0,0 +1,65 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-21. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_MESSAGES_STATUS +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.api.events.MessageGetEvent +import pl.szczodrzynski.edziennik.data.db.entity.MessageRecipient +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.full.MessageFull +import pl.szczodrzynski.edziennik.ext.JsonObject + +class VulcanHebeMessagesChangeStatus( + override val data: DataVulcan, + private val messageObject: MessageFull, + val onSuccess: () -> Unit +) : VulcanHebe(data, null) { + companion object { + const val TAG = "VulcanHebeMessagesChangeStatus" + } + + init { + apiPost( + TAG, + VULCAN_HEBE_ENDPOINT_MESSAGES_STATUS, + payload = JsonObject( + "MessageId" to messageObject.id, + "LoginId" to data.studentLoginId, + "Status" to 1 + ) + ) { _: Boolean, _ -> + + if (!messageObject.seen) { + data.setSeenMetadataList.add( + Metadata( + profileId, + Metadata.TYPE_MESSAGE, + messageObject.id, + true, + true + ) + ) + messageObject.seen = true + } + + if (!messageObject.isSent) { + val messageRecipientObject = MessageRecipient( + profileId, + -1, + -1, + System.currentTimeMillis(), + messageObject.id + ) + data.messageRecipientList.add(messageRecipientObject) + } + + EventBus.getDefault().postSticky(MessageGetEvent(messageObject)) + onSuccess() + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeNotices.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeNotices.kt new file mode 100644 index 00000000..be1e0545 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeNotices.kt @@ -0,0 +1,78 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2021-2-22 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_NOTICES +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_HEBE_NOTICES +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.Notice +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.* + +class VulcanHebeNotices( + override val data: DataVulcan, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : VulcanHebe(data, lastSync) { + + companion object { + const val TAG = "VulcanHebeNotices" + } + + init { + apiGetList( + TAG, + VULCAN_HEBE_ENDPOINT_NOTICES, + HebeFilterType.BY_PUPIL, + lastSync = lastSync + ) { list, _ -> + list.forEach { notice -> + val id = notice.getLong("Id") ?: return@forEach + val type = when (notice.getBoolean("Positive")) { + true -> Notice.TYPE_POSITIVE + else -> Notice.TYPE_NEUTRAL + } + val date = getDate(notice, "DateValid") ?: return@forEach + val semester = profile?.dateToSemester(date) ?: return@forEach + val text = notice.getString("Content") ?: "" + val category = notice.getJsonObject("Category")?.getString("Name") + val points = notice.getFloat("Points") + val teacherId = getTeacherId(notice, "Creator") ?: -1 + val addedDate = getDateTime(notice, "DateModify") + + if (!isCurrentYear(date)) return@forEach + + val noticeObject = Notice( + profileId = profileId, + id = id, + type = type, + semester = semester, + text = text, + category = category, + points = points, + teacherId = teacherId, + addedDate = addedDate + ) + + data.noticeList.add(noticeObject) + data.metadataList.add( + Metadata( + profileId, + Metadata.TYPE_NOTICE, + id, + profile?.empty ?: true, + profile?.empty ?: true + ) + ) + } + + data.setSyncNext(ENDPOINT_VULCAN_HEBE_NOTICES, SYNC_ALWAYS) + onSuccess(ENDPOINT_VULCAN_HEBE_NOTICES) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebePushConfig.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebePushConfig.kt new file mode 100644 index 00000000..fdf81bcb --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebePushConfig.kt @@ -0,0 +1,36 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-22. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import com.google.gson.JsonPrimitive +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_PUSH_ALL +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_HEBE_PUSH_CONFIG +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS + +class VulcanHebePushConfig( + override val data: DataVulcan, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : VulcanHebe(data, lastSync) { + companion object { + const val TAG = "VulcanHebePushConfig" + } + + init { + apiPost( + TAG, + VULCAN_HEBE_ENDPOINT_PUSH_ALL, + payload = JsonPrimitive("on") + ) { _: Boolean, _ -> + // sync always: this endpoint has .shouldSync set + data.setSyncNext(ENDPOINT_VULCAN_HEBE_PUSH_CONFIG, SYNC_ALWAYS) + data.app.config.sync.tokenVulcanList = + data.app.config.sync.tokenVulcanList + profileId + onSuccess(ENDPOINT_VULCAN_HEBE_PUSH_CONFIG) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeSendMessage.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeSendMessage.kt new file mode 100644 index 00000000..e71c4089 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeSendMessage.kt @@ -0,0 +1,99 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-22. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import com.google.gson.JsonObject +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.ERROR_VULCAN_HEBE_MISSING_SENDER_ENTRY +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_MESSAGES_SEND +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.api.events.MessageSentEvent +import pl.szczodrzynski.edziennik.data.db.entity.Message +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.ext.* + +class VulcanHebeSendMessage( + override val data: DataVulcan, + val recipients: List, + val subject: String, + val text: String, + val onSuccess: () -> Unit +) : VulcanHebe(data, null) { + companion object { + const val TAG = "VulcanHebeSendMessage" + } + + init { + if (data.senderAddressName == null || data.senderAddressHash == null) { + VulcanHebeMain(data).getStudents(data.profile, null) { + if (data.senderAddressName == null || data.senderAddressHash == null) { + data.error(TAG, ERROR_VULCAN_HEBE_MISSING_SENDER_ENTRY) + } + else { + sendMessage() + } + } + } + else { + sendMessage() + } + } + + private fun sendMessage() { + val recipientsArray = JsonArray() + recipients.forEach { teacher -> + recipientsArray += JsonObject( + "Address" to teacher.fullNameLastFirst, + "LoginId" to (teacher.loginId?.toIntOrNull() ?: return@forEach), + "Initials" to teacher.initialsLastFirst, + "AddressHash" to teacher.fullNameLastFirst.sha1Hex() + ) + } + + val senderName = (profile?.accountName ?: profile?.studentNameLong) + ?.swapFirstLastName() ?: "" + val sender = JsonObject( + "Address" to data.senderAddressName, + "LoginId" to data.studentLoginId.toString(), + "Initials" to senderName.getNameInitials(), + "AddressHash" to data.senderAddressHash + ) + + apiPost( + TAG, + VULCAN_HEBE_ENDPOINT_MESSAGES_SEND, + payload = JsonObject( + "Status" to 1, + "Sender" to sender, + "DateSent" to null, + "DateRead" to null, + "Content" to text, + "Receiver" to recipientsArray, + "Id" to 0, + "Subject" to subject, + "Attachments" to null, + "Self" to null + ) + ) { json: JsonObject, _ -> + val messageId = json.getLong("Id") + + if (messageId == null) { + // TODO error + return@apiPost + } + + VulcanHebeMessages(data, null) { + val message = data.messageList.firstOrNull { it.isSent && it.subject == subject } + // val metadata = data.metadataList.firstOrNull { it.thingType == Metadata.TYPE_MESSAGE && it.thingId == messageId } + val event = MessageSentEvent(data.profileId, message, message?.addedDate) + + EventBus.getDefault().postSticky(event) + onSuccess() + }.getMessages(Message.TYPE_SENT) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeTeachers.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeTeachers.kt new file mode 100644 index 00000000..f01e0d6b --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeTeachers.kt @@ -0,0 +1,60 @@ +/* + * Copyright (c) Antoni Czaplicki 2021-10-15. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import androidx.room.OnConflictStrategy +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_TEACHERS +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_HEBE_TEACHERS +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.ext.DAY +import pl.szczodrzynski.edziennik.ext.getString + +class VulcanHebeTeachers( + override val data: DataVulcan, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit, +) : VulcanHebe(data, lastSync) { + companion object { + const val TAG = "VulcanHebeTeachers" + } + + init { + apiGetList( + TAG, + VULCAN_HEBE_ENDPOINT_TEACHERS, + HebeFilterType.BY_PERIOD, + lastSync = 0L, + ) { list, _ -> + list.forEach { person -> + val name = person.getString("Name") + val surname = person.getString("Surname") + val displayName = person.getString("DisplayName") + val subjectName = person.getString("Description") ?: return@forEach + + if (subjectName.isBlank()) { + return@forEach + } + + val teacher = data.getTeacherByFirstLast( + name?.plus(" ")?.plus(surname) ?: displayName ?: return@forEach + ) + + when (subjectName) { + "Pedagog" -> teacher.setTeacherType(Teacher.TYPE_PEDAGOGUE) + else -> { + val subjectId = data.getSubject(null, subjectName).id + if (!teacher.subjects.contains(subjectId)) + teacher.addSubject(subjectId) + } + } + } + data.teacherOnConflictStrategy = OnConflictStrategy.REPLACE + data.setSyncNext(ENDPOINT_VULCAN_HEBE_TEACHERS, 2 * DAY) + onSuccess(ENDPOINT_VULCAN_HEBE_TEACHERS) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeTimetable.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeTimetable.kt new file mode 100644 index 00000000..c20cf1bf --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeTimetable.kt @@ -0,0 +1,258 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-21. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_TIMETABLE +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_TIMETABLE_CHANGES +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_HEBE_TIMETABLE +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel +import pl.szczodrzynski.edziennik.data.db.entity.Lesson +import pl.szczodrzynski.edziennik.data.db.entity.Lesson.Companion.TYPE_CANCELLED +import pl.szczodrzynski.edziennik.data.db.entity.Lesson.Companion.TYPE_CHANGE +import pl.szczodrzynski.edziennik.data.db.entity.Lesson.Companion.TYPE_NORMAL +import pl.szczodrzynski.edziennik.data.db.entity.Lesson.Companion.TYPE_SHIFTED_SOURCE +import pl.szczodrzynski.edziennik.data.db.entity.Lesson.Companion.TYPE_SHIFTED_TARGET +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.getBoolean +import pl.szczodrzynski.edziennik.ext.getInt +import pl.szczodrzynski.edziennik.ext.getJsonObject +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.utils.Utils.d +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Week + +class VulcanHebeTimetable( + override val data: DataVulcan, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : VulcanHebe(data, lastSync) { + companion object { + const val TAG = "VulcanHebeTimetable" + } + + private val lessonList = mutableListOf() + private val lessonDates = mutableSetOf() + + init { + val previousWeekStart = Week.getWeekStart().stepForward(0, 0, -7) + if (Date.getToday().weekDay > 4) { + previousWeekStart.stepForward(0, 0, 7) + } + + val dateFrom = data.arguments + ?.getString("weekStart") + ?.let { Date.fromY_m_d(it) } + ?: previousWeekStart + val dateTo = dateFrom.clone().stepForward(0, 0, 13) + + val lastSync = 0L + + apiGetList( + TAG, + VULCAN_HEBE_ENDPOINT_TIMETABLE, + HebeFilterType.BY_PUPIL, + dateFrom = dateFrom, + dateTo = dateTo, + lastSync = lastSync + ) { lessons, _ -> + apiGetList( + TAG, + VULCAN_HEBE_ENDPOINT_TIMETABLE_CHANGES, + HebeFilterType.BY_PUPIL, + dateFrom = dateFrom, + dateTo = dateTo, + lastSync = lastSync + ) { changes, _ -> + processData(lessons, changes) + + // cancel lesson changes when caused by a shift + for (lesson in lessonList) { + if (lesson.type != TYPE_SHIFTED_TARGET) + continue + lessonList.firstOrNull { + it.oldDate == lesson.date + && it.oldLessonNumber == lesson.lessonNumber + && it.type == TYPE_CHANGE + }?.let { + it.type = TYPE_CANCELLED + it.date = null + it.lessonNumber = null + it.startTime = null + it.endTime = null + it.subjectId = null + it.teacherId = null + it.teamId = null + it.classroom = null + } + } + + // add TYPE_NO_LESSONS to empty dates + val date: Date = dateFrom.clone() + while (date <= dateTo) { + if (!lessonDates.contains(date.value)) { + lessonList.add(Lesson(profileId, date.value.toLong()).apply { + this.type = Lesson.TYPE_NO_LESSONS + this.date = date.clone() + }) + } + + date.stepForward(0, 0, 1) + } + + d( + TAG, + "Clearing lessons between ${dateFrom.stringY_m_d} and ${dateTo.stringY_m_d}" + ) + + data.toRemove.add(DataRemoveModel.Timetable.between(dateFrom, dateTo)) + + data.lessonList.addAll(lessonList) + + data.setSyncNext(ENDPOINT_VULCAN_HEBE_TIMETABLE, SYNC_ALWAYS) + onSuccess(ENDPOINT_VULCAN_HEBE_TIMETABLE) + } + } + } + + private fun buildLesson(changes: List, json: JsonObject): Pair? { + val lesson = Lesson(profileId, -1) + var lessonShift: Lesson? = null + + val lessonDate = getDate(json, "Date") ?: return null + val lessonRange = getLessonRange(json, "TimeSlot") + val startTime = lessonRange?.startTime + val endTime = lessonRange?.endTime + val teacherId = getTeacherId(json, "TeacherPrimary") + val classroom = json.getJsonObject("Room").getString("Code") + val subjectId = getSubjectId(json, "Subject") + + val teamId = getTeamId(json, "Distribution") + ?: getClassId(json, "Clazz") + ?: data.teamClass?.id + ?: -1 + + val change = json.getJsonObject("Change") + val changeId = change.getInt("Id") + val type = when (change.getInt("Type")) { + 1 -> TYPE_CANCELLED + 2 -> TYPE_CHANGE + 3 -> TYPE_SHIFTED_SOURCE + 4 -> TYPE_CANCELLED // TODO: 2021-02-21 add showing cancellation reason + else -> TYPE_NORMAL + } + + lesson.type = type + if (type == TYPE_NORMAL) { + lesson.date = lessonDate + lesson.lessonNumber = lessonRange?.lessonNumber + lesson.startTime = startTime + lesson.endTime = endTime + lesson.subjectId = subjectId + lesson.teacherId = teacherId + lesson.teamId = teamId + lesson.classroom = classroom + } else { + lesson.oldDate = lessonDate + lesson.oldLessonNumber = lessonRange?.lessonNumber + lesson.oldStartTime = startTime + lesson.oldEndTime = endTime + lesson.oldSubjectId = subjectId + lesson.oldTeacherId = teacherId + lesson.oldTeamId = teamId + lesson.oldClassroom = classroom + } + + if (type == TYPE_CHANGE || type == TYPE_SHIFTED_SOURCE) { + val changeJson = changes.firstOrNull { + it.getInt("Id") == changeId + } ?: return lesson to null + + val changeLessonDate = getDate(changeJson, "LessonDate") ?: return lesson to null + val changeLessonRange = getLessonRange(changeJson, "TimeSlot") ?: lessonRange + val changeStartTime = changeLessonRange?.startTime + val changeEndTime = changeLessonRange?.endTime + val changeTeacherId = getTeacherId(changeJson, "TeacherPrimary") ?: teacherId + val changeClassroom = changeJson.getJsonObject("Room").getString("Code") ?: classroom + val changeSubjectId = getSubjectId(changeJson, "Subject") ?: subjectId + + val changeTeamId = getTeamId(json, "Distribution") + ?: getClassId(json, "Clazz") + ?: teamId + + if (type != TYPE_CHANGE) { + /* lesson shifted */ + lessonShift = Lesson(profileId, -1) + lessonShift.type = TYPE_SHIFTED_TARGET + + // update source lesson with the target lesson date + lesson.date = changeLessonDate + lesson.lessonNumber = changeLessonRange?.lessonNumber + lesson.startTime = changeStartTime + lesson.endTime = changeEndTime + // update target lesson with the source lesson date + lessonShift.oldDate = lessonDate + lessonShift.oldLessonNumber = lessonRange?.lessonNumber + lessonShift.oldStartTime = startTime + lessonShift.oldEndTime = endTime + } + + (if (type == TYPE_CHANGE) lesson else lessonShift) + ?.apply { + this.date = changeLessonDate + this.lessonNumber = changeLessonRange?.lessonNumber + this.startTime = changeStartTime + this.endTime = changeEndTime + this.subjectId = changeSubjectId + this.teacherId = changeTeacherId + this.teamId = changeTeamId + this.classroom = changeClassroom + } + } + + return lesson to lessonShift + } + + private fun processData(lessons: List, changes: List) { + lessons.forEach { lessonJson -> + if (lessonJson.getBoolean("Visible") != true) + return@forEach + + val lessonPair = buildLesson(changes, lessonJson) ?: return@forEach + val (lessonObject, lessonShift) = lessonPair + + when { + lessonShift != null -> lessonShift + lessonObject.type != TYPE_NORMAL -> lessonObject + else -> null + }?.let { lesson -> + val lessonDate = lesson.displayDate ?: return@let + val seen = profile?.empty ?: true || lessonDate < Date.getToday() + data.metadataList.add( + Metadata( + profileId, + Metadata.TYPE_LESSON_CHANGE, + lesson.id, + seen, + seen + ) + ) + } + + lessonObject.id = lessonObject.buildId() + lessonShift?.id = lessonShift?.buildId() ?: -1 + + lessonList.add(lessonObject) + lessonShift?.let { lessonList.add(it) } + + lessonObject.displayDate?.let { lessonDates.add(it.value) } + lessonShift?.displayDate?.let { lessonDates.add(it.value) } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/web/HomepageTile.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/web/HomepageTile.kt new file mode 100644 index 00000000..4d657ac7 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/web/HomepageTile.kt @@ -0,0 +1,16 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-20. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.web + +import com.google.gson.annotations.SerializedName + +data class HomepageTile( + @SerializedName("Nazwa") + val name: String?, + @SerializedName("Url") + val url: String?, + @SerializedName("Zawartosc") + val children: List +) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/web/VulcanWebLuckyNumber.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/web/VulcanWebLuckyNumber.kt new file mode 100644 index 00000000..adb4363d --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/web/VulcanWebLuckyNumber.kt @@ -0,0 +1,86 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-20. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.web + +import pl.szczodrzynski.edziennik.data.api.VULCAN_WEB_ENDPOINT_LUCKY_NUMBER +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_WEB_LUCKY_NUMBERS +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanWebMain +import pl.szczodrzynski.edziennik.data.db.entity.LuckyNumber +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS +import pl.szczodrzynski.edziennik.ext.DAY +import pl.szczodrzynski.edziennik.ext.getJsonArray +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time +import pl.szczodrzynski.edziennik.utils.models.Week + +class VulcanWebLuckyNumber(override val data: DataVulcan, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : VulcanWebMain(data, lastSync) { + companion object { + const val TAG = "VulcanWebLuckyNumber" + } + + init { + webGetJson(TAG, WEB_MAIN, VULCAN_WEB_ENDPOINT_LUCKY_NUMBER, parameters = mapOf( + "permissions" to data.webPermissions + )) { json, _ -> + val tiles = json + .getJsonArray("data") + ?.mapNotNull { data.app.gson.fromJson(it.toString(), HomepageTile::class.java) } + ?.flatMap { it.children } + + if (tiles == null) { + data.setSyncNext(ENDPOINT_VULCAN_WEB_LUCKY_NUMBERS, SYNC_ALWAYS) + onSuccess(ENDPOINT_VULCAN_WEB_LUCKY_NUMBERS) + return@webGetJson + } + + var nextSync = System.currentTimeMillis() + 1* DAY *1000 + + tiles.firstOrNull { it.name == data.schoolShort }?.children?.firstOrNull()?.let { tile -> + // "Szczęśliwy numer w dzienniku: 16" + return@let tile.name?.substringAfterLast(' ')?.toIntOrNull()?.let { number -> + // lucky number present + val luckyNumberObject = LuckyNumber( + profileId, + Date.getToday(), + number + ) + + data.luckyNumberList.add(luckyNumberObject) + data.metadataList.add( + Metadata( + profileId, + Metadata.TYPE_LUCKY_NUMBER, + luckyNumberObject.date.value.toLong(), + true, + profile?.empty ?: false + )) + } + } ?: run { + // no lucky number + if (Date.getToday().weekDay <= Week.FRIDAY && Time.getNow().hour >= 22) { + // working days, after 10PM + // consider the lucky number is disabled; sync in 4 days + nextSync = System.currentTimeMillis() + 4* DAY *1000 + } + else if (Date.getToday().weekDay <= Week.FRIDAY && Time.getNow().hour < 22) { + // working days, before 10PM + + } + else { + // weekends + nextSync = Week.getNearestWeekDayDate(Week.MONDAY).combineWith(Time(5, 0, 0)) + } + } + + data.setSyncNext(ENDPOINT_VULCAN_WEB_LUCKY_NUMBERS, SYNC_ALWAYS) + onSuccess(ENDPOINT_VULCAN_WEB_LUCKY_NUMBERS) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/firstlogin/VulcanFirstLogin.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/firstlogin/VulcanFirstLogin.kt new file mode 100644 index 00000000..61502488 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/firstlogin/VulcanFirstLogin.kt @@ -0,0 +1,129 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-10-19 + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.firstlogin + +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanWebMain +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe.VulcanHebeMain +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.login.CufsCertificate +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.login.VulcanLoginHebe +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.login.VulcanLoginWebMain +import pl.szczodrzynski.edziennik.data.api.events.FirstLoginFinishedEvent +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.getJsonObject +import pl.szczodrzynski.edziennik.ext.getString + +class VulcanFirstLogin(val data: DataVulcan, val onSuccess: () -> Unit) { + companion object { + const val TAG = "VulcanFirstLogin" + } + + private val web = VulcanWebMain(data, null) + private val hebe = VulcanHebe(data, null) + private val profileList = mutableListOf() + private val loginStoreId = data.loginStore.id + private var firstProfileId = loginStoreId + private val tryingSymbols = mutableListOf() + + init { + if (data.loginStore.mode == LOGIN_MODE_VULCAN_WEB) { + VulcanLoginWebMain(data) { + val xml = web.readCertificate() ?: run { + data.error(ApiError(TAG, ERROR_VULCAN_WEB_NO_CERTIFICATE)) + return@VulcanLoginWebMain + } + val certificate = web.parseCertificate(xml) + + if (data.symbol != null && data.symbol != "default") { + tryingSymbols += data.symbol ?: "default" + } + else { + + tryingSymbols += certificate.userInstances + } + + checkSymbol(certificate) + } + } + else { + registerDeviceHebe { + EventBus.getDefault().postSticky(FirstLoginFinishedEvent(profileList, data.loginStore)) + onSuccess() + } + } + } + + private fun checkSymbol(certificate: CufsCertificate) { + if (tryingSymbols.isEmpty()) { + EventBus.getDefault().postSticky(FirstLoginFinishedEvent(profileList, data.loginStore)) + onSuccess() + return + } + + val result = web.postCertificate(certificate, tryingSymbols.removeAt(0)) { symbol, state -> + when (state) { + VulcanWebMain.STATE_NO_REGISTER -> { + checkSymbol(certificate) + } + VulcanWebMain.STATE_LOGGED_OUT -> data.error(ApiError(TAG, ERROR_VULCAN_WEB_LOGGED_OUT)) + VulcanWebMain.STATE_SUCCESS -> { + webRegisterDevice(symbol) { + checkSymbol(certificate) + } + } + } + } + + // postCertificate returns false if the cert is not valid anymore + if (!result) { + data.error(ApiError(TAG, ERROR_VULCAN_WEB_CERTIFICATE_EXPIRED) + .withApiResponse(certificate.xml)) + } + } + + private fun webRegisterDevice(symbol: String, onSuccess: () -> Unit) { + web.getStartPage(symbol, postErrors = false) { _, schoolSymbols -> + if (schoolSymbols.isEmpty()) { + onSuccess() + return@getStartPage + } + data.symbol = symbol + val schoolSymbol = data.schoolSymbol ?: schoolSymbols.firstOrNull() + web.webGetJson(TAG, VulcanWebMain.WEB_NEW, "$schoolSymbol/$VULCAN_WEB_ENDPOINT_REGISTER_DEVICE") { result, _ -> + val json = result.getJsonObject("data") + data.symbol = symbol + data.apiToken = data.apiToken.toMutableMap().also { + it[symbol] = json.getString("TokenKey") + } + data.apiPin = data.apiPin.toMutableMap().also { + it[symbol] = json.getString("PIN") + } + registerDeviceHebe(onSuccess) + } + } + } + + private fun registerDeviceHebe(onSuccess: () -> Unit) { + VulcanLoginHebe(data) { + VulcanHebeMain(data).getStudents( + profile = null, + profileList, + loginStoreId, + firstProfileId, + onEmpty = { + EventBus.getDefault() + .postSticky(FirstLoginFinishedEvent(listOf(), data.loginStore)) + onSuccess() + }, + onSuccess = onSuccess + ) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/login/CufsCertificate.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/login/CufsCertificate.kt new file mode 100644 index 00000000..45fc96d2 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/login/CufsCertificate.kt @@ -0,0 +1,23 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-17. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.login + +import pl.droidsonroids.jspoon.annotation.Selector + +class CufsCertificate { + @Selector(value = "EndpointReference Address") + var targetUrl: String = "" + + @Selector(value = "Lifetime Created") + var createdDate: String = "" + + @Selector(value = "Lifetime Expires") + var expiryDate: String = "" + + @Selector(value = "Attribute[AttributeName=UserInstance] AttributeValue") + var userInstances: List = listOf() + + var xml = "" +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/login/VulcanLogin.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/login/VulcanLogin.kt new file mode 100644 index 00000000..3cbb7ea7 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/login/VulcanLogin.kt @@ -0,0 +1,59 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-6. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.login + +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_VULCAN_HEBE +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_VULCAN_WEB_MAIN +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.utils.Utils + +class VulcanLogin(val data: DataVulcan, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "VulcanLogin" + } + + private var cancelled = false + + init { + nextLoginMethod(onSuccess) + } + + private fun nextLoginMethod(onSuccess: () -> Unit) { + if (data.targetLoginMethodIds.isEmpty()) { + onSuccess() + return + } + if (cancelled) { + onSuccess() + return + } + useLoginMethod(data.targetLoginMethodIds.removeAt(0)) { usedMethodId -> + data.progress(data.progressStep) + if (usedMethodId != -1) + data.loginMethods.add(usedMethodId) + nextLoginMethod(onSuccess) + } + } + + private fun useLoginMethod(loginMethodId: Int, onSuccess: (usedMethodId: Int) -> Unit) { + // this should never be true + if (data.loginMethods.contains(loginMethodId)) { + onSuccess(-1) + return + } + Utils.d(TAG, "Using login method $loginMethodId") + when (loginMethodId) { + LOGIN_METHOD_VULCAN_WEB_MAIN -> { + data.startProgress(R.string.edziennik_progress_login_vulcan_web_main) + VulcanLoginWebMain(data) { onSuccess(loginMethodId) } + } + LOGIN_METHOD_VULCAN_HEBE -> { + data.startProgress(R.string.edziennik_progress_login_vulcan_api) + VulcanLoginHebe(data) { onSuccess(loginMethodId) } + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/login/VulcanLoginHebe.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/login/VulcanLoginHebe.kt new file mode 100644 index 00000000..241f249a --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/login/VulcanLoginHebe.kt @@ -0,0 +1,110 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-20. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.login + +import com.google.gson.JsonObject +import io.github.wulkanowy.signer.hebe.generateKeyPair +import pl.szczodrzynski.edziennik.data.api.ERROR_LOGIN_DATA_MISSING +import pl.szczodrzynski.edziennik.data.api.VULCAN_API_DEVICE_NAME +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_REGISTER_NEW +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.api.szkolny.SzkolnyApi +import pl.szczodrzynski.edziennik.ext.JsonObject +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty + +class VulcanLoginHebe(val data: DataVulcan, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "VulcanLoginHebe" + } + + init { run { + // i'm sure this does something useful + // not quite sure what, though + if (data.studentSemesterNumber == 1 && data.semester1Id == 0) + data.semester1Id = data.studentSemesterNumber + if (data.studentSemesterNumber == 2 && data.semester2Id == 0) + data.semester2Id = data.studentSemesterNumber + + copyFromLoginStore() + + if (data.profile != null && data.isHebeLoginValid()) { + onSuccess() + } + else { + if (data.symbol.isNotNullNorEmpty() && data.apiToken[data.symbol].isNotNullNorEmpty() && data.apiPin[data.symbol].isNotNullNorEmpty()) { + loginWithToken() + } + else { + data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) + } + } + }} + + private fun copyFromLoginStore() { + data.loginStore.data.apply { + // map form inputs to the symbol + if (has("symbol")) { + data.symbol = getString("symbol") + remove("symbol") + } + if (has("deviceToken")) { + data.apiToken = data.apiToken.toMutableMap().also { + it[data.symbol] = getString("deviceToken") + } + remove("deviceToken") + } + if (has("devicePin")) { + data.apiPin = data.apiPin.toMutableMap().also { + it[data.symbol] = getString("devicePin") + } + remove("devicePin") + } + } + } + + private fun loginWithToken() { + val szkolnyApi = SzkolnyApi(data.app) + val hebe = VulcanHebe(data, null) + + if (data.hebePublicKey == null || data.hebePrivateKey == null || data.hebePublicHash == null) { + val (publicPem, privatePem, publicHash) = generateKeyPair() + data.hebePublicKey = publicPem + data.hebePrivateKey = privatePem + data.hebePublicHash = publicHash + } + + val firebaseToken = szkolnyApi.runCatching({ + getFirebaseToken("vulcan") + }, onError = { + // screw errors + }) ?: data.app.config.sync.tokenVulcan + + hebe.apiPost( + TAG, + VULCAN_HEBE_ENDPOINT_REGISTER_NEW, + payload = JsonObject( + "OS" to "Android", + "PIN" to data.apiPin[data.symbol], + "Certificate" to data.hebePublicKey, + "CertificateType" to "RSA_PEM", + "DeviceModel" to VULCAN_API_DEVICE_NAME, + "SecurityToken" to data.apiToken[data.symbol], + "SelfIdentifier" to data.buildDeviceId(), + "CertificateThumbprint" to data.hebePublicHash + ), + baseUrl = true, + firebaseToken = firebaseToken + ) { _: JsonObject, _ -> + data.apiToken = data.apiToken.toMutableMap().also { + it[data.symbol] = it[data.symbol]?.substring(0, 3) + } + data.loginStore.removeLoginData("apiPin") + onSuccess() + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/login/VulcanLoginWebMain.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/login/VulcanLoginWebMain.kt new file mode 100644 index 00000000..3160ceb2 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/login/VulcanLoginWebMain.kt @@ -0,0 +1,128 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-16. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.login + +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanWebMain +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.fslogin.FSLogin +import pl.szczodrzynski.fslogin.realm.toRealm + +class VulcanLoginWebMain(val data: DataVulcan, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "VulcanLoginWebMain" + } + + private val web by lazy { VulcanWebMain(data, null) } + + init { run { + copyFromLoginStore() + + if (data.profile != null && data.isWebMainLoginValid()) { + onSuccess() + } + else { + if (data.symbol.isNotNullNorEmpty() + && data.webRealmData != null + && (data.webEmail.isNotNullNorEmpty() || data.webUsername.isNotNullNorEmpty()) + && data.webPassword.isNotNullNorEmpty()) { + try { + val success = loginWithCredentials() + if (!success) + data.error(ApiError(TAG, ERROR_VULCAN_WEB_DATA_MISSING)) + } catch (e: Exception) { + data.error(ApiError(TAG, EXCEPTION_VULCAN_WEB_LOGIN) + .withThrowable(e)) + } + } + else { + data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) + } + } + }} + + private fun copyFromLoginStore() { + data.loginStore.data.apply { + // 4.0 - new login form - copy user input to profile + if (has("symbol")) { + data.symbol = getString("symbol") + remove("symbol") + } + // 4.6 - form inputs renamed + if (has("email")) { + data.webEmail = getString("email") + remove("email") + } + if (has("username")) { + data.webUsername = getString("username") + remove("username") + } + if (has("password")) { + data.webPassword = getString("password") + remove("password") + } + } + + if (data.symbol == null && data.webRealmData != null) { + data.symbol = data.webRealmData?.symbol + } + } + + private fun loginWithCredentials(): Boolean { + val realm = data.webRealmData?.toRealm() ?: return false + + val certificate = web.readCertificate()?.let { web.parseCertificate(it) } + if (certificate != null && Date.fromIso(certificate.expiryDate) > System.currentTimeMillis()) { + useCertificate(certificate) + return true + } + + val fsLogin = FSLogin(data.app.http, debug = App.devMode) + fsLogin.performLogin( + realm = realm, + username = data.webUsername ?: data.webEmail ?: return false, + password = data.webPassword ?: return false, + onSuccess = { fsCertificate -> + web.saveCertificate(fsCertificate.wresult) + useCertificate(web.parseCertificate(fsCertificate.wresult)) + }, + onFailure = { errorText -> + // TODO + data.error(ApiError(TAG, 0).withThrowable(RuntimeException(errorText))) + } + ) + + return true + } + + private fun useCertificate(certificate: CufsCertificate) { + // auto-post certificate when not first login + if (data.profile != null && data.symbol != null && data.symbol != "default") { + val result = web.postCertificate(certificate, data.symbol ?: "default") { _, state -> + when (state) { + VulcanWebMain.STATE_SUCCESS -> { + web.getStartPage { _, _ -> onSuccess() } + } + VulcanWebMain.STATE_NO_REGISTER -> data.error(ApiError(TAG, ERROR_VULCAN_WEB_NO_REGISTER)) + VulcanWebMain.STATE_LOGGED_OUT -> data.error(ApiError(TAG, ERROR_VULCAN_WEB_LOGGED_OUT)) + } + } + // postCertificate returns false if the cert is not valid anymore + if (!result) { + data.error(ApiError(TAG, ERROR_VULCAN_WEB_CERTIFICATE_EXPIRED) + .withApiResponse(certificate.xml)) + } + } + else { + // first login - succeed immediately + onSuccess() + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/AnnouncementGetEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/AnnouncementGetEvent.kt new file mode 100644 index 00000000..237c1c33 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/AnnouncementGetEvent.kt @@ -0,0 +1,9 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-26 + */ + +package pl.szczodrzynski.edziennik.data.api.events + +import pl.szczodrzynski.edziennik.data.db.full.AnnouncementFull + +data class AnnouncementGetEvent(val announcement: AnnouncementFull) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ApiTaskAllFinishedEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ApiTaskAllFinishedEvent.kt new file mode 100644 index 00000000..a5d026cb --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ApiTaskAllFinishedEvent.kt @@ -0,0 +1,7 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-28. + */ + +package pl.szczodrzynski.edziennik.data.api.events + +class ApiTaskAllFinishedEvent diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ApiTaskErrorEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ApiTaskErrorEvent.kt new file mode 100644 index 00000000..11c1813f --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ApiTaskErrorEvent.kt @@ -0,0 +1,9 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-28. + */ + +package pl.szczodrzynski.edziennik.data.api.events + +import pl.szczodrzynski.edziennik.data.api.models.ApiError + +class ApiTaskErrorEvent(val error: ApiError) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ApiTaskFinishedEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ApiTaskFinishedEvent.kt new file mode 100644 index 00000000..7dba791d --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ApiTaskFinishedEvent.kt @@ -0,0 +1,7 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-28. + */ + +package pl.szczodrzynski.edziennik.data.api.events + +class ApiTaskFinishedEvent(val profileId: Int) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ApiTaskProgressEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ApiTaskProgressEvent.kt new file mode 100644 index 00000000..cc7463dc --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ApiTaskProgressEvent.kt @@ -0,0 +1,7 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-28. + */ + +package pl.szczodrzynski.edziennik.data.api.events + +class ApiTaskProgressEvent(val profileId: Int, val progress: Float, val progressText: String?) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ApiTaskStartedEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ApiTaskStartedEvent.kt new file mode 100644 index 00000000..b0f5bd67 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ApiTaskStartedEvent.kt @@ -0,0 +1,9 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-28. + */ + +package pl.szczodrzynski.edziennik.data.api.events + +import pl.szczodrzynski.edziennik.data.db.entity.Profile + +class ApiTaskStartedEvent(val profileId: Int, val profile: Profile? = null) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/AttachmentGetEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/AttachmentGetEvent.kt new file mode 100644 index 00000000..52415c56 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/AttachmentGetEvent.kt @@ -0,0 +1,24 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-11-24 + */ + +package pl.szczodrzynski.edziennik.data.api.events + +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.Message + +data class AttachmentGetEvent(val profileId: Int, val owner: Any, val attachmentId: Long, + var eventType: Int = TYPE_PROGRESS, val fileName: String? = null, + val bytesWritten: Long = 0) { + companion object { + const val TYPE_PROGRESS = 0 + const val TYPE_FINISHED = 1 + } + + val ownerId + get() = when (owner) { + is Message -> owner.id + is Event -> owner.id + else -> -1 + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/EventGetEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/EventGetEvent.kt new file mode 100644 index 00000000..00cf1727 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/EventGetEvent.kt @@ -0,0 +1,9 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-3-31. + */ + +package pl.szczodrzynski.edziennik.data.api.events + +import pl.szczodrzynski.edziennik.data.db.full.EventFull + +data class EventGetEvent(val event: EventFull) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/FeedbackMessageEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/FeedbackMessageEvent.kt new file mode 100644 index 00000000..aeb3ac0c --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/FeedbackMessageEvent.kt @@ -0,0 +1,9 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-1-21. + */ + +package pl.szczodrzynski.edziennik.data.api.events + +import pl.szczodrzynski.edziennik.data.db.entity.FeedbackMessage + +data class FeedbackMessageEvent(val message: FeedbackMessage) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/FirstLoginFinishedEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/FirstLoginFinishedEvent.kt new file mode 100644 index 00000000..114c2d3a --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/FirstLoginFinishedEvent.kt @@ -0,0 +1,6 @@ +package pl.szczodrzynski.edziennik.data.api.events + +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore +import pl.szczodrzynski.edziennik.data.db.entity.Profile + +data class FirstLoginFinishedEvent(val profileList: List, val loginStore: LoginStore) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/MessageGetEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/MessageGetEvent.kt new file mode 100644 index 00000000..182a356f --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/MessageGetEvent.kt @@ -0,0 +1,9 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-11-12. + */ + +package pl.szczodrzynski.edziennik.data.api.events + +import pl.szczodrzynski.edziennik.data.db.full.MessageFull + +data class MessageGetEvent(val message: MessageFull) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/MessageSentEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/MessageSentEvent.kt new file mode 100644 index 00000000..6da0ae9b --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/MessageSentEvent.kt @@ -0,0 +1,9 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-12-27. + */ + +package pl.szczodrzynski.edziennik.data.api.events + +import pl.szczodrzynski.edziennik.data.db.entity.Message + +data class MessageSentEvent(val profileId: Int, val message: Message?, val sentDate: Long?) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ProfileListEmptyEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ProfileListEmptyEvent.kt new file mode 100644 index 00000000..aef467b0 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/ProfileListEmptyEvent.kt @@ -0,0 +1,7 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-1-18. + */ + +package pl.szczodrzynski.edziennik.data.api.events + +class ProfileListEmptyEvent \ No newline at end of file diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/RecipientListGetEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/RecipientListGetEvent.kt new file mode 100644 index 00000000..1d3bd49c --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/RecipientListGetEvent.kt @@ -0,0 +1,9 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-12-22. + */ + +package pl.szczodrzynski.edziennik.data.api.events + +import pl.szczodrzynski.edziennik.data.db.entity.Teacher + +data class RecipientListGetEvent(val profileId: Int, val teacherList: List) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/RegisterAvailabilityEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/RegisterAvailabilityEvent.kt new file mode 100644 index 00000000..2a3531df --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/RegisterAvailabilityEvent.kt @@ -0,0 +1,7 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-9-3. + */ + +package pl.szczodrzynski.edziennik.data.api.events + +class RegisterAvailabilityEvent() diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/UserActionRequiredEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/UserActionRequiredEvent.kt new file mode 100644 index 00000000..d88fa652 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/UserActionRequiredEvent.kt @@ -0,0 +1,16 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-2-15. + */ + +package pl.szczodrzynski.edziennik.data.api.events + +data class UserActionRequiredEvent(val profileId: Int, val type: Int) { + companion object { + const val LOGIN_DATA_MOBIDZIENNIK = 101 + const val LOGIN_DATA_LIBRUS = 102 + const val LOGIN_DATA_IDZIENNIK = 103 + const val LOGIN_DATA_VULCAN = 104 + const val LOGIN_DATA_EDUDZIENNIK = 105 + const val CAPTCHA_LIBRUS = 202 + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/requests/ServiceCloseRequest.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/requests/ServiceCloseRequest.kt new file mode 100644 index 00000000..a4a696a4 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/requests/ServiceCloseRequest.kt @@ -0,0 +1,7 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-1. + */ + +package pl.szczodrzynski.edziennik.data.api.events.requests + +class ServiceCloseRequest diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/requests/TaskCancelRequest.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/requests/TaskCancelRequest.kt new file mode 100644 index 00000000..2985daac --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/requests/TaskCancelRequest.kt @@ -0,0 +1,7 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-1. + */ + +package pl.szczodrzynski.edziennik.data.api.events.requests + +class TaskCancelRequest(val taskId: Int) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/AttachmentGetCallback.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/AttachmentGetCallback.java deleted file mode 100644 index 0bd76455..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/AttachmentGetCallback.java +++ /dev/null @@ -1,11 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api.interfaces; - -import im.wangchao.mhttp.Request; - -/** - * Callback containing a {@link Request.Builder} which has correct headers and body to download a corresponding message attachment when ran. - * {@code onSuccess} has to be ran on the UI thread. - */ -public interface AttachmentGetCallback { - void onSuccess(Request.Builder builder); -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/EdziennikCallback.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/EdziennikCallback.kt new file mode 100644 index 00000000..c1c878b4 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/EdziennikCallback.kt @@ -0,0 +1,17 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-29. + */ + +package pl.szczodrzynski.edziennik.data.api.interfaces + +import pl.szczodrzynski.edziennik.data.api.models.Feature +import pl.szczodrzynski.edziennik.data.api.models.LoginMethod + +/** + * A callback passed only to an e-register class. + * All [Feature]s and [LoginMethod]s receive this callback, + * but may only use [EndpointCallback]'s methods. + */ +interface EdziennikCallback : EndpointCallback { + fun onCompleted() +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/EdziennikInterface.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/EdziennikInterface.java deleted file mode 100644 index 962b1bef..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/EdziennikInterface.java +++ /dev/null @@ -1,92 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api.interfaces; - -import android.content.Context; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import java.util.Map; - -import pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore; -import pl.szczodrzynski.edziennik.data.db.modules.messages.MessageFull; -import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile; -import pl.szczodrzynski.edziennik.data.db.modules.profiles.ProfileFull; -import pl.szczodrzynski.edziennik.data.db.modules.teachers.Teacher; -import pl.szczodrzynski.edziennik.ui.modules.messages.MessagesComposeInfo; -import pl.szczodrzynski.edziennik.utils.models.Endpoint; - -public interface EdziennikInterface { - - /** - * Sync all Edziennik data. - * Ran always on worker thread. - * - * @param activityContext a {@link Context}, used for resource extractions, passed back to {@link SyncCallback} - * @param callback ran on worker thread. - * @param profileId - * @param profile - * @param loginStore - */ - void sync(@NonNull Context activityContext, @NonNull SyncCallback callback, int profileId, @Nullable Profile profile, @NonNull LoginStore loginStore); - void syncMessages(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile); - void syncFeature(@NonNull Context activityContext, @NonNull SyncCallback callback, @NonNull ProfileFull profile, int ... featureList); - - int FEATURE_ALL = 0; - int FEATURE_TIMETABLE = 1; - int FEATURE_AGENDA = 2; - int FEATURE_GRADES = 3; - int FEATURE_HOMEWORK = 4; - int FEATURE_NOTICES = 5; - int FEATURE_ATTENDANCE = 6; - int FEATURE_MESSAGES_INBOX = 7; - int FEATURE_MESSAGES_OUTBOX = 8; - int FEATURE_ANNOUNCEMENTS = 9; - - /** - * Download a single message or get its recipient list if it's already downloaded. - * - * May be executed on any thread. - * - * @param activityContext - * @param errorCallback used for error reporting. Ran on a background thread. - * @param profile - * @param message a message of which body and recipient list should be downloaded. - * @param messageCallback always executed on UI thread. - */ - void getMessage(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile, @NonNull MessageFull message, @NonNull MessageGetCallback messageCallback); - void getAttachment(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile, @NonNull MessageFull message, long attachmentId, @NonNull AttachmentGetCallback attachmentCallback); - //void getMessageList(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile, int type, @NonNull MessageListCallback messageCallback); - /** - * Download a list of available message recipients. - * - * Updates a database-saved {@code teacherList} with {@code loginId}s. - * - * A {@link Teacher} is considered as a recipient when its {@code loginId} is not null. - * - * May be executed on any thread. - * - * @param activityContext - * @param errorCallback used for error reporting. Ran on a background thread. - * @param profile - * @param recipientListGetCallback always executed on UI thread. - */ - void getRecipientList(@NonNull Context activityContext, @NonNull SyncCallback errorCallback, @NonNull ProfileFull profile, @NonNull RecipientListGetCallback recipientListGetCallback); - MessagesComposeInfo getComposeInfo(@NonNull ProfileFull profile); - - - /** - * - * @param profile a {@link Profile} containing already changed endpoints - * @return a map of configurable {@link Endpoint}s along with their names, {@code null} when unsupported - */ - Map getConfigurableEndpoints(Profile profile); - - /** - * Check if the specified endpoint is enabled for the current profile. - * - * @param profile a {@link Profile} containing already changed endpoints - * @param defaultActive if the endpoint is enabled by default. - * @param name the endpoint's name - * @return {@code true} if the endpoint is enabled, {@code false} when it's not. Return {@code defaultActive} if unsupported. - */ - boolean isEndpointEnabled(Profile profile, boolean defaultActive, String name); -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/EdziennikInterface.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/EdziennikInterface.kt new file mode 100644 index 00000000..153bbe18 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/EdziennikInterface.kt @@ -0,0 +1,24 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-29. + */ + +package pl.szczodrzynski.edziennik.data.api.interfaces + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.data.db.full.AnnouncementFull +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.data.db.full.MessageFull + +interface EdziennikInterface { + fun sync(featureIds: List, viewId: Int? = null, onlyEndpoints: List? = null, arguments: JsonObject? = null) + fun getMessage(message: MessageFull) + fun sendMessage(recipients: List, subject: String, text: String) + fun markAllAnnouncementsAsRead() + fun getAnnouncement(announcement: AnnouncementFull) + fun getAttachment(owner: Any, attachmentId: Long, attachmentName: String) + fun getRecipientList() + fun getEvent(eventFull: EventFull) + fun firstLogin() + fun cancel() +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/EndpointCallback.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/EndpointCallback.kt new file mode 100644 index 00000000..b44820c5 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/EndpointCallback.kt @@ -0,0 +1,18 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-29. + */ + +package pl.szczodrzynski.edziennik.data.api.interfaces + +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.api.models.Feature +import pl.szczodrzynski.edziennik.data.api.models.LoginMethod + +/** + * A callback passed to all [Feature]s and [LoginMethod]s + */ +interface EndpointCallback { + fun onError(apiError: ApiError) + fun onProgress(step: Float) + fun onStartProgress(stringRes: Int) +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/ErrorCallback.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/ErrorCallback.java deleted file mode 100644 index cc8f2375..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/ErrorCallback.java +++ /dev/null @@ -1,11 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api.interfaces; - -import android.content.Context; - -import androidx.annotation.NonNull; - -import pl.szczodrzynski.edziennik.data.api.AppError; - -public interface ErrorCallback { - void onError(Context activityContext, @NonNull AppError error); -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/LoginCallback.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/LoginCallback.java deleted file mode 100644 index cae0c65e..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/LoginCallback.java +++ /dev/null @@ -1,5 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api.interfaces; - -public interface LoginCallback { - void onSuccess(); -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/MessageGetCallback.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/MessageGetCallback.java deleted file mode 100644 index 7fd973c8..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/MessageGetCallback.java +++ /dev/null @@ -1,11 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api.interfaces; - -import pl.szczodrzynski.edziennik.data.db.modules.messages.MessageFull; - -/** - * Callback containing a {@link MessageFull} which already has its {@code body} and {@code recipients}. - * {@code onSuccess} is always ran on the UI thread. - */ -public interface MessageGetCallback { - void onSuccess(MessageFull message); -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/MessageListCallback.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/MessageListCallback.java deleted file mode 100644 index 71561ffd..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/MessageListCallback.java +++ /dev/null @@ -1,9 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api.interfaces; - -import java.util.List; - -import pl.szczodrzynski.edziennik.data.db.modules.messages.MessageFull; - -public interface MessageListCallback { - void onSuccess(List messageList); -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/ProgressCallback.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/ProgressCallback.java deleted file mode 100644 index 32948eb9..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/ProgressCallback.java +++ /dev/null @@ -1,8 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api.interfaces; - -import androidx.annotation.StringRes; - -public interface ProgressCallback extends ErrorCallback { - void onProgress(int progressStep); - void onActionStarted(@StringRes int stringResId); -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/RecipientListGetCallback.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/RecipientListGetCallback.java deleted file mode 100644 index fc249432..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/RecipientListGetCallback.java +++ /dev/null @@ -1,9 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api.interfaces; - -import java.util.List; - -import pl.szczodrzynski.edziennik.data.db.modules.teachers.Teacher; - -public interface RecipientListGetCallback { - void onSuccess(List teacherList); -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/SyncCallback.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/SyncCallback.java deleted file mode 100644 index dfaf243b..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/interfaces/SyncCallback.java +++ /dev/null @@ -1,19 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api.interfaces; - -import android.content.Context; - -import java.util.List; - -import pl.szczodrzynski.edziennik.data.db.modules.login.LoginStore; -import pl.szczodrzynski.edziennik.data.db.modules.profiles.Profile; -import pl.szczodrzynski.edziennik.data.db.modules.profiles.ProfileFull; - -/** - * A callback used for error reporting, progress information. - * All the methods are always ran on a worker thread. - */ -public interface SyncCallback extends ProgressCallback { - void onLoginFirst(List profileList, LoginStore loginStore); - void onSuccess(Context activityContext, ProfileFull profileFull); - -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/models/ApiError.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/models/ApiError.kt new file mode 100644 index 00000000..bb5d20cc --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/models/ApiError.kt @@ -0,0 +1,113 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-28. + */ + +package pl.szczodrzynski.edziennik.data.api.models + +import android.content.Context +import com.google.gson.JsonObject +import im.wangchao.mhttp.Request +import im.wangchao.mhttp.Response +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.api.ERROR_API_EXCEPTION +import pl.szczodrzynski.edziennik.data.api.ERROR_EXCEPTION +import pl.szczodrzynski.edziennik.data.api.szkolny.SzkolnyApiException +import pl.szczodrzynski.edziennik.data.api.szkolny.request.ErrorReportRequest +import pl.szczodrzynski.edziennik.ext.stackTraceString +import pl.szczodrzynski.edziennik.ext.toErrorCode + +class ApiError(val tag: String, var errorCode: Int) { + companion object { + fun fromThrowable(tag: String, throwable: Throwable) = + ApiError(tag, throwable.toErrorCode() ?: ERROR_EXCEPTION) + .withThrowable(throwable) + } + + val id = System.currentTimeMillis() + var profileId: Int? = null + var throwable: Throwable? = null + var apiResponse: String? = null + var request: Request? = null + var response: Response? = null + var isCritical = true + + fun withThrowable(throwable: Throwable?): ApiError { + this.throwable = throwable + return this + } + fun withApiResponse(apiResponse: String?): ApiError { + this.apiResponse = apiResponse + return this + } + fun withApiResponse(apiResponse: JsonObject?): ApiError { + this.apiResponse = apiResponse?.toString() + return this + } + fun withRequest(request: Request?): ApiError { + this.request = request + return this + } + fun withResponse(response: Response?): ApiError { + this.response = response + this.request = response?.request() + return this + } + + fun setCritical(isCritical: Boolean): ApiError { + this.isCritical = isCritical + return this + } + + fun getStringText(context: Context): String { + return context.resources.getIdentifier("error_${errorCode}", "string", context.packageName).let { + if (it != 0) + context.getString(it) + else + "?" + } + } + + fun getStringReason(context: Context): String { + if (errorCode == ERROR_API_EXCEPTION && throwable is SzkolnyApiException) + return throwable?.message.toString() + return context.resources.getIdentifier("error_${errorCode}_reason", "string", context.packageName).let { + if (it != 0) + context.getString(it) + else + context.getString(R.string.error_unknown_format, errorCode, tag) + } + } + + override fun toString(): String { + return "ApiError(tag='$tag', errorCode=$errorCode, profileId=$profileId, throwable=$throwable, apiResponse=$apiResponse, request=$request, response=$response, isCritical=$isCritical)" + } + + fun toReportableError(context: Context): ErrorReportRequest.Error { + val requestString = request?.let { + it.method() + " " + it.url() + "\n" + it.headers() + "\n\n" + (it.jsonBody()?.toString() ?: "") + (it.textBody() ?: "") + } + val responseString = response?.let { + if (it.parserErrorBody == null) { + try { + it.parserErrorBody = it.raw().body()?.string() + } catch (e: Exception) { + it.parserErrorBody = e.stackTraceString + } + } + "HTTP "+it.code()+" "+it.message()+"\n" + it.headers() + "\n\n" + it.parserErrorBody + } + return ErrorReportRequest.Error( + id = id, + tag = tag, + errorCode = errorCode, + errorText = getStringText(context), + errorReason = getStringReason(context), + stackTrace = throwable?.stackTraceString, + request = requestString, + response = responseString, + apiResponse = apiResponse ?: response?.parserErrorBody, + isCritical = isCritical + ) + } + +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/models/Data.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/models/Data.kt new file mode 100644 index 00000000..94e12fe8 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/models/Data.kt @@ -0,0 +1,499 @@ +package pl.szczodrzynski.edziennik.data.api.models + +import android.util.LongSparseArray +import android.util.SparseArray +import androidx.core.util.set +import androidx.core.util.size +import androidx.room.OnConflictStrategy +import com.google.gson.JsonObject +import im.wangchao.mhttp.Response +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.BuildConfig +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.api.ERROR_REQUEST_FAILURE +import pl.szczodrzynski.edziennik.data.api.interfaces.EndpointCallback +import pl.szczodrzynski.edziennik.data.db.AppDb +import pl.szczodrzynski.edziennik.data.db.entity.* +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.Utils +import pl.szczodrzynski.edziennik.utils.models.Date + +abstract class Data(val app: App, val profile: Profile?, val loginStore: LoginStore) { + companion object { + private const val TAG = "Data" + private val DEBUG = true && BuildConfig.DEBUG + } + + var fakeLogin = false + + var cancelled = false + + val profileId + get() = profile?.id ?: -1 + + var arguments: JsonObject? = null + + /** + * A callback passed to all [Feature]s and [LoginMethod]s + */ + lateinit var callback: EndpointCallback + + /** + * A list of [LoginMethod]s *already fulfilled* during this sync. + * + * A [LoginMethod] may add elements to this list only after a successful login + * with that method. + */ + val loginMethods = mutableListOf() + + /** + * A method which may be overridden in child Data* classes. + * + * Calling it should populate [loginMethods] with all + * already available login methods (e.g. a non-expired OAuth token). + */ + open fun satisfyLoginMethods() {} + + /** + * A list of Login method IDs that are still pending + * to run. + */ + var targetLoginMethodIds = mutableListOf() + /** + * A map of endpoint ID to last sync time, that are still pending + * to run. + */ + var targetEndpointIds = sortedMapOf() + /** + * A count of all network requests to do. + */ + var progressCount: Int = 0 + /** + * A number by which the progress will be incremented, every time + * a login method/endpoint finishes its job. + */ + var progressStep: Float = 0f + + /** + * A map of endpoint IDs to JSON objects, specifying their arguments bundle. + */ + var endpointArgs = mutableMapOf() + + var endpointTimers = mutableListOf() + + val notifications = mutableListOf() + + val teacherList = LongSparseArray() + val subjectList = LongSparseArray() + val teamList = LongSparseArray() + val lessonRanges = SparseArray() + val gradeCategories = LongSparseArray() + + var teacherOnConflictStrategy = OnConflictStrategy.IGNORE + var eventListReplace = false + var messageListReplace = false + var announcementListReplace = false + + val classrooms = LongSparseArray() + val attendanceTypes = LongSparseArray() + val noticeTypes = LongSparseArray() + val eventTypes = LongSparseArray() + val teacherAbsenceTypes = LongSparseArray() + val librusLessons = LongSparseArray() + + private var mTeamClass: Team? = null + var teamClass: Team? + get() { + if (mTeamClass == null) + mTeamClass = teamList.singleOrNull { it.type == Team.TYPE_CLASS } + return mTeamClass + } + set(value) { + mTeamClass = value + } + + var toRemove = mutableListOf() + + val lessonList = mutableListOf() + + val gradeList = mutableListOf() + + val eventList = mutableListOf() + + val noticeList = mutableListOf() + + val attendanceList = mutableListOf() + + val announcementList = mutableListOf() + + val luckyNumberList = mutableListOf() + + val teacherAbsenceList = mutableListOf() + + val messageList = mutableListOf() + val messageRecipientList = mutableListOf() + val messageRecipientIgnoreList = mutableListOf() + + val metadataList = mutableListOf() + val setSeenMetadataList = mutableListOf() + + val db: AppDb by lazy { app.db } + + init { + if (App.debugMode) { + fakeLogin = loginStore.hasLoginData("fakeLogin") + } + clear() + if (profile != null) { + endpointTimers = db.endpointTimerDao().getAllNow(profile.id).toMutableList() + db.teacherDao().getAllNow(profileId).toSparseArray(teacherList) { it.id } + db.subjectDao().getAllNow(profileId).toSparseArray(subjectList) { it.id } + db.teamDao().getAllNow(profileId).toSparseArray(teamList) { it.id } + db.lessonRangeDao().getAllNow(profileId).toSparseArray(lessonRanges) { it.lessonNumber } + db.gradeCategoryDao().getAllNow(profileId).toSparseArray(gradeCategories) { it.categoryId } + } + } + + private fun d(message: String) { + if (DEBUG) + Utils.d(TAG, message) + } + + fun clear() { + loginMethods.clear() + + toRemove.clear() + endpointTimers.clear() + teacherList.clear() + subjectList.clear() + teamList.clear() + lessonRanges.clear() + gradeCategories.clear() + + classrooms.clear() + attendanceTypes.clear() + noticeTypes.clear() + eventTypes.clear() + teacherAbsenceTypes.clear() + librusLessons.clear() + + lessonList.clear() + gradeList.clear() + noticeList.clear() + attendanceList.clear() + announcementList.clear() + luckyNumberList.clear() + teacherAbsenceList.clear() + messageList.clear() + messageRecipientList.clear() + messageRecipientIgnoreList.clear() + metadataList.clear() + setSeenMetadataList.clear() + } + + open fun saveData() { + if (profile == null) + return // return on first login + val totalStart = System.currentTimeMillis() + var startTime = System.currentTimeMillis() + d("Saving data to DB") + + profile.userCode = generateUserCode() + + // update profile subname with class name, school year and account type + profile.subname = joinNotNullStrings( + " - ", + profile.studentClassName, + "${profile.studentSchoolYearStart}/${profile.studentSchoolYearStart + 1}" + ) + " " + app.getString(if (profile.isParent) R.string.account_type_parent else R.string.account_type_child) + + db.profileDao().add(profile) + db.loginStoreDao().add(loginStore) + + if (profile.id == app.profile.id) { + app.profile.apply { + name = profile.name + subname = profile.subname + syncEnabled = profile.syncEnabled + empty = profile.empty + archived = profile.archived + studentNameLong = profile.studentNameLong + studentNameShort = profile.studentNameShort + studentNumber = profile.studentNumber + accountName = profile.accountName + dateSemester1Start = profile.dateSemester1Start + dateSemester2Start = profile.dateSemester2Start + dateYearEnd = profile.dateYearEnd + lastReceiversSync = profile.lastReceiversSync + } + } + + d("Profiles saved in ${System.currentTimeMillis()-startTime} ms") + startTime = System.currentTimeMillis() + + // always present and not empty, during every sync + db.endpointTimerDao().addAll(endpointTimers) + if (teacherOnConflictStrategy == OnConflictStrategy.IGNORE) + db.teacherDao().addAllIgnore(teacherList.values()) + else if (teacherOnConflictStrategy == OnConflictStrategy.REPLACE) + db.teacherDao().addAll(teacherList.values()) + db.subjectDao().addAll(subjectList.values()) + db.teamDao().clear(profileId) + db.teamDao().addAll(teamList.values()) + db.lessonRangeDao().clear(profileId) + db.lessonRangeDao().addAll(lessonRanges.values()) + db.gradeCategoryDao().clear(profileId) + db.gradeCategoryDao().addAll(gradeCategories.values()) + + d("Maps saved in ${System.currentTimeMillis()-startTime} ms") + startTime = System.currentTimeMillis() + + // may be empty - extracted from DB on demand, by an endpoint + if (classrooms.size > 0) + db.classroomDao().addAll(classrooms.values()) + if (attendanceTypes.size > 0) + db.attendanceTypeDao().addAll(attendanceTypes.values()) + if (noticeTypes.size > 0) + db.noticeTypeDao().addAll(noticeTypes.values()) + if (eventTypes.size > 0) + db.eventTypeDao().addAll(eventTypes.values()) + if (teacherAbsenceTypes.size > 0) + db.teacherAbsenceTypeDao().addAll(teacherAbsenceTypes.values()) + if (librusLessons.size > 0) + db.librusLessonDao().addAll(librusLessons.values()) + + d("On-demand maps saved in ${System.currentTimeMillis()-startTime} ms") + startTime = System.currentTimeMillis() + + // clear DB with DataRemoveModels added by endpoints + for (model in toRemove) { + d("Clearing DB with $model") + when (model) { + is DataRemoveModel.Timetable -> model.commit(profileId, db.timetableDao()) + is DataRemoveModel.Grades -> model.commit(profileId, db.gradeDao()) + is DataRemoveModel.Events -> model.commit(profileId, db.eventDao()) + is DataRemoveModel.Attendance -> model.commit(profileId, db.attendanceDao()) + } + } + + d("DB cleared in ${System.currentTimeMillis()-startTime} ms") + startTime = System.currentTimeMillis() + + if (metadataList.isNotEmpty()) + db.metadataDao().addAllIgnore(metadataList) + if (setSeenMetadataList.isNotEmpty()) + db.metadataDao().setSeen(setSeenMetadataList) + + d("Metadata saved in ${System.currentTimeMillis()-startTime} ms") + startTime = System.currentTimeMillis() + + db.timetableDao().putAll(lessonList, removeNotKept = true) + db.gradeDao().putAll(gradeList, removeNotKept = true) + db.eventDao().putAll(eventList, forceReplace = eventListReplace, removeNotKept = true) + if (noticeList.isNotEmpty()) { + db.noticeDao().clear(profile.id) + db.noticeDao().putAll(noticeList) + } + db.attendanceDao().putAll(attendanceList, removeNotKept = true) + db.announcementDao().putAll(announcementList, forceReplace = announcementListReplace, removeNotKept = false) + db.luckyNumberDao().putAll(luckyNumberList) + db.teacherAbsenceDao().putAll(teacherAbsenceList) + + db.messageDao().putAll(messageList, forceReplace = messageListReplace, removeNotKept = false) + if (messageRecipientList.isNotEmpty()) + db.messageRecipientDao().addAll(messageRecipientList) + if (messageRecipientIgnoreList.isNotEmpty()) + db.messageRecipientDao().addAllIgnore(messageRecipientIgnoreList) + + d("Other data saved in ${System.currentTimeMillis()-startTime} ms") + + d("Total save time: ${System.currentTimeMillis()-totalStart} ms") + } + + fun setSyncNext(endpointId: Int, syncIn: Long? = null, viewId: Int? = null, syncAt: Long? = null) { + EndpointTimer(profile?.id + ?: -1, endpointId).apply { + syncedNow() + + if (syncIn != null) { + if (syncIn < 10) + nextSync = syncIn + else + syncIn(syncIn) + } + if (syncAt != null) { + nextSync = syncAt + } + if (viewId != null) + syncWhenView(viewId) + + endpointTimers.add(this) + } + } + + abstract fun generateUserCode(): String + + fun cancel() { + d("Cancelled") + cancelled = true + saveData() + } + + fun shouldSyncLuckyNumber(): Boolean { + return db.luckyNumberDao().getNearestFutureNow(profileId, Date.getToday()) == null + } + + /*fun error(tag: String, errorCode: Int, response: Response? = null, throwable: Throwable? = null, apiResponse: JsonObject? = null) { + val code = when (throwable) { + is UnknownHostException, is SSLException, is InterruptedIOException -> CODE_NO_INTERNET + is SocketTimeoutException -> CODE_TIMEOUT + else -> when (response?.code()) { + 400, 401, 424, 500, 503, 404 -> CODE_MAINTENANCE + else -> errorCode + } + } + error(ApiError(tag, code).apply { + profileId = profile?.id ?: -1 + }.withResponse(response).withThrowable(throwable).withApiResponse(apiResponse)) + }*/ + + fun error(tag: String, errorCode: Int, response: Response? = null, apiResponse: String? = null) { + error(ApiError(tag, errorCode).apply { + profileId = profile?.id ?: -1 + }.withResponse(response).withApiResponse(apiResponse)) + } + + fun error(apiError: ApiError) { + apiError.errorCode = apiError.throwable?.toErrorCode() ?: + if (apiError.errorCode == ERROR_REQUEST_FAILURE) + apiError.response?.toErrorCode() ?: apiError.errorCode + else + apiError.errorCode + + callback.onError(apiError) + } + + fun progress(step: Float) { + callback.onProgress(step) + } + + fun startProgress(stringRes: Int) { + callback.onStartProgress(stringRes) + } + + /* _ _ _ _ _ + | | | | | (_) | + | | | | |_ _| |___ + | | | | __| | / __| + | |__| | |_| | \__ \ + \____/ \__|_|_|__*/ + fun getSubject(id: Long?, name: String, shortName: String = name): Subject { + var subject = subjectList.singleOrNull { it.id == id } + if (subject == null) + subject = subjectList.singleOrNull { it.longName == name } + if (subject == null) + subject = subjectList.singleOrNull { it.shortName == name } + + if (subject == null) { + subject = Subject( + profileId, + id ?: name.crc32(), + name, + shortName + ) + subjectList[subject.id] = subject + } + return subject + } + + fun getTeam( + id: Long?, + name: String, + schoolCode: String, + isTeamClass: Boolean = false, + profileId: Int? = null, + ): Team { + if (isTeamClass && teamClass != null) + return teamClass as Team + var team = teamList.singleOrNull { it.id == id } + + val namePlain = name.replace(" ", "") + if (team == null) + team = teamList.singleOrNull { it.name.replace(" ", "") == namePlain } + + if (team == null) { + team = Team( + profileId ?: this.profileId, + id ?: name.crc32(), + name, + if (isTeamClass) Team.TYPE_CLASS else Team.TYPE_VIRTUAL, + "$schoolCode:$name", + -1 + ) + teamList[team.id] = team + } else if (id != null) { + team.id = id + } + return team + } + + fun getTeacher(firstName: String, lastName: String, loginId: String? = null): Teacher { + val teacher = teacherList.singleOrNull { it.fullName == "$firstName $lastName" } + return validateTeacher(teacher, firstName, lastName, loginId) + } + + fun getTeacher(firstNameChar: Char, lastName: String, loginId: String? = null): Teacher { + val teacher = teacherList.singleOrNull { it.shortName == "$firstNameChar.$lastName" } + return validateTeacher(teacher, firstNameChar.toString(), lastName, loginId) + } + + fun getTeacherByLastFirst(nameLastFirst: String, loginId: String? = null): Teacher { + // comparing full name is safer than splitting and swapping + val teacher = teacherList.singleOrNull { it.fullNameLastFirst == nameLastFirst } + val nameParts = nameLastFirst.split(" ", limit = 2) + return if (nameParts.size == 1) + validateTeacher(teacher, nameParts[0], "", loginId) + else + validateTeacher(teacher, nameParts[1], nameParts[0], loginId) + } + + fun getTeacherByFirstLast(nameFirstLast: String, loginId: String? = null): Teacher { + // comparing full name is safer than splitting and swapping + val teacher = teacherList.singleOrNull { it.fullName == nameFirstLast } + val nameParts = nameFirstLast.split(" ", limit = 2) + return if (nameParts.size == 1) + validateTeacher(teacher, nameParts[0], "", loginId) + else + validateTeacher(teacher, nameParts[0], nameParts[1], loginId) + } + + fun getTeacherByFDotLast(nameFDotLast: String, loginId: String? = null): Teacher { + val nameParts = nameFDotLast.split(".") + return if (nameParts.size == 1) + getTeacher(nameParts[0], "", loginId) + else + getTeacher(nameParts[0][0], nameParts[1], loginId) + } + + fun getTeacherByFDotSpaceLast(nameFDotSpaceLast: String, loginId: String? = null): Teacher { + val nameParts = nameFDotSpaceLast.split(".") + return if (nameParts.size == 1) + getTeacher(nameParts[0], "", loginId) + else + getTeacher(nameParts[0][0], nameParts[1], loginId) + } + + private fun validateTeacher(teacher: Teacher?, firstName: String, lastName: String, loginId: String?): Teacher { + val obj = teacher ?: Teacher(profileId, -1, firstName, lastName, loginId).apply { + id = fullName.crc32() + teacherList[id] = this + } + return obj.also { + if (loginId != null && it.loginId != null) + it.loginId = loginId + if (firstName.length > 1) + it.name = firstName + it.surname = lastName + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/models/DataRemoveModel.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/models/DataRemoveModel.kt new file mode 100644 index 00000000..73096f28 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/models/DataRemoveModel.kt @@ -0,0 +1,79 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-10-2. + */ + +package pl.szczodrzynski.edziennik.data.api.models + +import pl.szczodrzynski.edziennik.data.db.dao.AttendanceDao +import pl.szczodrzynski.edziennik.data.db.dao.EventDao +import pl.szczodrzynski.edziennik.data.db.dao.GradeDao +import pl.szczodrzynski.edziennik.data.db.dao.TimetableDao +import pl.szczodrzynski.edziennik.utils.models.Date + +open class DataRemoveModel { + data class Timetable(private val dateFrom: Date?, private val dateTo: Date?, private val isExtra: Boolean?) : DataRemoveModel() { + companion object { + fun from(dateFrom: Date, isExtra: Boolean? = null) = Timetable(dateFrom, null, isExtra) + fun to(dateTo: Date, isExtra: Boolean? = null) = Timetable(null, dateTo, isExtra) + fun between(dateFrom: Date, dateTo: Date, isExtra: Boolean? = null) = Timetable(dateFrom, dateTo, isExtra) + } + + fun commit(profileId: Int, dao: TimetableDao) { + if (dateFrom != null && dateTo != null) { + dao.dontKeepBetweenDates(profileId, dateFrom, dateTo, isExtra ?: false) + } else { + dateFrom?.let { dateFrom -> dao.dontKeepFromDate(profileId, dateFrom, isExtra ?: false) } + dateTo?.let { dateTo -> dao.dontKeepToDate(profileId, dateTo, isExtra ?: false) } + } + } + } + + data class Grades(private val all: Boolean, private val semester: Int?, private val type: Int?) : DataRemoveModel() { + companion object { + fun all() = Grades(true, null, null) + fun allWithType(type: Int) = Grades(true, null, type) + fun semester(semester: Int) = Grades(false, semester, null) + fun semesterWithType(semester: Int, type: Int) = Grades(false, semester, type) + } + + fun commit(profileId: Int, dao: GradeDao) { + if (all) { + if (type != null) dao.dontKeepWithType(profileId, type) + else dao.clear(profileId) + } + semester?.let { + if (type != null) dao.dontKeepForSemesterWithType(profileId, it, type) + else dao.dontKeepForSemester(profileId, it) + } + } + } + + data class Events(private val type: Long?, private val exceptType: Long?, private val exceptTypes: List?) : DataRemoveModel() { + companion object { + fun futureExceptType(exceptType: Long) = Events(null, exceptType, null) + fun futureExceptTypes(exceptTypes: List) = Events(null, null, exceptTypes) + fun futureWithType(type: Long) = Events(type, null, null) + fun future() = Events(null, null, null) + } + + fun commit(profileId: Int, dao: EventDao) { + type?.let { dao.dontKeepFutureWithType(profileId, Date.getToday(), it) } + exceptType?.let { dao.dontKeepFutureExceptType(profileId, Date.getToday(), it) } + exceptTypes?.let { dao.dontKeepFutureExceptTypes(profileId, Date.getToday(), it) } + if (type == null && exceptType == null && exceptTypes == null) + dao.dontKeepFuture(profileId, Date.getToday()) + } + } + + data class Attendance(private val dateFrom: Date?) : DataRemoveModel() { + companion object { + fun from(dateFrom: Date) = Attendance(dateFrom) + } + + fun commit(profileId: Int, dao: AttendanceDao) { + if (dateFrom != null) { + dao.dontKeepAfterDate(profileId, dateFrom) + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/models/Feature.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/models/Feature.kt new file mode 100644 index 00000000..fd7c7873 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/models/Feature.kt @@ -0,0 +1,33 @@ +package pl.szczodrzynski.edziennik.data.api.models + +/** + * A Endpoint descriptor class. + * + * The API runs appropriate endpoints in order to fulfill its + * feature list. + * An endpoint may have its [LoginMethod] dependencies which will be + * satisfied by the API before the [endpointClass]'s constructor is invoked. + * + * @param loginType type of the e-register this endpoint handles + * @param featureId a feature ID + * @param endpointIds a [List] of [Feature]s that satisfy this feature ID + * @param requiredLoginMethod a required login method, which will have to be executed before this endpoint. + */ +data class Feature( + val loginType: Int, + val featureId: Int, + val endpointIds: List>, + val requiredLoginMethods: List +) { + var priority = endpointIds.size + fun withPriority(priority: Int): Feature { + this.priority = priority + return this + } + + var shouldSync: ((Data) -> Boolean)? = null + fun withShouldSync(shouldSync: ((Data) -> Boolean)?): Feature { + this.shouldSync = shouldSync + return this + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/models/LoginMethod.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/models/LoginMethod.kt new file mode 100644 index 00000000..cf899cff --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/models/LoginMethod.kt @@ -0,0 +1,46 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-9-20. + */ + +package pl.szczodrzynski.edziennik.data.api.models + +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_NOT_NEEDED +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore +import pl.szczodrzynski.edziennik.data.db.entity.Profile + +/** + * A Login Method descriptor class. + * + * This is used by the API to satisfy all [Feature]s' dependencies. + * A login method may have its own dependencies which need to be + * satisfied before the [loginMethodClass]'s constructor is invoked. + * + * @param loginType type of the e-register this login method handles + * @param loginMethodId a unique ID of this login method + * @param loginMethodClass a [Class] which constructor will be invoked when a log in is needed + * @param requiredLoginMethod a required login method (which will be called before this). May differ depending on the [Profile] and/or [LoginStore]. + */ +class LoginMethod( + val loginType: Int, + val loginMethodId: Int, + val loginMethodClass: Class<*>, + private var mIsPossible: ((profile: Profile?, loginStore: LoginStore) -> Boolean)? = null, + private var mRequiredLoginMethod: ((profile: Profile?, loginStore: LoginStore) -> Int)? = null +) { + + fun withIsPossible(isPossible: (profile: Profile?, loginStore: LoginStore) -> Boolean): LoginMethod { + this.mIsPossible = isPossible + return this + } + fun withRequiredLoginMethod(requiredLoginMethod: (profile: Profile?, loginStore: LoginStore) -> Int): LoginMethod { + this.mRequiredLoginMethod = requiredLoginMethod + return this + } + + fun isPossible(profile: Profile?, loginStore: LoginStore): Boolean { + return mIsPossible?.invoke(profile, loginStore) ?: false + } + fun requiredLoginMethod(profile: Profile?, loginStore: LoginStore): Int { + return mRequiredLoginMethod?.invoke(profile, loginStore) ?: LOGIN_METHOD_NOT_NEEDED + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/SzkolnyApi.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/SzkolnyApi.kt new file mode 100644 index 00000000..c86ae235 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/SzkolnyApi.kt @@ -0,0 +1,481 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-8 + */ + +package pl.szczodrzynski.edziennik.data.api.szkolny + +import android.os.Build +import android.widget.Toast +import androidx.appcompat.app.AppCompatActivity +import com.google.gson.GsonBuilder +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.withContext +import okhttp3.OkHttpClient +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.ERROR_API_INVALID_SIGNATURE +import pl.szczodrzynski.edziennik.data.api.szkolny.adapter.DateAdapter +import pl.szczodrzynski.edziennik.data.api.szkolny.adapter.TimeAdapter +import pl.szczodrzynski.edziennik.data.api.szkolny.interceptor.ApiCacheInterceptor +import pl.szczodrzynski.edziennik.data.api.szkolny.interceptor.SignatureInterceptor +import pl.szczodrzynski.edziennik.data.api.szkolny.interceptor.Signing +import pl.szczodrzynski.edziennik.data.api.szkolny.request.* +import pl.szczodrzynski.edziennik.data.api.szkolny.response.* +import pl.szczodrzynski.edziennik.data.db.entity.* +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.ext.keys +import pl.szczodrzynski.edziennik.ext.md5 +import pl.szczodrzynski.edziennik.ext.toApiError +import pl.szczodrzynski.edziennik.ext.toErrorCode +import pl.szczodrzynski.edziennik.ui.error.ErrorDetailsDialog +import pl.szczodrzynski.edziennik.ui.error.ErrorSnackbar +import pl.szczodrzynski.edziennik.ui.login.LoginInfo +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time +import retrofit2.Response +import retrofit2.Retrofit +import retrofit2.converter.gson.GsonConverterFactory +import retrofit2.create +import java.util.concurrent.TimeUnit.SECONDS +import kotlin.coroutines.CoroutineContext + +class SzkolnyApi(val app: App) : CoroutineScope { + companion object { + const val TAG = "SzkolnyApi" + } + + private val api: SzkolnyService + private val retrofit: Retrofit + + private val job = Job() + override val coroutineContext: CoroutineContext + get() = job + Dispatchers.Main + + init { + val okHttpClient: OkHttpClient = app.http.newBuilder() + .followRedirects(true) + .callTimeout(10, SECONDS) + .addInterceptor(ApiCacheInterceptor(app)) + .addInterceptor(SignatureInterceptor(app)) + .build() + + val gsonConverterFactory = GsonConverterFactory.create( + GsonBuilder() + .setLenient() + .registerTypeAdapter(Date::class.java, DateAdapter()) + .registerTypeAdapter(Time::class.java, TimeAdapter()) + .create()) + + retrofit = Retrofit.Builder() + .baseUrl("https://api.szkolny.eu/") + .addConverterFactory(gsonConverterFactory) + .client(okHttpClient) + .build() + + api = retrofit.create() + } + + suspend inline fun runCatching(errorSnackbar: ErrorSnackbar, crossinline block: SzkolnyApi.() -> T?): T? { + return try { + withContext(Dispatchers.Default) { block.invoke(this@SzkolnyApi) } + } + catch (e: Exception) { + errorSnackbar.addError(e.toApiError(TAG)).show() + null + } + } + suspend inline fun runCatching(activity: AppCompatActivity, crossinline block: SzkolnyApi.() -> T?): T? { + return try { + withContext(Dispatchers.Default) { block.invoke(this@SzkolnyApi) } + } + catch (e: Exception) { + withContext(coroutineContext) { + val apiError = e.toApiError(TAG) + if (apiError.errorCode == ERROR_API_INVALID_SIGNATURE) { + Toast.makeText(activity, R.string.error_no_api_access, Toast.LENGTH_SHORT).show() + return@withContext null + } + ErrorDetailsDialog( + activity, + listOf(apiError), + R.string.error_occured + ).show() + null + } + null + } + } + inline fun runCatching(block: SzkolnyApi.() -> T, onError: (e: Throwable) -> Unit): T? { + return try { + block.invoke(this@SzkolnyApi) + } + catch (e: Exception) { + onError(e) + null + } + } + + /** + * Check if a server request returned a successful response. + * + * If not, throw a [SzkolnyApiException] containing an [ApiResponse.Error], + * or null if it's a HTTP call error. + */ + @Throws(Exception::class) + private inline fun parseResponse( + response: Response>, + updateDeviceHash: Boolean = false, + ): T { + app.config.update = response.body()?.update?.let { update -> + if (update.versionCode > BuildConfig.VERSION_CODE) { + if (update.updateMandatory + && EventBus.getDefault().hasSubscriberForEvent(update::class.java)) { + EventBus.getDefault().postSticky(update) + } + update + } + else + null + } + + response.body()?.registerAvailability?.let { registerAvailability -> + app.config.sync.registerAvailability = registerAvailability + } + + if (response.isSuccessful && response.body()?.success == true) { + // update the device's hash on success + if (updateDeviceHash) { + val hash = getDevice()?.toString()?.md5() + if (hash != null) { + app.config.hash = hash + } + } + + if (Unit is T) { + return Unit + } + if (response.body()?.data != null) { + return response.body()?.data!! + } + } + + val body = response.body() ?: response.errorBody()?.let { + try { + retrofit.responseBodyConverter>(ApiResponse::class.java, arrayOf()).convert(it) + } + catch (e: Exception) { + null + } + } + + if (body?.errors?.any { it.toErrorCode() == ERROR_API_INVALID_SIGNATURE } == true) { + app.config.apiInvalidCert = Signing.appCertificate.md5() + } + + throw SzkolnyApiException(body?.errors?.firstOrNull()) + } + + private fun getDevice() = run { + val config = app.config + val device = Device( + osType = "Android", + osVersion = Build.VERSION.RELEASE, + hardware = "${Build.MANUFACTURER} ${Build.MODEL}", + pushToken = app.config.sync.tokenApp, + appVersion = BuildConfig.VERSION_NAME, + appType = BuildConfig.BUILD_TYPE, + appVersionCode = BuildConfig.VERSION_CODE, + syncInterval = app.config.sync.interval + ) + val hash = device.toString().md5() + if (hash == config.hash) + return@run null + return@run device + } + + @Throws(Exception::class) + fun getEvents( + profiles: List, + notifications: List, + blacklistedIds: List, + lastSyncTime: Long, + ): Pair, List> { + val teams = app.db.teamDao().allNow + + val users = profiles.mapNotNull { profile -> + val config = app.config.getFor(profile.id) + val user = ServerSyncRequest.User( + profile.userCode, + profile.studentNameLong, + profile.studentNameShort, + profile.loginStoreType, + teams.filter { it.profileId == profile.id }.map { it.code } + ) + val hash = user.toString().md5() + if (hash == config.hash) + return@mapNotNull null + return@mapNotNull user to config + } + + val response = api.serverSync(ServerSyncRequest( + deviceId = app.deviceId, + device = getDevice(), + userCodes = profiles.map { it.userCode }, + users = users.keys(), + lastSync = lastSyncTime, + notifications = notifications.map { ServerSyncRequest.Notification(it.profileName ?: "", it.type, it.text) } + )).execute() + val (events, notes, hasBrowsers) = parseResponse(response, updateDeviceHash = true) + + hasBrowsers?.let { + app.config.sync.webPushEnabled = it + } + + // update users' hashes on success + users.forEach { (user, config) -> + config.hash = user.toString().md5() + } + + val eventList = mutableListOf() + val noteList = mutableListOf() + + events.forEach { event -> + // skip blacklisted events + if (event.id in blacklistedIds) + return@forEach + + // force nullable non-negative colors + if (event.color == -1) + event.color = null + + val eventSharedBy = event.sharedBy + + // create the event for every matching team and profile + teams.filter { it.code == event.teamCode }.onEach { team -> + val profile = profiles.firstOrNull { it.id == team.profileId } ?: return@onEach + if (!profile.canShare) + return@forEach + + eventList += EventFull(event).apply { + profileId = team.profileId + teamId = team.id + addedManually = true + seen = profile.empty + notified = profile.empty + + if (profile.userCode == event.sharedBy) { + sharedBy = "self" + addedManually = true + } else { + sharedBy = eventSharedBy + } + } + } + } + + notes.forEach { note -> + val noteSharedBy = note.sharedBy + + // create the note for every matching team and profile + teams.filter { it.code == note.teamCode }.onEach { team -> + val profile = profiles.firstOrNull { it.id == team.profileId } ?: return@onEach + if (!profile.canShare) + return@forEach + note.profileId = team.profileId + if (profile.userCode == note.sharedBy) { + note.sharedBy = "self" + } else { + note.sharedBy = noteSharedBy + } + + if (app.noteManager.hasValidOwner(note)) + noteList += note + } + } + return eventList to noteList + } + + @Throws(Exception::class) + fun shareEvent(event: EventFull) { + val profile = app.db.profileDao().getByIdNow(event.profileId) + ?: throw NullPointerException("Profile is not found") + val team = app.db.teamDao().getByIdNow(event.profileId, event.teamId) + ?: throw NullPointerException("Team is not found") + + val response = api.shareEvent(EventShareRequest( + deviceId = app.deviceId, + device = getDevice(), + userCode = profile.userCode, + studentNameLong = profile.studentNameLong, + shareTeamCode = team.code, + event = event + )).execute() + parseResponse(response, updateDeviceHash = true) + } + + @Throws(Exception::class) + fun unshareEvent(event: Event) { + val profile = app.db.profileDao().getByIdNow(event.profileId) + ?: throw NullPointerException("Profile is not found") + val team = app.db.teamDao().getByIdNow(event.profileId, event.teamId) + ?: throw NullPointerException("Team is not found") + + val response = api.shareEvent(EventShareRequest( + deviceId = app.deviceId, + device = getDevice(), + userCode = profile.userCode, + studentNameLong = profile.studentNameLong, + unshareTeamCode = team.code, + eventId = event.id + )).execute() + parseResponse(response, updateDeviceHash = true) + } + + @Throws(Exception::class) + fun shareNote(note: Note) { + val profile = app.db.profileDao().getByIdNow(note.profileId) + ?: throw NullPointerException("Profile is not found") + val team = app.db.teamDao().getClassNow(note.profileId) + ?: throw NullPointerException("TeamClass is not found") + + val response = api.shareNote(NoteShareRequest( + deviceId = app.deviceId, + device = getDevice(), + userCode = profile.userCode, + studentNameLong = profile.studentNameLong, + shareTeamCode = team.code, + note = note, + )).execute() + parseResponse(response) + } + + @Throws(Exception::class) + fun unshareNote(note: Note) { + val profile = app.db.profileDao().getByIdNow(note.profileId) + ?: throw NullPointerException("Profile is not found") + val team = app.db.teamDao().getClassNow(note.profileId) + ?: throw NullPointerException("TeamClass is not found") + + val response = api.shareNote(NoteShareRequest( + deviceId = app.deviceId, + device = getDevice(), + userCode = profile.userCode, + studentNameLong = profile.studentNameLong, + unshareTeamCode = team.code, + noteId = note.id, + )).execute() + parseResponse(response) + } + + /*fun eventEditRequest(requesterName: String, event: Event): ApiResponse? { + + }*/ + + @Throws(Exception::class) + fun pairBrowser(browserId: String?, pairToken: String?): List { + val response = api.webPush(WebPushRequest( + deviceId = app.deviceId, + device = getDevice(), + action = "pairBrowser", + browserId = browserId, + pairToken = pairToken + )).execute() + + return parseResponse(response, updateDeviceHash = true).browsers + } + + @Throws(Exception::class) + fun listBrowsers(): List { + val response = api.webPush(WebPushRequest( + deviceId = app.deviceId, + device = getDevice(), + action = "listBrowsers" + )).execute() + + return parseResponse(response, updateDeviceHash = true).browsers + } + + @Throws(Exception::class) + fun unpairBrowser(browserId: String): List { + val response = api.webPush(WebPushRequest( + deviceId = app.deviceId, + device = getDevice(), + action = "unpairBrowser", + browserId = browserId + )).execute() + + return parseResponse(response, updateDeviceHash = true).browsers + } + + @Throws(Exception::class) + fun errorReport(errors: List) { + val response = api.errorReport(ErrorReportRequest( + deviceId = app.deviceId, + device = getDevice(), + appVersion = BuildConfig.VERSION_NAME, + errors = errors + )).execute() + parseResponse(response, updateDeviceHash = true) + } + + @Throws(Exception::class) + fun unregisterAppUser(userCode: String) { + val response = api.appUser(AppUserRequest( + deviceId = app.deviceId, + device = getDevice(), + userCode = userCode + )).execute() + parseResponse(response, updateDeviceHash = true) + } + + @Throws(Exception::class) + fun getUpdate(channel: String): List { + val response = api.updates(channel).execute() + return parseResponse(response) + } + + @Throws(Exception::class) + fun sendFeedbackMessage(senderName: String?, targetDeviceId: String?, text: String): FeedbackMessage { + val response = api.feedbackMessage(FeedbackMessageRequest( + deviceId = app.deviceId, + device = getDevice(), + senderName = senderName, + targetDeviceId = targetDeviceId, + text = text + )).execute() + + return parseResponse(response, updateDeviceHash = true).message + } + + @Throws(Exception::class) + fun getRealms(registerName: String): List { + val response = api.fsLoginRealms(registerName).execute() + if (response.isSuccessful && response.body() != null) { + return response.body()!! + } + throw SzkolnyApiException(null) + } + + @Throws(Exception::class) + fun getContributors(): ContributorsResponse { + val response = api.contributors().execute() + if (response.isSuccessful && response.body() != null) { + return parseResponse(response) + } + throw SzkolnyApiException(null) + } + + @Throws(Exception::class) + fun getFirebaseToken(registerName: String): String { + val response = api.firebaseToken(registerName).execute() + return parseResponse(response) + } + + @Throws(Exception::class) + fun getRegisterAvailability(): Map { + val response = api.registerAvailability().execute() + return parseResponse(response) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/SzkolnyApiException.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/SzkolnyApiException.kt new file mode 100644 index 00000000..7e15873d --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/SzkolnyApiException.kt @@ -0,0 +1,9 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-2-16. + */ + +package pl.szczodrzynski.edziennik.data.api.szkolny + +import pl.szczodrzynski.edziennik.data.api.szkolny.response.ApiResponse + +class SzkolnyApiException(val error: ApiResponse.Error?) : Exception(if (error == null) "Error body does not contain a valid Error." else "${error.code}: ${error.reason}") diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/SzkolnyService.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/SzkolnyService.kt new file mode 100644 index 00000000..5c60c3ff --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/SzkolnyService.kt @@ -0,0 +1,50 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-8 + */ + +package pl.szczodrzynski.edziennik.data.api.szkolny + +import pl.szczodrzynski.edziennik.data.api.szkolny.request.* +import pl.szczodrzynski.edziennik.data.api.szkolny.response.* +import pl.szczodrzynski.edziennik.ui.login.LoginInfo +import retrofit2.Call +import retrofit2.http.* + +interface SzkolnyService { + + @POST("appSync") + fun serverSync(@Body request: ServerSyncRequest): Call> + + @POST("share") + fun shareEvent(@Body request: EventShareRequest): Call> + + @POST("share") + fun shareNote(@Body request: NoteShareRequest): Call> + + @POST("webPush") + fun webPush(@Body request: WebPushRequest): Call> + + @POST("errorReport") + fun errorReport(@Body request: ErrorReportRequest): Call> + + @POST("appUser") + fun appUser(@Body request: AppUserRequest): Call> + + @GET("contributors/android") + fun contributors(): Call> + + @GET("updates/app") + fun updates(@Query("channel") channel: String = "release"): Call>> + + @POST("feedbackMessage") + fun feedbackMessage(@Body request: FeedbackMessageRequest): Call> + + @GET("firebase/token/{registerName}") + fun firebaseToken(@Path("registerName") registerName: String): Call> + + @GET("registerAvailability") + fun registerAvailability(): Call>> + + @GET("https://szkolny-eu.github.io/FSLogin/realms/{registerName}.json") + fun fsLoginRealms(@Path("registerName") registerName: String): Call> +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/adapter/DateAdapter.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/adapter/DateAdapter.kt new file mode 100644 index 00000000..01f2d6ef --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/adapter/DateAdapter.kt @@ -0,0 +1,29 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-8 + */ + +package pl.szczodrzynski.edziennik.data.api.szkolny.adapter + +import com.google.gson.TypeAdapter +import com.google.gson.stream.JsonReader +import com.google.gson.stream.JsonToken +import com.google.gson.stream.JsonWriter +import pl.szczodrzynski.edziennik.utils.models.Date + +class DateAdapter : TypeAdapter() { + override fun write(writer: JsonWriter?, date: Date?) { + if (date == null) { + writer?.nullValue() + } else { + writer?.value(date.value) + } + } + + override fun read(reader: JsonReader?): Date? { + if (reader?.peek() == JsonToken.NULL) { + reader.nextNull() + return null + } + return reader?.nextInt()?.let { Date.fromValue(it) } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/adapter/TimeAdapter.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/adapter/TimeAdapter.kt new file mode 100644 index 00000000..69abca66 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/adapter/TimeAdapter.kt @@ -0,0 +1,29 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2019-12-8 + */ + +package pl.szczodrzynski.edziennik.data.api.szkolny.adapter + +import com.google.gson.TypeAdapter +import com.google.gson.stream.JsonReader +import com.google.gson.stream.JsonToken +import com.google.gson.stream.JsonWriter +import pl.szczodrzynski.edziennik.utils.models.Time + +class TimeAdapter : TypeAdapter