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 25786692..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,22 +46,22 @@ captures/ .idea/tasks.xml .idea/gradle.xml .idea/assetWizardSettings.xml -.idea/dictionaries +#.idea/dictionaries .idea/libraries # Android Studio 3 in .gitignore file. .idea/caches .idea/modules.xml # Comment next line if keeping position of elements in Navigation Editor is relevant for you .idea/navEditor.xml -.idea/copyright/profiles_settings.xml # 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 @@ -82,8 +88,181 @@ lint/outputs/ lint/tmp/ # lint/reports/ -app/schemas/ +### 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/ - -app/.cxx \ No newline at end of file +.idea/*.xml diff --git a/.idea/.name b/.idea/.name deleted file mode 100644 index 9ffcbb8a..00000000 --- a/.idea/.name +++ /dev/null @@ -1 +0,0 @@ -Szkolny.eu \ No newline at end of file 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/dictionaries/Kuba.xml b/.idea/dictionaries/Kuba.xml new file mode 100644 index 00000000..aba38775 --- /dev/null +++ b/.idea/dictionaries/Kuba.xml @@ -0,0 +1,19 @@ + + + + autoryzacji + ciasteczko + csrf + edziennik + elearning + gson + hebe + idziennik + kuba + synergia + szczodrzyński + szkolny + usos + + + \ 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/jarRepositories.xml b/.idea/jarRepositories.xml deleted file mode 100644 index 6afdce41..00000000 --- a/.idea/jarRepositories.xml +++ /dev/null @@ -1,45 +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 24f8c447..00000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,60 +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 92731fb9..00000000 --- a/agendacalendarview/build.gradle +++ /dev/null @@ -1,54 +0,0 @@ -apply plugin: 'com.android.library' -//apply plugin: 'me.tatarka.retrolambda' - -android { - compileSdkVersion setup.compileSdk - - android { - lintOptions { - abortOnError false - } - } - - defaultConfig { - minSdkVersion 14 - targetSdkVersion setup.targetSdk - 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:${versions.appcompat}" - implementation "androidx.recyclerview:recyclerview:${versions.recyclerView}" - implementation "com.google.android.material:material:${versions.material}" - - // 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/event_color_circle.xml b/agendacalendarview/src/main/res/drawable/event_color_circle.xml deleted file mode 100644 index 3cc72359..00000000 --- a/agendacalendarview/src/main/res/drawable/event_color_circle.xml +++ /dev/null @@ -1,5 +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 ca5c9fcd..57334e8f 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,73 +1,105 @@ apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-kapt' -apply plugin: 'kotlin-android-extensions' +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 setup.compileSdk + defaultConfig { applicationId 'pl.szczodrzynski.edziennik' minSdkVersion setup.minSdk targetSdkVersion setup.targetSdk + versionCode release.versionCode versionName release.versionName - multiDexEnabled true + + 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" } } - } - 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" - } + + kapt { + arguments { + arg("room.schemaLocation", "$projectDir/schemas") } } + } + + buildTypes { debug { - minifyEnabled false + getIsDefault().set(true) + 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 { + unofficial { + getIsDefault().set(true) + versionName "${release.versionName}-${gitInfo.versionSuffix}" + } + official {} + play {} } + variantFilter { variant -> + def flavors = variant.flavors*.name + setIgnore(variant.buildType.name == "debug" && !flavors.contains("unofficial") || flavors.contains("main")) + } + sourceSets { + unofficial { + java.srcDirs = ["src/main/java", "src/play-not/java"] + manifest.srcFile("src/play-not/AndroidManifest.xml") + } + official { + java.srcDirs = ["src/main/java", "src/play-not/java"] + manifest.srcFile("src/play-not/AndroidManifest.xml") + } + play { + java.srcDirs = ["src/main/java", "src/play/java"] + } + } + defaultConfig { vectorDrawables.useSupportLibrary = true } - lintOptions { - 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" } packagingOptions { - exclude 'META-INF/library-core_release.kotlin_module' + resources { + excludes += ['META-INF/library-core_release.kotlin_module'] + } } externalNativeBuild { cmake { @@ -75,125 +107,124 @@ android { version "3.10.2" } } -} - -/*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 + lint { + checkReleaseBuilds false } -}*/ +} + +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') - kapt "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" + implementation "androidx.multidex:multidex:2.0.1" + 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.5.1" + implementation "androidx.cardview:cardview:1.0.0" + implementation "androidx.constraintlayout:constraintlayout:2.1.4" + implementation "androidx.core:core-ktx:1.9.0" + implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.5.1" + implementation "androidx.navigation:navigation-fragment-ktx:2.5.2" + implementation "androidx.recyclerview:recyclerview:1.2.1" + implementation "androidx.room:room-runtime:2.4.3" + implementation "androidx.work:work-runtime-ktx:2.7.1" + kapt "androidx.room:room-compiler:2.4.3" - 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.6.1" + 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" - implementation "com.mikepenz:materialize:1.2.1" + // Play Services/Firebase + implementation "com.google.android.gms:play-services-wearable:17.1.0" + implementation("com.google.firebase:firebase-core") { version { strictly "19.0.2" } } + implementation "com.google.firebase:firebase-crashlytics:18.2.13" + 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" + officialImplementation "eu.szkolny:ssl-provider:1.0.0" + unofficialImplementation "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.2" - 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") - - implementation "com.github.ChuckerTeam.Chucker:library:3.0.1" - //releaseImplementation "com.github.ChuckerTeam.Chucker:library-no-op:3.0.1" - - //implementation 'com.github.wulkanowy:uonet-request-signer:master-SNAPSHOT' - //implementation 'com.github.kuba2k2.uonet-request-signer:android:master-63f094b14a-1' - - //implementation "org.redundent:kotlin-xml-builder:1.5.3" - - implementation "io.github.wulkanowy:signer-android:0.1.1" - - implementation "androidx.work:work-runtime-ktx:${versions.work}" - - implementation 'com.hypertrack:hyperlog:0.0.10' - - implementation 'com.github.kuba2k2:RecyclerTabLayout:700f980584' - - implementation 'com.github.kuba2k2:Tachyon:551943a6b5' - - implementation "com.squareup.retrofit2:retrofit:${versions.retrofit}" - implementation "com.squareup.retrofit2:converter-gson:${versions.retrofit}" - - implementation 'com.github.jetradarmobile:android-snowfall:1.2.0' - - implementation "io.coil-kt:coil:0.9.2" - - implementation 'com.github.kuba2k2:NumberSlidingPicker:2921225f76' -} -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/proguard/app.pro b/app/proguard-rules.pro similarity index 80% rename from app/proguard/app.pro rename to app/proguard-rules.pro index 711a62e4..1d72bf89 100644 --- a/app/proguard/app.pro +++ b/app/proguard-rules.pro @@ -25,15 +25,17 @@ -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.ui.modules.home.HomeCardModel { *; } +-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); } --keepclassmembernames class androidx.appcompat.view.menu.StandardMenuPopup { private *; } -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 *; } @@ -64,5 +66,9 @@ -keep class pl.szczodrzynski.edziennik.data.api.szkolny.interceptor.Signing { public final byte[] pleaseStopRightNow(java.lang.String, long); } --keepclassmembernames class pl.szczodrzynski.edziennik.data.api.szkolny.request.** { *; } --keepclassmembernames class pl.szczodrzynski.edziennik.data.api.szkolny.response.** { *; } +-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/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/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/schemas/pl.szczodrzynski.edziennik.data.db.AppDb/98.json b/app/schemas/pl.szczodrzynski.edziennik.data.db.AppDb/98.json new file mode 100644 index 00000000..1a291aef --- /dev/null +++ b/app/schemas/pl.szczodrzynski.edziennik.data.db.AppDb/98.json @@ -0,0 +1,2314 @@ +{ + "formatVersion": 1, + "database": { + "version": 98, + "identityHash": "2612ebba9802eedc7ebc69724606a23c", + "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" + ], + "orders": [], + "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" + ], + "orders": [], + "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" + ], + "orders": [], + "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" + ], + "orders": [], + "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" + ], + "orders": [], + "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" + ], + "orders": [], + "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" + ], + "orders": [], + "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" + ], + "orders": [], + "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, `color` INTEGER, `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": "color", + "columnName": "color", + "affinity": "INTEGER", + "notNull": false + }, + { + "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" + ], + "orders": [], + "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" + ], + "orders": [], + "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" + ], + "orders": [], + "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" + ], + "orders": [], + "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" + ], + "orders": [], + "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" + ], + "orders": [], + "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" + ], + "orders": [], + "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, '2612ebba9802eedc7ebc69724606a23c')" + ] + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 21c13afb..2c24b426 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -3,7 +3,6 @@ xmlns:tools="http://schemas.android.com/tools" package="pl.szczodrzynski.edziennik"> - @@ -13,6 +12,9 @@ + + + + + + android:label="@string/widget_timetable_title" + android:exported="true"> @@ -84,10 +90,12 @@ android:configChanges="orientation|keyboardHidden" android:excludeFromRecents="true" android:noHistory="true" + android:exported="true" android:theme="@style/AppTheme.Dark.NoDisplay" /> + android:label="@string/widget_notifications_title" + android:exported="true"> @@ -100,7 +108,8 @@ android:permission="android.permission.BIND_REMOTEVIEWS" /> + android:label="@string/widget_lucky_number_title" + android:exported="true"> @@ -117,37 +126,43 @@ / ____ \ (__| |_| |\ V /| | |_| | __/\__ \ /_/ \_\___|\__|_| \_/ |_|\__|_|\___||___/ --> - - - - - - - - - - + + + + android:enabled="true" + android:exported="true"> - + @@ -181,13 +198,6 @@ ____) | __/ | \ V /| | (_| __/\__ \ |_____/ \___|_| \_/ |_|\___\___||___/ --> - 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 7f69e85a..d57022f1 100644 --- a/app/src/main/assets/pl-changelog.html +++ b/app/src/main/assets/pl-changelog.html @@ -1,29 +1,11 @@ -

    Wersja 4.0-rc.2, 2020-03-26

    +

    Wersja 4.13-beta.1, 2022-10-17

      -
    • Wysyłanie wiadomości - funkcja, na którą czekał każdy. Od teraz w Szkolnym można wysyłać oraz odpowiadać na wiadomości do nauczycieli 👏
    • -
    • Przebudowaliśmy cały moduł synchronizacji, co oznacza większą stabilność aplikacji, szybkość oraz poprawność pobieranych danych
    • -
    • Udoskonalony wygląd Szkolnego - sprawi, że korzystanie z aplikacji będzie jeszcze przyjemniejsze
    • -
    • Nowa Strona główna - ładniejszy wygląd oraz możliwość przestawiania kart na każdym profilu
    • -
    • Nowy Plan lekcji - z doskonałą obsługą lekcji przesuniętych oraz dwóch lekcji o tej samej godzinie
    • -
    • Nowe Oceny - z możliwością zmiany wartości plusów oraz minusów oraz wyłączenia niektórych ocen ze średniej
    • -
    • Opcja wyłączenia wybranych powiadomień z aplikacji
    • -
    • Znaczki nieprzeczytanych informacji na obrazkach profili.
    • -
      -
      -
    • Nowe okienka informacji o wydarzeniach oraz lekcjach
    • -
    • Nowe, przyjemniejsze powiadomienia
    • -
    • Dużo poprawek w widoku Wiadomości oraz Ogłoszeń
    • -
    • Częściowa Obsługa dziennika EduDziennik
    • -
    • Librus: opcja logowania w dziennikach Jednostek Samorządu Terytorialnego oraz Oświata w Radomiu
    • -
    • Librus: poprawione obliczanie frekwencji
    • -
    • Librus: obsługa Zadań domowych bez posiadania Mobilnych dodatków (przez system Synergia)
    • -
    • Lepsze przekazywanie powiadomień na komputer oraz łatwiejsze parowanie
    • -
    • Łatwiejsze dodawanie własnych wydarzeń
    • -
    • Poprawiliśmy synchronizację w tle na niektórych telefonach
    • -
    • Usunąłem denerwujący brak zaznaczenia w lewym menu
    • -
    • Znaczna ilość błędów z poprzednich wersji już nie występuje
    • +
    • Poprawione powiadomienia na Androidzie 13. @santoni0
    • +
    • Możliwość dostosowania wyświetlania planu lekcji
    • +
    • Opcja kolorowania bloków w planie lekcji
    • +
    • USOS - pierwsza wersja obsługi systemu


    Dzięki za korzystanie ze Szkolnego!
    -© Kuba Szczodrzyński, Kacper Ziubryniewicz 2020 +© [Kuba Szczodrzyński](@kuba2k2), [Kacper Ziubryniewicz](@kapi2289) 2022 diff --git a/app/src/main/cpp/szkolny-signing.cpp b/app/src/main/cpp/szkolny-signing.cpp index f43b766b..57774985 100644 --- a/app/src/main/cpp/szkolny-signing.cpp +++ b/app/src/main/cpp/szkolny-signing.cpp @@ -9,7 +9,7 @@ /*secret password - removed for source code publication*/ static toys AES_IV[16] = { - 0x30, 0xfe, 0xe2, 0x8d, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + 0x12, 0xdd, 0xb2, 0x93, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; unsigned char *agony(unsigned int laugh, unsigned char *box, unsigned char *heat); diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/App.kt b/app/src/main/java/pl/szczodrzynski/edziennik/App.kt index 59db1ab2..56886775 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/App.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/App.kt @@ -26,7 +26,6 @@ import com.google.firebase.messaging.FirebaseMessaging import com.google.gson.Gson import com.hypertrack.hyperlog.HyperLog import com.mikepenz.iconics.Iconics -import com.mikepenz.iconics.typeface.library.szkolny.font.SzkolnyFont import im.wangchao.mhttp.MHttp import kotlinx.coroutines.* import me.leolin.shortcutbadger.ShortcutBadger @@ -34,19 +33,21 @@ 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.network.NetworkUtils +import pl.szczodrzynski.edziennik.ext.DAY +import pl.szczodrzynski.edziennik.ext.MS +import pl.szczodrzynski.edziennik.ext.setLanguage +import pl.szczodrzynski.edziennik.network.SSLProviderInstaller import pl.szczodrzynski.edziennik.network.cookie.DumbCookieJar import pl.szczodrzynski.edziennik.sync.SyncWorker import pl.szczodrzynski.edziennik.sync.UpdateWorker -import pl.szczodrzynski.edziennik.ui.modules.base.CrashActivity +import pl.szczodrzynski.edziennik.ui.base.CrashActivity import pl.szczodrzynski.edziennik.utils.* -import pl.szczodrzynski.edziennik.utils.managers.GradesManager -import pl.szczodrzynski.edziennik.utils.managers.NotificationChannelsManager -import pl.szczodrzynski.edziennik.utils.managers.TimetableManager -import pl.szczodrzynski.edziennik.utils.managers.UserActionManager +import pl.szczodrzynski.edziennik.utils.Utils.d +import pl.szczodrzynski.edziennik.utils.managers.* import java.util.concurrent.TimeUnit import kotlin.coroutines.CoroutineContext @@ -54,19 +55,29 @@ class App : MultiDexApplication(), Configuration.Provider, CoroutineScope { companion object { @Volatile lateinit var db: AppDb - val config: Config by lazy { Config(db) } - var profile: Profile by mutableLazy { Profile(0, 0, 0, "") } + lateinit var config: Config + lateinit var profile: Profile val profileId get() = profile.id - var devMode = false + 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 @@ -85,7 +96,6 @@ class App : MultiDexApplication(), Configuration.Provider, CoroutineScope { .build() val permissionChecker by lazy { PermissionChecker(this) } - val networkUtils by lazy { NetworkUtils(this) } val gson by lazy { Gson() } /* _ _ _______ _______ _____ @@ -94,34 +104,41 @@ class App : MultiDexApplication(), Configuration.Provider, CoroutineScope { | __ | | | | | | ___/ | | | | | | | | | | |_| |_| |_| |_| |*/ - val http: OkHttpClient by lazy { - val builder = OkHttpClient.Builder() - .cache(null) - .followRedirects(true) - .followSslRedirects(true) - .retryOnConnectionFailure(true) - .cookieJar(cookieJar) - .connectTimeout(20, TimeUnit.SECONDS) - .writeTimeout(5, TimeUnit.SECONDS) - .readTimeout(10, TimeUnit.SECONDS) - builder.installHttpsSupport(this) + lateinit var http: OkHttpClient + lateinit var httpLazy: OkHttpClient - if (debugMode || BuildConfig.DEBUG) { + 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) + + SSLProviderInstaller.enableSupportedTls(builder, enableCleartext = true) + + if (devMode) { HyperLog.initialize(this) HyperLog.setLogLevel(Log.VERBOSE) HyperLog.setLogFormat(DebugLogFormat(this)) - val chuckerCollector = ChuckerCollector(this, true, RetentionManager.Period.ONE_HOUR) - val chuckerInterceptor = ChuckerInterceptor(this, chuckerCollector) - builder.addInterceptor(chuckerInterceptor) + if (enableChucker) { + val chuckerCollector = ChuckerCollector(this, true, RetentionManager.Period.ONE_HOUR) + val chuckerInterceptor = ChuckerInterceptor(this, chuckerCollector) + builder.addInterceptor(chuckerInterceptor) + } } - builder.build() - } - val httpLazy: OkHttpClient by lazy { - http.newBuilder() - .followRedirects(false) - .followSslRedirects(false) - .build() + http = builder.build() + + httpLazy = http.newBuilder() + .followRedirects(false) + .followSslRedirects(false) + .build() + + MHttp.instance().customOkHttpClient(http) } val cookieJar by lazy { DumbCookieJar(this) } @@ -158,17 +175,26 @@ class App : MultiDexApplication(), Configuration.Provider, CoroutineScope { .errorActivity(CrashActivity::class.java) .apply() Iconics.init(applicationContext) - Iconics.registerFont(SzkolnyFont) + Iconics.respectFontBoundsDefault = true + + // initialize companion object values App.db = AppDb(this) - Themes.themeInt = config.ui.theme - debugMode = config.debugMode - MHttp.instance().customOkHttpClient(http) + 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) } } - devMode = "f054761fbdb6a238" == deviceId || BuildConfig.DEBUG + buildHttp() + + Themes.themeInt = config.ui.theme + config.ui.language?.let { + setLanguage(it) + } Signing.getCert(this) @@ -176,9 +202,10 @@ class App : MultiDexApplication(), Configuration.Provider, CoroutineScope { withContext(Dispatchers.Default) { config.migrate(this@App) + SSLProviderInstaller.install(applicationContext, this@App::buildHttp) + if (config.devModePassword != null) checkDevModePassword() - debugMode = devMode || config.debugMode if (config.sync.enabled) SyncWorker.scheduleNext(this@App, false) @@ -251,6 +278,10 @@ class App : MultiDexApplication(), Configuration.Provider, CoroutineScope { 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(), @@ -260,6 +291,10 @@ class App : MultiDexApplication(), Configuration.Provider, CoroutineScope { 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(), @@ -269,19 +304,38 @@ class App : MultiDexApplication(), Configuration.Provider, CoroutineScope { 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() @@ -289,6 +343,7 @@ class App : MultiDexApplication(), Configuration.Provider, CoroutineScope { } 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() @@ -296,11 +351,20 @@ class App : MultiDexApplication(), Configuration.Provider, CoroutineScope { } 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() @@ -341,6 +405,9 @@ class App : MultiDexApplication(), Configuration.Provider, CoroutineScope { if (!success) { EventBus.getDefault().post(ProfileListEmptyEvent()) } + else { + onSuccess(profile) + } } } fun profileSave() = profileSave(profile) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/Binding.kt b/app/src/main/java/pl/szczodrzynski/edziennik/Binding.kt index 3dc9d0a6..fba06502 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/Binding.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/Binding.kt @@ -4,8 +4,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 @@ -17,4 +20,64 @@ object Binding { 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 0d7b1f56..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/Extensions.kt +++ /dev/null @@ -1,1168 +0,0 @@ -package pl.szczodrzynski.edziennik - -import android.Manifest -import android.app.Activity -import android.content.ClipData -import android.content.ClipboardManager -import android.content.Context -import android.content.Intent -import android.content.pm.PackageManager -import android.content.res.ColorStateList -import android.content.res.Resources -import android.database.Cursor -import android.graphics.PorterDuff -import android.graphics.PorterDuffColorFilter -import android.graphics.Rect -import android.graphics.Typeface -import android.graphics.drawable.Drawable -import android.os.Build -import android.os.Bundle -import android.text.* -import android.text.style.ForegroundColorSpan -import android.text.style.StrikethroughSpan -import android.text.style.StyleSpan -import android.util.* -import android.util.Base64 -import android.util.Base64.NO_WRAP -import android.util.Base64.encodeToString -import android.view.View -import android.view.WindowManager -import android.widget.CheckBox -import android.widget.CompoundButton -import android.widget.RadioButton -import android.widget.TextView -import androidx.annotation.* -import androidx.core.app.ActivityCompat -import androidx.core.database.getIntOrNull -import androidx.core.database.getLongOrNull -import androidx.core.database.getStringOrNull -import androidx.core.util.forEach -import androidx.lifecycle.LifecycleOwner -import androidx.lifecycle.LiveData -import androidx.lifecycle.Observer -import com.google.android.gms.security.ProviderInstaller -import com.google.gson.JsonArray -import com.google.gson.JsonElement -import com.google.gson.JsonObject -import com.google.gson.JsonParser -import im.wangchao.mhttp.Response -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch -import okhttp3.ConnectionSpec -import okhttp3.OkHttpClient -import okhttp3.RequestBody -import okhttp3.TlsVersion -import okio.Buffer -import pl.szczodrzynski.edziennik.data.api.* -import pl.szczodrzynski.edziennik.data.api.models.ApiError -import pl.szczodrzynski.edziennik.data.api.szkolny.SzkolnyApiException -import pl.szczodrzynski.edziennik.data.api.szkolny.response.ApiResponse -import pl.szczodrzynski.edziennik.data.db.entity.Notification -import pl.szczodrzynski.edziennik.data.db.entity.Profile -import pl.szczodrzynski.edziennik.data.db.entity.Teacher -import pl.szczodrzynski.edziennik.data.db.entity.Team -import pl.szczodrzynski.edziennik.network.TLSSocketFactory -import pl.szczodrzynski.edziennik.utils.models.Time -import java.io.InterruptedIOException -import java.io.PrintWriter -import java.io.StringWriter -import java.math.BigInteger -import java.net.ConnectException -import java.net.SocketTimeoutException -import java.net.UnknownHostException -import java.nio.charset.Charset -import java.security.KeyStore -import java.security.MessageDigest -import java.text.SimpleDateFormat -import java.util.* -import java.util.zip.CRC32 -import javax.crypto.Mac -import javax.crypto.spec.SecretKeySpec -import javax.net.ssl.SSLContext -import javax.net.ssl.SSLException -import javax.net.ssl.TrustManagerFactory -import javax.net.ssl.X509TrustManager -import kotlin.Pair - - -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?.get(key: String): JsonElement? = this?.get(key) - -fun JsonObject?.getBoolean(key: String): Boolean? = get(key)?.let { if (it.isJsonNull) null else it.asBoolean } -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?.getFloat(key: String): Float? = get(key)?.let { if(it.isJsonNull) null else it.asFloat } -fun JsonObject?.getChar(key: String): Char? = get(key)?.let { if(it.isJsonNull) null else it.asCharacter } -fun JsonObject?.getJsonObject(key: String): JsonObject? = get(key)?.let { if (it.isJsonObject) it.asJsonObject else null } -fun JsonObject?.getJsonArray(key: String): JsonArray? = get(key)?.let { if (it.isJsonArray) it.asJsonArray else null } - -fun JsonObject?.getBoolean(key: String, defaultValue: Boolean): Boolean = get(key)?.let { if (it.isJsonNull) defaultValue else it.asBoolean } ?: defaultValue -fun JsonObject?.getString(key: String, defaultValue: String): String = get(key)?.let { if (it.isJsonNull) defaultValue else it.asString } ?: defaultValue -fun JsonObject?.getInt(key: String, defaultValue: Int): Int = get(key)?.let { if (it.isJsonNull) defaultValue else it.asInt } ?: defaultValue -fun JsonObject?.getLong(key: String, defaultValue: Long): Long = get(key)?.let { if (it.isJsonNull) defaultValue else it.asLong } ?: defaultValue -fun JsonObject?.getFloat(key: String, defaultValue: Float): Float = get(key)?.let { if(it.isJsonNull) defaultValue else it.asFloat } ?: defaultValue -fun JsonObject?.getChar(key: String, defaultValue: Char): Char = get(key)?.let { if(it.isJsonNull) defaultValue else it.asCharacter } ?: defaultValue -fun JsonObject?.getJsonObject(key: String, defaultValue: JsonObject): JsonObject = get(key)?.let { if (it.isJsonObject) it.asJsonObject else defaultValue } ?: defaultValue -fun JsonObject?.getJsonArray(key: String, defaultValue: JsonArray): JsonArray = get(key)?.let { if (it.isJsonArray) it.asJsonArray else defaultValue } ?: defaultValue - -fun JsonArray.getBoolean(key: Int): Boolean? = if (key >= size()) null else get(key)?.let { if (it.isJsonNull) null else it.asBoolean } -fun JsonArray.getString(key: Int): String? = if (key >= size()) null else get(key)?.let { if (it.isJsonNull) null else it.asString } -fun JsonArray.getInt(key: Int): Int? = if (key >= size()) null else get(key)?.let { if (it.isJsonNull) null else it.asInt } -fun JsonArray.getLong(key: Int): Long? = if (key >= size()) null else get(key)?.let { if (it.isJsonNull) null else it.asLong } -fun JsonArray.getFloat(key: Int): Float? = if (key >= size()) null else get(key)?.let { if(it.isJsonNull) null else it.asFloat } -fun JsonArray.getChar(key: Int): Char? = if (key >= size()) null else get(key)?.let { if(it.isJsonNull) null else it.asCharacter } -fun JsonArray.getJsonObject(key: Int): JsonObject? = if (key >= size()) null else get(key)?.let { if (it.isJsonObject) it.asJsonObject else null } -fun JsonArray.getJsonArray(key: Int): JsonArray? = if (key >= size()) null else get(key)?.let { if (it.isJsonArray) it.asJsonArray else null } - -fun String.toJsonObject(): JsonObject? = try { JsonParser().parse(this).asJsonObject } catch (ignore: Exception) { null } - -operator fun JsonObject.set(key: String, value: JsonElement) = this.add(key, value) -operator fun JsonObject.set(key: String, value: Boolean) = this.addProperty(key, value) -operator fun JsonObject.set(key: String, value: String?) = this.addProperty(key, value) -operator fun JsonObject.set(key: String, value: Number) = this.addProperty(key, value) -operator fun JsonObject.set(key: String, value: Char) = this.addProperty(key, value) - -operator fun Profile.set(key: String, value: JsonElement) = this.studentData.add(key, value) -operator fun Profile.set(key: String, value: Boolean) = this.studentData.addProperty(key, value) -operator fun Profile.set(key: String, value: String?) = this.studentData.addProperty(key, value) -operator fun Profile.set(key: String, value: Number) = this.studentData.addProperty(key, value) -operator fun Profile.set(key: String, value: Char) = this.studentData.addProperty(key, value) - -fun JsonArray.asJsonObjectList() = this.mapNotNull { it.asJsonObject } - -fun CharSequence?.isNotNullNorEmpty(): Boolean { - return this != null && this.isNotEmpty() -} - -fun CharSequence?.isNotNullNorBlank(): Boolean { - return this != null && this.isNotBlank() -} - -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 -} - -/** - * ` The quick BROWN_fox Jumps OveR THE LAZy-DOG. ` - * - * converts to - * - * `The Quick Brown_fox Jumps Over The Lazy-Dog.` - */ -fun String?.fixName(): String { - return this?.fixWhiteSpaces()?.toProperCase() ?: "" -} - -/** - * `The quick BROWN_fox Jumps OveR THE LAZy-DOG.` - * - * converts to - * - * `The Quick Brown_fox Jumps Over The Lazy-Dog.` - */ -fun String.toProperCase(): String = changeStringCase(this) - -/** - * `John Smith` -> `Smith John` - * - * `JOHN SMith` -> `SMith JOHN` - */ -fun String.swapFirstLastName(): String { - return this.split(" ").let { - if (it.size > 1) - it[1]+" "+it[0] - else - it[0] - } -} - -fun String.splitName(): Pair? { - return this.split(" ").let { - if (it.size >= 2) Pair(it[0], it[1]) - else null - } -} - -fun changeStringCase(s: String): String { - val delimiters = " '-/" - val sb = StringBuilder() - var capNext = true - for (ch in s.toCharArray()) { - var c = ch - c = if (capNext) - Character.toUpperCase(c) - else - Character.toLowerCase(c) - sb.append(c) - capNext = delimiters.indexOf(c) >= 0 - } - return sb.toString() -} - -fun buildFullName(firstName: String?, lastName: String?): String { - return "$firstName $lastName".fixName() -} - -fun String.getShortName(): String { - return split(" ").let { - if (it.size > 1) - "${it[0]} ${it[1][0]}." - else - it[0] - } -} - -/** - * "John Smith" -> "JS" - * - * "JOHN SMith" -> "JS" - * - * "John" -> "J" - * - * "John " -> "J" - * - * "John Smith " -> "JS" - * - * " " -> "" - * - * " " -> "" - */ -fun String?.getNameInitials(): String { - if (this.isNullOrBlank()) return "" - return this.toUpperCase().fixWhiteSpaces().split(" ").take(2).map { it[0] }.joinToString("") -} - -fun List.join(delimiter: String): String { - return concat(delimiter).toString() -} - -fun colorFromName(name: String?): Int { - val i = (name ?: "").crc32() - return when ((i / 10 % 16 + 1).toInt()) { - 13 -> 0xffF44336 - 4 -> 0xffF50057 - 2 -> 0xffD500F9 - 9 -> 0xff6200EA - 5 -> 0xffFFAB00 - 1 -> 0xff304FFE - 6 -> 0xff40C4FF - 14 -> 0xff26A69A - 15 -> 0xff00C853 - 7 -> 0xffFFD600 - 3 -> 0xffFF3D00 - 8 -> 0xffDD2C00 - 10 -> 0xff795548 - 12 -> 0xff2979FF - 11 -> 0xffFF6D00 - else -> 0xff64DD17 - }.toInt() -} - -fun colorFromCssName(name: String): Int { - return when (name) { - "red" -> 0xffff0000 - "green" -> 0xff008000 - "blue" -> 0xff0000ff - "violet" -> 0xffee82ee - "brown" -> 0xffa52a2a - "orange" -> 0xffffa500 - "black" -> 0xff000000 - "white" -> 0xffffffff - else -> -1 - }.toInt() -} - -fun List.filterOutArchived() = this.filter { !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 Response?.getUnixDate(): Long { - val rfcDate = this?.headers()?.get("date") ?: return currentTimeUnix() - val pattern = "EEE, dd MMM yyyy HH:mm:ss Z" - val format = SimpleDateFormat(pattern, Locale.ENGLISH) - return format.parse(rfcDate).time / 1000 -} - -const val MINUTE = 60L -const val HOUR = 60L*MINUTE -const val DAY = 24L*HOUR -const val WEEK = 7L*DAY -const val MONTH = 30L*DAY -const val YEAR = 365L*DAY -const val MS = 1000L - -fun LongSparseArray.values(): List { - val result = mutableListOf() - forEach { _, value -> - result += value - } - return result -} - -fun SparseArray<*>.keys(): List { - val result = mutableListOf() - forEach { key, _ -> - result += key - } - return result -} -fun SparseArray.values(): List { - val result = mutableListOf() - forEach { _, value -> - result += value - } - return result -} - -fun SparseIntArray.keys(): List { - val result = mutableListOf() - forEach { key, _ -> - result += key - } - return result -} -fun SparseIntArray.values(): List { - val result = mutableListOf() - forEach { _, value -> - result += value - } - return result -} - -fun List>.keys(): List { - val result = mutableListOf() - forEach { pair -> - result += pair.first - } - return result -} -fun List>.values(): List { - val result = mutableListOf() - forEach { pair -> - result += pair.second - } - return result -} - -fun List.toSparseArray(destination: SparseArray, key: (T) -> Int) { - forEach { - destination.put(key(it), it) - } -} -fun List.toSparseArray(destination: LongSparseArray, key: (T) -> Long) { - forEach { - destination.put(key(it), it) - } -} - -fun List.toSparseArray(key: (T) -> Int): SparseArray { - val result = SparseArray() - toSparseArray(result, key) - return result -} -fun List.toSparseArray(key: (T) -> Long): LongSparseArray { - val result = LongSparseArray() - toSparseArray(result, key) - return result -} - -fun SparseArray.singleOrNull(predicate: (T) -> Boolean): T? { - forEach { _, value -> - if (predicate(value)) - return value - } - return null -} -fun LongSparseArray.singleOrNull(predicate: (T) -> Boolean): T? { - forEach { _, value -> - if (predicate(value)) - return value - } - return null -} - -fun String.fixWhiteSpaces() = buildString(length) { - var wasWhiteSpace = true - for (c in this@fixWhiteSpaces) { - if (c.isWhitespace()) { - if (!wasWhiteSpace) { - append(c) - wasWhiteSpace = true - } - } else { - append(c) - wasWhiteSpace = false - } - } -}.trimEnd() - -fun List.getById(id: Long): Team? { - return singleOrNull { it.id == id } -} -fun LongSparseArray.getById(id: Long): Team? { - forEach { _, value -> - if (value.id == id) - return value - } - return null -} - -operator fun MatchResult.get(group: Int): String { - if (group >= groupValues.size) - return "" - return groupValues[group] -} - -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) - } -} - -fun String.crc16(): Int { - var crc = 0xFFFF - for (aBuffer in this) { - crc = crc.ushr(8) or (crc shl 8) and 0xffff - crc = crc xor (aBuffer.toInt() and 0xff) // byte to int, trunc sign - crc = crc xor (crc and 0xff shr 4) - crc = crc xor (crc shl 12 and 0xffff) - crc = crc xor (crc and 0xFF shl 5 and 0xffff) - } - crc = crc and 0xffff - return crc + 32768 -} - -fun String.crc32(): Long { - val crc = CRC32() - crc.update(toByteArray()) - return crc.value -} - -fun String.hmacSHA1(password: String): String { - val key = SecretKeySpec(password.toByteArray(), "HmacSHA1") - - val mac = Mac.getInstance("HmacSHA1").apply { - init(key) - update(this@hmacSHA1.toByteArray()) - } - - return encodeToString(mac.doFinal(), NO_WRAP) -} - -fun String.md5(): String { - val md = MessageDigest.getInstance("MD5") - return BigInteger(1, md.digest(toByteArray())).toString(16).padStart(32, '0') -} - -fun String.sha256(): ByteArray { - val md = MessageDigest.getInstance("SHA-256") - md.update(toByteArray()) - return md.digest() -} - -fun RequestBody.bodyToString(): String { - val buffer = Buffer() - writeTo(buffer) - return buffer.readUtf8() -} - -fun Long.formatDate(format: String = "yyyy-MM-dd HH:mm:ss"): String = SimpleDateFormat(format).format(this) - -fun CharSequence?.asColoredSpannable(colorInt: Int): Spannable { - val spannable = SpannableString(this) - spannable.setSpan(ForegroundColorSpan(colorInt), 0, spannable.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) - return spannable -} -fun CharSequence?.asStrikethroughSpannable(): Spannable { - val spannable = SpannableString(this) - spannable.setSpan(StrikethroughSpan(), 0, spannable.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) - return spannable -} -fun CharSequence?.asItalicSpannable(): Spannable { - val spannable = SpannableString(this) - spannable.setSpan(StyleSpan(Typeface.ITALIC), 0, spannable.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) - return spannable -} -fun CharSequence?.asBoldSpannable(): Spannable { - val spannable = SpannableString(this) - spannable.setSpan(StyleSpan(Typeface.BOLD), 0, spannable.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) - return spannable -} -fun CharSequence.asSpannable(vararg spans: Any, substring: String? = null, ignoreCase: Boolean = false): Spannable { - val spannable = SpannableString(this) - if (substring == null) { - spans.forEach { - spannable.setSpan(it, 0, spannable.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) - } - } - else if (substring.isNotEmpty()) { - var index = indexOf(substring, ignoreCase = ignoreCase) - while (index >= 0) { - spans.forEach { - spannable.setSpan(it, index, index + substring.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) - } - index = indexOf(substring, startIndex = index + 1, ignoreCase = ignoreCase) - } - } - return spannable -} - -/** - * Returns a new read-only list only of those given elements, that are not empty. - * Applies for CharSequence and descendants. - */ -fun listOfNotEmpty(vararg elements: T): List = elements.filterNot { it.isEmpty() } - -fun List.concat(delimiter: CharSequence? = null): CharSequence { - if (this.isEmpty()) { - return "" - } - - if (this.size == 1) { - return this[0] ?: "" - } - - var spanned = delimiter is Spanned - if (!spanned) { - for (piece in this) { - if (piece is Spanned) { - spanned = true - break - } - } - } - - var first = true - if (spanned) { - val ssb = SpannableStringBuilder() - for (piece in this) { - if (piece == null) - continue - if (!first && delimiter != null) - ssb.append(delimiter) - first = false - ssb.append(piece) - } - return SpannedString(ssb) - } else { - val sb = StringBuilder() - for (piece in this) { - if (piece == null) - continue - if (!first && delimiter != null) - sb.append(delimiter) - first = false - sb.append(piece) - } - return sb.toString() - } -} - -fun TextView.setText(@StringRes resid: Int, vararg formatArgs: Any) { - text = context.getString(resid, *formatArgs) -} - -fun JsonObject(vararg properties: Pair): JsonObject { - return JsonObject().apply { - for (property in properties) { - when (property.second) { - is JsonElement -> add(property.first, property.second as JsonElement?) - is String -> addProperty(property.first, property.second as String?) - is Char -> addProperty(property.first, property.second as Char?) - is Number -> addProperty(property.first, property.second as Number?) - is Boolean -> addProperty(property.first, property.second as Boolean?) - } - } - } -} - -fun JsonArray(vararg properties: Any?): JsonArray { - return JsonArray().apply { - for (property in properties) { - when (property) { - is JsonElement -> add(property as JsonElement?) - is String -> add(property as String?) - is Char -> add(property as Char?) - is Number -> add(property as Number?) - is Boolean -> add(property as Boolean?) - } - } - } -} - -fun Bundle(vararg properties: Pair): Bundle { - return Bundle().apply { - for (property in properties) { - when (property.second) { - is String -> putString(property.first, property.second as String?) - is Char -> putChar(property.first, property.second as Char) - is Int -> putInt(property.first, property.second as Int) - is Long -> putLong(property.first, property.second as Long) - is Float -> putFloat(property.first, property.second as Float) - is Short -> putShort(property.first, property.second as Short) - is Double -> putDouble(property.first, property.second as Double) - is Boolean -> putBoolean(property.first, property.second as Boolean) - } - } - } -} -fun Intent(action: String? = null, vararg properties: Pair): Intent { - return Intent(action).putExtras(Bundle(*properties)) -} -fun Intent(packageContext: Context, cls: Class<*>, vararg properties: Pair): Intent { - return Intent(packageContext, cls).putExtras(Bundle(*properties)) -} - -fun Bundle.toJsonObject(): JsonObject { - val json = JsonObject() - keySet()?.forEach { key -> - get(key)?.let { - when (it) { - is String -> json.addProperty(key, it) - is Char -> json.addProperty(key, it) - is Int -> json.addProperty(key, it) - is Long -> json.addProperty(key, it) - is Float -> json.addProperty(key, it) - is Short -> json.addProperty(key, it) - is Double -> json.addProperty(key, it) - is Boolean -> json.addProperty(key, it) - is Bundle -> json.add(key, it.toJsonObject()) - else -> json.addProperty(key, it.toString()) - } - } - } - return json -} -fun Intent.toJsonObject() = extras?.toJsonObject() - -fun JsonArray?.isNullOrEmpty(): Boolean = (this?.size() ?: 0) == 0 -fun JsonArray.isEmpty(): Boolean = this.size() == 0 -operator fun JsonArray.plusAssign(o: JsonElement) = this.add(o) -operator fun JsonArray.plusAssign(o: String) = this.add(o) -operator fun JsonArray.plusAssign(o: Char) = this.add(o) -operator fun JsonArray.plusAssign(o: Number) = this.add(o) -operator fun JsonArray.plusAssign(o: Boolean) = this.add(o) - -@Suppress("UNCHECKED_CAST") -inline fun T.onClick(crossinline onClickListener: (v: T) -> Unit) { - setOnClickListener { v: View -> - onClickListener(v as T) - } -} - -@Suppress("UNCHECKED_CAST") -inline fun T.onChange(crossinline onChangeListener: (v: T, isChecked: Boolean) -> Unit) { - setOnCheckedChangeListener { buttonView, isChecked -> - onChangeListener(buttonView as T, isChecked) - } -} - -fun LiveData.observeOnce(lifecycleOwner: LifecycleOwner, observer: Observer) { - observe(lifecycleOwner, object : Observer { - override fun onChanged(t: T?) { - observer.onChanged(t) - removeObserver(this) - } - }) -} - -/** - * Convert a value in dp to pixels. - */ -val Int.dp: Int - get() = (this * Resources.getSystem().displayMetrics.density).toInt() -/** - * Convert a value in pixels to dp. - */ -val Int.px: Int - get() = (this / Resources.getSystem().displayMetrics.density).toInt() - -@ColorInt -fun @receiver:AttrRes Int.resolveAttr(context: Context?): Int { - val typedValue = TypedValue() - context?.theme?.resolveAttribute(this, typedValue, true) - return typedValue.data -} -@ColorInt -fun @receiver:ColorRes Int.resolveColor(context: Context): Int { - return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - context.resources.getColor(this, context.theme) - } - else { - context.resources.getColor(this) - } -} -fun @receiver:DrawableRes Int.resolveDrawable(context: Context): Drawable { - return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - context.resources.getDrawable(this, context.theme) - } - else { - context.resources.getDrawable(this) - } -} - -fun View.findParentById(targetId: Int): View? { - if (id == targetId) { - return this - } - val viewParent = this.parent ?: return null - if (viewParent is View) { - return viewParent.findParentById(targetId) - } - return null -} - -fun CoroutineScope.startCoroutineTimer(delayMillis: Long = 0, repeatMillis: Long = 0, action: () -> Unit) = launch { - delay(delayMillis) - if (repeatMillis > 0) { - while (true) { - action() - delay(repeatMillis) - } - } else { - action() - } -} - -operator fun Time?.compareTo(other: Time?): Int { - if (this == null && other == null) - return 0 - if (this == null) - return -1 - if (other == null) - return 1 - return this.compareTo(other) -} - -operator fun StringBuilder.plusAssign(str: String?) { - this.append(str) -} - -fun Context.timeTill(time: Int, delimiter: String = " ", countInSeconds: Boolean = false): String { - val parts = mutableListOf>() - - val hours = time / 3600 - val minutes = (time - hours*3600) / 60 - val seconds = time - minutes*60 - hours*3600 - - if (!countInSeconds) { - var prefixAdded = false - if (hours > 0) { - if (!prefixAdded) parts += R.plurals.time_till_text to hours - prefixAdded = true - parts += R.plurals.time_till_hours to hours - } - if (minutes > 0) { - if (!prefixAdded) parts += R.plurals.time_till_text to minutes - prefixAdded = true - parts += R.plurals.time_till_minutes to minutes - } - if (hours == 0 && minutes < 10) { - if (!prefixAdded) parts += R.plurals.time_till_text to seconds - prefixAdded = true - parts += R.plurals.time_till_seconds to seconds - } - } else { - parts += R.plurals.time_till_text to time - parts += R.plurals.time_till_seconds to time - } - - return parts.joinToString(delimiter) { resources.getQuantityString(it.first, it.second, it.second) } -} - -fun Context.timeLeft(time: Int, delimiter: String = " ", countInSeconds: Boolean = false): String { - val parts = mutableListOf>() - - val hours = time / 3600 - val minutes = (time - hours*3600) / 60 - val seconds = time - minutes*60 - hours*3600 - - if (!countInSeconds) { - var prefixAdded = false - if (hours > 0) { - if (!prefixAdded) parts += R.plurals.time_left_text to hours - prefixAdded = true - parts += R.plurals.time_left_hours to hours - } - if (minutes > 0) { - if (!prefixAdded) parts += R.plurals.time_left_text to minutes - prefixAdded = true - parts += R.plurals.time_left_minutes to minutes - } - if (hours == 0 && minutes < 10) { - if (!prefixAdded) parts += R.plurals.time_left_text to seconds - prefixAdded = true - parts += R.plurals.time_left_seconds to seconds - } - } else { - parts += R.plurals.time_left_text to time - parts += R.plurals.time_left_seconds to time - } - - return parts.joinToString(delimiter) { resources.getQuantityString(it.first, it.second, it.second) } -} - -inline fun Any?.instanceOfOrNull(): T? { - return when (this) { - is T -> this - else -> null - } -} - -fun Drawable.setTintColor(color: Int): Drawable { - colorFilter = PorterDuffColorFilter( - color, - PorterDuff.Mode.SRC_ATOP - ) - return this -} - -inline fun List.ifNotEmpty(block: (List) -> Unit) { - if (!isEmpty()) - block(this) -} - -val String.firstLettersName: String - get() { - var nameShort = "" - this.split(" ").forEach { - if (it.isBlank()) - return@forEach - nameShort += it[0].toLowerCase() - } - return nameShort - } - -val Throwable.stackTraceString: String - get() { - val sw = StringWriter() - printStackTrace(PrintWriter(sw)) - return sw.toString() - } - -inline fun LongSparseArray.filter(predicate: (T) -> Boolean): List { - val destination = ArrayList() - this.forEach { _, element -> if (predicate(element)) destination.add(element) } - return destination -} - -fun CharSequence.replace(oldValue: String, newValue: CharSequence, ignoreCase: Boolean = false): CharSequence = - splitToSequence(oldValue, ignoreCase = ignoreCase).toList().concat(newValue) - -fun Int.toColorStateList(): ColorStateList { - val states = arrayOf( - intArrayOf( android.R.attr.state_enabled ), - intArrayOf(-android.R.attr.state_enabled ), - intArrayOf(-android.R.attr.state_checked ), - intArrayOf( android.R.attr.state_pressed ) - ) - - val colors = intArrayOf( - this, - this, - this, - this - ) - - return ColorStateList(states, colors) -} - -fun SpannableStringBuilder.appendText(text: CharSequence): SpannableStringBuilder { - append(text) - return this -} -fun SpannableStringBuilder.appendSpan(text: CharSequence, what: Any, flags: Int): SpannableStringBuilder { - val start: Int = length - append(text) - setSpan(what, start, length, flags) - return this -} - -fun joinNotNullStrings(delimiter: String = "", vararg parts: String?): String { - var first = true - val sb = StringBuilder() - for (part in parts) { - if (part == null) - continue - if (!first) - sb += delimiter - first = false - sb += part - } - return sb.toString() -} - -fun String.notEmptyOrNull(): String? { - return if (isEmpty()) - null - else - this -} - -fun String.base64Encode(): String { - return encodeToString(toByteArray(), NO_WRAP) -} -fun ByteArray.base64Encode(): String { - return encodeToString(this, NO_WRAP) -} -fun String.base64Decode(): ByteArray { - return Base64.decode(this, Base64.DEFAULT) -} -fun String.base64DecodeToString(): String { - return Base64.decode(this, Base64.DEFAULT).toString(Charset.defaultCharset()) -} - -fun CheckBox.trigger() { isChecked = !isChecked } - -fun Context.plural(@PluralsRes resId: Int, value: Int): String = resources.getQuantityString(resId, value, value) - -fun Context.getNotificationTitle(type: Int): String { - return getString(when (type) { - Notification.TYPE_UPDATE -> R.string.notification_type_update - Notification.TYPE_ERROR -> R.string.notification_type_error - Notification.TYPE_TIMETABLE_CHANGED -> R.string.notification_type_timetable_change - Notification.TYPE_TIMETABLE_LESSON_CHANGE -> R.string.notification_type_timetable_lesson_change - Notification.TYPE_NEW_GRADE -> R.string.notification_type_new_grade - Notification.TYPE_NEW_EVENT -> R.string.notification_type_new_event - Notification.TYPE_NEW_HOMEWORK -> R.string.notification_type_new_homework - Notification.TYPE_NEW_SHARED_EVENT -> R.string.notification_type_new_shared_event - Notification.TYPE_NEW_SHARED_HOMEWORK -> R.string.notification_type_new_shared_homework - Notification.TYPE_REMOVED_SHARED_EVENT -> R.string.notification_type_removed_shared_event - Notification.TYPE_NEW_MESSAGE -> R.string.notification_type_new_message - Notification.TYPE_NEW_NOTICE -> R.string.notification_type_notice - Notification.TYPE_NEW_ATTENDANCE -> R.string.notification_type_attendance - Notification.TYPE_SERVER_MESSAGE -> R.string.notification_type_server_message - Notification.TYPE_LUCKY_NUMBER -> R.string.notification_type_lucky_number - Notification.TYPE_FEEDBACK_MESSAGE -> R.string.notification_type_feedback_message - Notification.TYPE_NEW_ANNOUNCEMENT -> R.string.notification_type_new_announcement - Notification.TYPE_AUTO_ARCHIVING -> R.string.notification_type_auto_archiving - Notification.TYPE_GENERAL -> R.string.notification_type_general - else -> R.string.notification_type_general - }) -} - -fun Cursor?.getString(columnName: String) = this?.getStringOrNull(getColumnIndex(columnName)) -fun Cursor?.getInt(columnName: String) = this?.getIntOrNull(getColumnIndex(columnName)) -fun Cursor?.getLong(columnName: String) = this?.getLongOrNull(getColumnIndex(columnName)) - -fun OkHttpClient.Builder.installHttpsSupport(context: Context) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) { - try { - try { - ProviderInstaller.installIfNeeded(context) - } catch (e: Exception) { - Log.e("OkHttpTLSCompat", "Play Services not found or outdated") - - val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) - trustManagerFactory.init(null as KeyStore?) - - val x509TrustManager = trustManagerFactory.trustManagers.singleOrNull { it is X509TrustManager } as X509TrustManager? - ?: return - - val sc = SSLContext.getInstance("TLSv1.2") - sc.init(null, null, null) - sslSocketFactory(TLSSocketFactory(sc.socketFactory), x509TrustManager) - val cs: ConnectionSpec = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) - .tlsVersions(TlsVersion.TLS_1_0) - .tlsVersions(TlsVersion.TLS_1_1) - .tlsVersions(TlsVersion.TLS_1_2) - .build() - val specs: MutableList = ArrayList() - specs.add(cs) - specs.add(ConnectionSpec.COMPATIBLE_TLS) - specs.add(ConnectionSpec.CLEARTEXT) - connectionSpecs(specs) - } - } catch (exc: Exception) { - Log.e("OkHttpTLSCompat", "Error while setting TLS 1.2", exc) - } - } -} - -fun CharSequence.containsAll(list: List, ignoreCase: Boolean = false): Boolean { - for (i in list) { - if (!contains(i, ignoreCase)) - return false - } - return true -} - -inline fun RadioButton.setOnSelectedListener(crossinline listener: (buttonView: CompoundButton) -> Unit) - = setOnCheckedChangeListener { buttonView, isChecked -> if (isChecked) listener(buttonView) } - -fun Response.toErrorCode() = when (this.code()) { - 400 -> ERROR_REQUEST_HTTP_400 - 401 -> ERROR_REQUEST_HTTP_401 - 403 -> ERROR_REQUEST_HTTP_403 - 404 -> ERROR_REQUEST_HTTP_404 - 405 -> ERROR_REQUEST_HTTP_405 - 410 -> ERROR_REQUEST_HTTP_410 - 424 -> ERROR_REQUEST_HTTP_424 - 500 -> ERROR_REQUEST_HTTP_500 - 503 -> ERROR_REQUEST_HTTP_503 - else -> null -} -fun Throwable.toErrorCode() = when (this) { - is UnknownHostException -> ERROR_REQUEST_FAILURE_HOSTNAME_NOT_FOUND - is SSLException -> ERROR_REQUEST_FAILURE_SSL_ERROR - is SocketTimeoutException -> ERROR_REQUEST_FAILURE_TIMEOUT - is InterruptedIOException, is ConnectException -> ERROR_REQUEST_FAILURE_NO_INTERNET - is SzkolnyApiException -> this.error?.toErrorCode() - else -> null -} -private fun ApiResponse.Error.toErrorCode() = when (this.code) { - else -> ERROR_API_EXCEPTION -} -fun Throwable.toApiError(tag: String) = ApiError.fromThrowable(tag, this) - -inline fun ifNotNull(a: A?, b: B?, code: (A, B) -> R): R? { - if (a != null && b != null) { - return code(a, b) - } - return null -} - -@kotlin.jvm.JvmName("averageOrNullOfInt") -fun Iterable.averageOrNull() = this.average().let { if (it.isNaN()) null else it } -@kotlin.jvm.JvmName("averageOrNullOfFloat") -fun Iterable.averageOrNull() = this.average().let { if (it.isNaN()) null else it } - -fun String.copyToClipboard(context: Context) { - val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager - val clipData = ClipData.newPlainText("Tekst", this) - clipboard.primaryClip = clipData -} - -fun TextView.getTextPosition(range: IntRange): Rect { - val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager - - // Initialize global value - var parentTextViewRect = Rect() - - // Initialize values for the computing of clickedText position - //val completeText = parentTextView.text as SpannableString - val textViewLayout = this.layout - - val startOffsetOfClickedText = range.first//completeText.getSpanStart(clickedText) - val endOffsetOfClickedText = range.last//completeText.getSpanEnd(clickedText) - var startXCoordinatesOfClickedText = textViewLayout.getPrimaryHorizontal(startOffsetOfClickedText) - var endXCoordinatesOfClickedText = textViewLayout.getPrimaryHorizontal(endOffsetOfClickedText) - - // Get the rectangle of the clicked text - val currentLineStartOffset = textViewLayout.getLineForOffset(startOffsetOfClickedText) - val currentLineEndOffset = textViewLayout.getLineForOffset(endOffsetOfClickedText) - val keywordIsInMultiLine = currentLineStartOffset != currentLineEndOffset - textViewLayout.getLineBounds(currentLineStartOffset, parentTextViewRect) - - // Update the rectangle position to his real position on screen - val parentTextViewLocation = intArrayOf(0, 0) - this.getLocationOnScreen(parentTextViewLocation) - - val parentTextViewTopAndBottomOffset = (parentTextViewLocation[1] - this.scrollY + this.compoundPaddingTop) - parentTextViewRect.top += parentTextViewTopAndBottomOffset - parentTextViewRect.bottom += parentTextViewTopAndBottomOffset - - // In the case of multi line text, we have to choose what rectangle take - if (keywordIsInMultiLine) { - val screenHeight = windowManager.defaultDisplay.height - val dyTop = parentTextViewRect.top - val dyBottom = screenHeight - parentTextViewRect.bottom - val onTop = dyTop > dyBottom - - if (onTop) { - endXCoordinatesOfClickedText = textViewLayout.getLineRight(currentLineStartOffset); - } else { - parentTextViewRect = Rect() - textViewLayout.getLineBounds(currentLineEndOffset, parentTextViewRect); - parentTextViewRect.top += parentTextViewTopAndBottomOffset; - parentTextViewRect.bottom += parentTextViewTopAndBottomOffset; - startXCoordinatesOfClickedText = textViewLayout.getLineLeft(currentLineEndOffset); - } - } - - parentTextViewRect.left += ( - parentTextViewLocation[0] + - startXCoordinatesOfClickedText + - this.compoundPaddingLeft - - this.scrollX - ).toInt() - parentTextViewRect.right = ( - parentTextViewRect.left + - endXCoordinatesOfClickedText - - startXCoordinatesOfClickedText - ).toInt() - - return parentTextViewRect -} 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 8f53b625..000f9be6 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/MainActivity.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/MainActivity.kt @@ -10,77 +10,82 @@ import android.graphics.BitmapFactory import android.graphics.drawable.BitmapDrawable import android.os.Build import android.os.Bundle -import android.os.Environment 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 androidx.recyclerview.widget.RecyclerView import com.danimahardhika.cafebar.CafeBar import com.google.android.material.dialog.MaterialAlertDialogBuilder -import com.mikepenz.iconics.IconicsColor +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.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.withIsHiddenInMiniDrawer +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.data.api.ERROR_REQUIRES_USER_ACTION +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.ext.* import pl.szczodrzynski.edziennik.sync.AppManagerDetectedEvent import pl.szczodrzynski.edziennik.sync.SyncWorker import pl.szczodrzynski.edziennik.sync.UpdateWorker -import pl.szczodrzynski.edziennik.ui.dialogs.ServerMessageDialog -import pl.szczodrzynski.edziennik.ui.dialogs.changelog.ChangelogDialog -import pl.szczodrzynski.edziennik.ui.dialogs.event.EventManualDialog -import pl.szczodrzynski.edziennik.ui.dialogs.settings.ProfileRemoveDialog +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.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.base.MainSnackbar -import pl.szczodrzynski.edziennik.ui.modules.behaviour.BehaviourFragment -import pl.szczodrzynski.edziennik.ui.modules.error.ErrorSnackbar -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.MessageFragment -import pl.szczodrzynski.edziennik.ui.modules.messages.MessagesComposeFragment -import pl.szczodrzynski.edziennik.ui.modules.messages.MessagesFragment -import pl.szczodrzynski.edziennik.ui.modules.messages.MessagesListFragment -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.ui.modules.webpush.WebPushFragment -import pl.szczodrzynski.edziennik.utils.SwipeRefreshLayoutNoTouch -import pl.szczodrzynski.edziennik.utils.Themes -import pl.szczodrzynski.edziennik.utils.Utils +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.login.LoginProgressFragment +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.appManagerIntentList +import pl.szczodrzynski.edziennik.utils.managers.AvailabilityManager.Error.Type +import pl.szczodrzynski.edziennik.utils.managers.UserActionManager import pl.szczodrzynski.edziennik.utils.models.Date import pl.szczodrzynski.edziennik.utils.models.NavTarget import pl.szczodrzynski.navlib.* @@ -90,24 +95,19 @@ 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 java.io.File import java.io.IOException import java.util.* import kotlin.coroutines.CoroutineContext import kotlin.math.roundToInt 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 @@ -120,113 +120,162 @@ class MainActivity : AppCompatActivity(), CoroutineScope { 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_outline) - .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_outline) - .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_outline) - .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_outline) - .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_notebook_outline) - .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.Icon.cmd_emoticon_outline) - .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_outline) - .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_bullhorn_outline) - .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_outline) - .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_outline) - .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_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.Icon.cmd_download_outline) - .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, MessageFragment::class).withPopTo(DRAWER_ITEM_MESSAGES) - list += NavTarget(TARGET_MESSAGES_COMPOSE, R.string.menu_message_compose, MessagesComposeFragment::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) - list += NavTarget(DRAWER_ITEM_DEBUG, R.string.menu_debug, DebugFragment::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 } @@ -242,9 +291,14 @@ class MainActivity : AppCompatActivity(), CoroutineScope { 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 } @@ -275,6 +329,8 @@ class MainActivity : AppCompatActivity(), CoroutineScope { setLanguage(it) } + app.buildManager.validateBuild(this) + if (App.profileId == 0) { onProfileListEmptyEvent(ProfileListEmptyEvent()) return @@ -287,6 +343,13 @@ class MainActivity : AppCompatActivity(), CoroutineScope { 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 { @@ -307,8 +370,12 @@ class MainActivity : AppCompatActivity(), CoroutineScope { 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 @@ -328,8 +395,8 @@ class MainActivity : AppCompatActivity(), CoroutineScope { 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() } @@ -351,20 +418,24 @@ class MainActivity : AppCompatActivity(), CoroutineScope { drawerProfileListEmptyListener = { 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 (view != null && profile is ProfileDrawerItem) { - showProfileContextMenu(profile, view) + 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 } } @@ -383,70 +454,94 @@ class MainActivity : AppCompatActivity(), CoroutineScope { savedInstanceState.clear() } - app.db.profileDao().all.observe(this, Observer { profiles -> - drawer.setProfileList(profiles.filter { it.id >= 0 }.toMutableList()) + 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 - }) + } setDrawerItems() handleIntent(intent?.extras) - app.db.metadataDao().unreadCounts.observe(this, Observer { unreadCounters -> + 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 + R.color.md_blue_500, + R.color.md_amber_500, + R.color.md_green_500 ) - isStoragePermissionGranted() - SyncWorker.scheduleNext(app) UpdateWorker.scheduleNext(app) - // APP BACKGROUND - if (app.config.ui.appBackground != null) { - try { - app.config.ui.appBackground?.let { - var bg = it - 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) - } else { - linearLayout.background = BitmapDrawable.createFromPath(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 { + loadProfile(0) } - } catch (e: IOException) { - e.printStackTrace() } } + // APP BACKGROUND + setAppBackground() + // IT'S WINTER MY DUDES val today = Date.getToday() - if ((today.month == 12 || today.month == 1) && app.config.ui.snowfall) { + 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.config.appVersion < BuildConfig.VERSION_CODE) { // force an AppSync after update app.config.sync.lastAppSync = 0L - ChangelogDialog(this) + ChangelogDialog(this).show() if (app.config.appVersion < 170) { //Intent intent = new Intent(this, ChangelogIntroActivity.class); //startActivity(intent); @@ -459,83 +554,95 @@ class MainActivity : AppCompatActivity(), CoroutineScope { 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_outline).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.config.appRateSnackbarTime = 0 - } - .onNegative { cafeBar -> - Toast.makeText(this, "Szkoda, opinie innych pomagają mi rozwijać aplikację.", Toast.LENGTH_LONG).show() - cafeBar.dismiss() - app.config.appRateSnackbarTime = 0 - } - .onNeutral { cafeBar -> - Toast.makeText(this, "OK", Toast.LENGTH_LONG).show() - cafeBar.dismiss() - app.config.appRateSnackbarTime = System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000 - } - .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.Icon.cmd_download_outline) - .withOnClickListener(View.OnClickListener { - bottomSheet.close() - SyncViewListDialog(this, navTargetId) - }), - BottomSheetSeparatorItem(false), - BottomSheetPrimaryItem(false) - .withTitle(R.string.menu_settings) - .withIcon(CommunityMaterial.Icon2.cmd_settings_outline) - .withOnClickListener(View.OnClickListener { loadTarget(DRAWER_ITEM_SETTINGS) }), - BottomSheetPrimaryItem(false) - .withTitle(R.string.menu_feedback) - .withIcon(CommunityMaterial.Icon2.cmd_help_circle_outline) - .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_studio) - .withOnClickListener(View.OnClickListener { loadTarget(DRAWER_ITEM_DEBUG) }) + .withTitle(R.string.menu_debug) + .withIcon(CommunityMaterial.Icon.cmd_android_debug_bridge) + .withOnClickListener { loadTarget(DRAWER_ITEM_DEBUG) } } } - private var profileSettingClickListener = { id: Int, view: View? -> + private var profileSettingClickListener = { id: Int, _: View? -> when (id) { DRAWER_PROFILE_ADD_NEW -> { - startActivityForResult(Intent(this, LoginActivity::class.java), REQUEST_LOGIN_ACTIVITY) + requestHandler.requestLogin() } DRAWER_PROFILE_SYNC_ALL -> { 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) + 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() } - Toast.makeText(this@MainActivity, R.string.main_menu_mark_as_read_success, Toast.LENGTH_SHORT).show() - }} + } else -> { loadTarget(id) } @@ -551,7 +658,62 @@ class MainActivity : AppCompatActivity(), CoroutineScope { |_____/ \__, |_| |_|\___| __/ | |__*/ - 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 fragmentParam = when (navTargetId) { @@ -563,11 +725,27 @@ class MainActivity : AppCompatActivity(), CoroutineScope { else -> null } EdziennikTask.syncProfile( - App.profileId, - listOf(navTargetId to fragmentParam), - arguments = arguments + 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() + } + } + @Subscribe(threadMode = ThreadMode.MAIN) fun onApiTaskStartedEvent(event: ApiTaskStartedEvent) { swipeRefreshLayout.isRefreshing = true @@ -579,6 +757,7 @@ class MainActivity : AppCompatActivity(), CoroutineScope { } } } + @Subscribe(threadMode = ThreadMode.MAIN) fun onProfileListEmptyEvent(event: ProfileListEmptyEvent) { d(TAG, "Profile list is empty. Launch LoginActivity.") @@ -586,6 +765,7 @@ class MainActivity : AppCompatActivity(), CoroutineScope { startActivity(Intent(this, LoginActivity::class.java)) finish() } + @Subscribe(threadMode = ThreadMode.MAIN) fun onApiTaskProgressEvent(event: ApiTaskProgressEvent) { if (event.profileId == App.profileId) { @@ -595,11 +775,16 @@ class MainActivity : AppCompatActivity(), CoroutineScope { subtitle = if (event.progress < 0f) event.progressText ?: "" else - getString(R.string.toolbar_subtitle_syncing_format, event.progress.roundToInt(), event.progressText ?: "") + 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) @@ -611,14 +796,21 @@ class MainActivity : AppCompatActivity(), CoroutineScope { } } } + @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 @@ -627,39 +819,44 @@ class MainActivity : AppCompatActivity(), CoroutineScope { 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) { dialog, which -> - 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() + .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) { dialog, which -> - app.config.sync.dontShowAppManagerDialog = true - } - .setCancelable(false) - .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) + app.userActionManager.execute(this, event, UserActionManager.UserActionCallback()) } private fun fragmentToSyncName(currentFragment: Int): Int { @@ -690,11 +887,12 @@ class MainActivity : AppCompatActivity(), CoroutineScope { handleIntent(intent?.extras) } } - private fun handleIntent(extras: Bundle?) { + + fun handleIntent(extras: Bundle?) { d(TAG, "handleIntent() {") extras?.keySet()?.forEach { key -> - d(TAG, " \"$key\": "+extras.get(key)) + d(TAG, " \"$key\": " + extras.get(key)) } d(TAG, "}") @@ -705,10 +903,10 @@ class MainActivity : AppCompatActivity(), CoroutineScope { val handled = when (extras.getString("action")) { "serverMessage" -> { ServerMessageDialog( - this, - extras.getString("serverMessageTitle") ?: getString(R.string.app_name), - extras.getString("serverMessageText") ?: "" - ) + this, + extras.getString("serverMessageTitle") ?: getString(R.string.app_name), + extras.getString("serverMessageText") ?: "" + ).show() true } "feedbackMessage" -> { @@ -716,20 +914,24 @@ class MainActivity : AppCompatActivity(), CoroutineScope { false } "userActionRequired" -> { - app.userActionManager.execute( - this, - extras.getInt("profileId"), - extras.getInt("type") + val event = UserActionRequiredEvent( + profileId = extras.getInt("profileId"), + type = extras.getEnum("type") ?: return, + params = extras.getBundle("params") ?: return, + errorText = 0, ) + app.userActionManager.execute(this, event, UserActionManager.UserActionCallback()) true } "createManualEvent" -> { - val date = extras.getString("eventDate")?.let { Date.fromY_m_d(it) } ?: Date.getToday() + val date = extras.getString("eventDate") + ?.let { Date.fromY_m_d(it) } + ?: Date.getToday() EventManualDialog( - this, - App.profileId, - defaultDate = date - ) + this, + App.profileId, + defaultDate = date + ).show() true } else -> false @@ -795,9 +997,11 @@ class MainActivity : AppCompatActivity(), CoroutineScope { 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) @@ -814,10 +1018,12 @@ class MainActivity : AppCompatActivity(), CoroutineScope { 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() @@ -826,12 +1032,14 @@ class MainActivity : AppCompatActivity(), CoroutineScope { 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() @@ -846,15 +1054,11 @@ class MainActivity : AppCompatActivity(), CoroutineScope { 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 (!app.config.loginFinished) - finish() - else { - handleIntent(data?.extras) - } - } + requestHandler.handleResult(requestCode, resultCode, data) } /* _ _ _ _ _ @@ -864,52 +1068,168 @@ class MainActivity : AppCompatActivity(), CoroutineScope { | |___| (_) | (_| | (_| | | | | | | | __/ |_| | | | (_) | (_| \__ \ |______\___/ \__,_|\__,_| |_| |_| |_|\___|\__|_| |_|\___/ \__,_|__*/ 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() + + private fun canNavigate(): Boolean = onBeforeNavigate?.invoke() != false + + 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 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) { + + // 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 - loadTarget(drawerSelection, arguments) - return + // skipBeforeNavigate because it's checked above already + loadTarget(drawerSelection, arguments, skipBeforeNavigate = true) + return true } app.profileLoad(id) { - MessagesFragment.pageSelection = -1 - MessagesListFragment.tapPositions = intArrayOf(RecyclerView.NO_POSITION, RecyclerView.NO_POSITION) - MessagesListFragment.topPositions = intArrayOf(RecyclerView.NO_POSITION, RecyclerView.NO_POSITION) - MessagesListFragment.bottomPositions = intArrayOf(RecyclerView.NO_POSITION, RecyclerView.NO_POSITION) - - setDrawerItems() - // 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) + loadProfile(it, drawerSelection, arguments) } + return true } - fun loadTarget(id: Int, arguments: Bundle? = null) { + + 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 - .firstOrNull { 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) { - d("NavDebug", "loadTarget(target = $target, arguments = $arguments)") + 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 @@ -921,27 +1241,27 @@ class MainActivity : AppCompatActivity(), CoroutineScope { navView.bottomBar.fabExtended = false navView.bottomBar.setFabOnClickListener(null) - 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 { + } 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 @@ -957,16 +1277,17 @@ class MainActivity : AppCompatActivity(), CoroutineScope { 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 to arguments) + navBackStack.add(navTarget to navArguments) navTarget = target navArguments = arguments } @@ -981,7 +1302,8 @@ class MainActivity : AppCompatActivity(), CoroutineScope { } } - 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 -> d("NavDebug", " - $index: ${target2.first.fragmentClass?.java?.simpleName}") } @@ -992,39 +1314,46 @@ class MainActivity : AppCompatActivity(), CoroutineScope { // 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 when { navTarget.popToHome -> { - loadTarget(HOME_ID) + loadTarget(HOME_ID, skipBeforeNavigate = skipBeforeNavigate) } navTarget.popTo != null -> { - loadTarget(navTarget.popTo ?: HOME_ID) + loadTarget(navTarget.popTo ?: HOME_ID, skipBeforeNavigate = skipBeforeNavigate) } else -> { navBackStack.last().let { - loadTarget(it.first, it.second) + loadTarget(it.first, it.second, skipBeforeNavigate = skipBeforeNavigate) } } } return true } - fun navigateUp() { - if (!popBackStack()) { + + fun navigateUp(skipBeforeNavigate: Boolean = false) { + if (!popBackStack(skipBeforeNavigate)) { super.onBackPressed() } } @@ -1053,31 +1382,52 @@ class MainActivity : AppCompatActivity(), CoroutineScope { }, 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) - .withIsHiddenInMiniDrawer(!app.config.ui.miniMenuButtons.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 } @@ -1102,7 +1452,11 @@ class MainActivity : AppCompatActivity(), CoroutineScope { 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 @@ -1110,11 +1464,14 @@ class MainActivity : AppCompatActivity(), CoroutineScope { } 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!!) + } } } @@ -1127,32 +1484,13 @@ class MainActivity : AppCompatActivity(), CoroutineScope { 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) { - ProfileRemoveDialog(this, profileId, profile.name?.getText(this) ?: "?") - } - true - } - popupMenu.show() - } - private val targetPopToHomeList = arrayListOf() private var targetHomeId: Int = -1 override fun onBackPressed() { if (!b.navView.onBackPressed()) { if (App.config.ui.openDrawerOnBackPressed && ((navTarget.popTo == null && navTarget.popToHome) - || navTarget.id == DRAWER_ITEM_HOME)) { + || navTarget.id == DRAWER_ITEM_HOME) + ) { b.navView.drawer.toggle() } else { navigateUp() @@ -1161,6 +1499,11 @@ class MainActivity : AppCompatActivity(), CoroutineScope { } fun error(error: ApiError) = errorSnackbar.addError(error).show() - fun snackbar(text: String, actionText: String? = null, onClick: (() -> Unit)? = null) = mainSnackbar.snackbar(text, actionText, onClick) + 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/config/Config.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/Config.kt index bf4f743f..e29d93ad 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/config/Config.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/Config.kt @@ -12,17 +12,14 @@ 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.ConfigMigration -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.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 = 11 + const val DATA_VERSION = 12 } private val job = Job() @@ -75,10 +72,15 @@ class Config(val db: AppDb) : CoroutineScope, AbstractConfig { get() { mPrivacyPolicyAccepted = mPrivacyPolicyAccepted ?: values.get("privacyPolicyAccepted", false); return mPrivacyPolicyAccepted ?: false } set(value) { set("privacyPolicyAccepted", value); mPrivacyPolicyAccepted = value } - private var mDebugMode: Boolean? = null - var debugMode: Boolean - get() { mDebugMode = mDebugMode ?: values.get("debugMode", false); return mDebugMode ?: false } - set(value) { set("debugMode", value); mDebugMode = 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? @@ -105,6 +107,26 @@ class Config(val db: AppDb) : CoroutineScope, AbstractConfig { 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 { diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigSync.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigSync.kt index a6bb68df..387e5cf7 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigSync.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigSync.kt @@ -4,12 +4,19 @@ 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 } @@ -93,6 +100,10 @@ class ConfigSync(private val config: Config) { 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 @@ -106,4 +117,26 @@ class ConfigSync(private val config: Config) { 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/ConfigUI.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigUI.kt index 7b39383e..f36652a1 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigUI.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/ConfigUI.kt @@ -49,6 +49,11 @@ class ConfigUI(private val config: Config) { 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 } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfig.kt b/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfig.kt index 6281225d..6482634c 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfig.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfig.kt @@ -18,7 +18,7 @@ import kotlin.coroutines.CoroutineContext class ProfileConfig(val db: AppDb, val profileId: Int, rawEntries: List) : CoroutineScope, AbstractConfig { companion object { - const val DATA_VERSION = 1 + const val DATA_VERSION = 3 } private val job = Job() @@ -30,6 +30,7 @@ class ProfileConfig(val db: AppDb, val profileId: Int, rawEntries: 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 index 6d8f95e3..2012bc4b 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfigSync.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfigSync.kt @@ -4,12 +4,12 @@ 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 ProfileConfigSync(private val config: ProfileConfig) { private var mNotificationFilter: List? = null var notificationFilter: List - get() { mNotificationFilter = mNotificationFilter ?: config.values.get("notificationFilter", listOf()); return mNotificationFilter ?: listOf() } + 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 index 5ce237a0..a3fb184e 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfigUI.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/ProfileConfigUI.kt @@ -7,7 +7,7 @@ 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.modules.home.HomeCardModel +import pl.szczodrzynski.edziennik.ui.home.HomeCardModel class ProfileConfigUI(private val config: ProfileConfig) { private var mAgendaViewType: Int? = null @@ -15,8 +15,78 @@ class ProfileConfigUI(private val config: ProfileConfig) { 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 } + + private var mTimetableShowAttendance: Boolean? = null + var timetableShowAttendance: Boolean + get() { mTimetableShowAttendance = mTimetableShowAttendance ?: config.values.get("timetableShowAttendance", true); return mTimetableShowAttendance ?: true } + set(value) { config.set("timetableShowAttendance", value); mTimetableShowAttendance = value } + + private var mTimetableShowEvents: Boolean? = null + var timetableShowEvents: Boolean + get() { mTimetableShowEvents = mTimetableShowEvents ?: config.values.get("timetableShowEvents", true); return mTimetableShowEvents ?: true } + set(value) { config.set("timetableShowEvents", value); mTimetableShowEvents = value } + + private var mTimetableTrimHourRange: Boolean? = null + var timetableTrimHourRange: Boolean + get() { mTimetableTrimHourRange = mTimetableTrimHourRange ?: config.values.get("timetableTrimHourRange", false); return mTimetableTrimHourRange ?: false } + set(value) { config.set("timetableTrimHourRange", value); mTimetableTrimHourRange = value } + + private var mTimetableColorSubjectName: Boolean? = null + var timetableColorSubjectName: Boolean + get() { mTimetableColorSubjectName = mTimetableColorSubjectName ?: config.values.get("timetableColorSubjectName", false); return mTimetableColorSubjectName ?: false } + set(value) { config.set("timetableColorSubjectName", value); mTimetableColorSubjectName = value } } 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 index 1188b1a4..94bb87e6 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ConfigExtensions.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ConfigExtensions.kt @@ -49,6 +49,9 @@ fun AbstractConfig.setIntList(key: String, value: List?) { 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 @@ -56,6 +59,9 @@ fun HashMap.get(key: String, default: String?): String? { 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 } 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 index eb04578d..0b0a634e 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ConfigGsonUtils.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ConfigGsonUtils.kt @@ -5,13 +5,14 @@ package pl.szczodrzynski.edziennik.config.utils import com.google.gson.Gson import com.google.gson.JsonParser -import pl.szczodrzynski.edziennik.getInt -import pl.szczodrzynski.edziennik.ui.modules.home.HomeCardModel +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().parse(str) + val json = JsonParser.parseString(str) val list: MutableList = mutableListOf() if (!json.isJsonArray) return list @@ -41,4 +42,4 @@ class ConfigGsonUtils { return list } -} \ No newline at end of file +} 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 index a30c996a..dcb4ab94 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ConfigMigration.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ConfigMigration.kt @@ -7,9 +7,9 @@ package pl.szczodrzynski.edziennik.config.utils import android.content.Context import pl.szczodrzynski.edziennik.App import pl.szczodrzynski.edziennik.BuildConfig -import pl.szczodrzynski.edziennik.HOUR 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 @@ -42,7 +42,7 @@ class ConfigMigration(app: App, config: Config) { MainActivity.DRAWER_ITEM_SETTINGS ) sync.enabled = true - sync.interval = 1*HOUR.toInt() + sync.interval = 1* HOUR.toInt() sync.notifyAboutUpdates = true sync.onlyWifi = false sync.quietHoursEnabled = false @@ -64,11 +64,25 @@ class ConfigMigration(app: App, config: Config) { 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 } 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 index 67861d25..57177899 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ProfileConfigMigration.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/config/utils/ProfileConfigMigration.kt @@ -5,7 +5,10 @@ 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 @@ -14,11 +17,33 @@ class ProfileConfigMigration(config: ProfileConfig) { if (dataVersion < 1) { grades.colorMode = COLOR_MODE_WEIGHTED - grades.dontCountEnabled = false 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 index 2b0b63f2..0d9fe92c 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/ApiService.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/ApiService.kt @@ -22,7 +22,7 @@ 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.toApiError +import pl.szczodrzynski.edziennik.ext.toApiError import pl.szczodrzynski.edziennik.utils.Utils.d import kotlin.math.min import kotlin.math.roundToInt @@ -38,6 +38,9 @@ class ApiService : Service() { 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 } @@ -64,9 +67,6 @@ class ApiService : Service() { private val notification by lazy { EdziennikNotification(app) } - private var lastEventTime = System.currentTimeMillis() - private var taskCancelTries = 0 - /* ______ _ _ _ _ _____ _ _ _ _ | ____| | | (_) (_) | / ____| | | | | | | | |__ __| |_____ ___ _ __ _ __ _| | __ | | __ _| | | |__ __ _ ___| | __ @@ -84,19 +84,21 @@ class ApiService : Service() { runTask() } + override fun onRequiresUserAction(event: UserActionRequiredEvent) { + app.userActionManager.sendToUser(event) + taskRunning?.cancel() + clearTask() + 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() - } + EventBus.getDefault().postSticky(ApiTaskErrorEvent(apiError)) + errorList.add(apiError) + apiError.throwable?.printStackTrace() if (apiError.isCritical) { taskRunning?.cancel() 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 index 4fba7d9b..c29b8698 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Constants.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Constants.kt @@ -24,14 +24,14 @@ 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 = "6XPsKf10LPz1nxgHQLcvZ1KM48DYzlBAhxipaXY8" -const val LIBRUS_REDIRECT_URL = "http://localhost/bar" +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 = "/v2/SynergiaAccounts/fresh/" // + login -const val LIBRUS_ACCOUNTS_URL = "/v2/SynergiaAccounts" +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" @@ -43,7 +43,7 @@ const val LIBRUS_API_TOKEN_URL = "https://api.librus.pl/OAuth/Token" 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 = "49" +const val LIBRUS_API_CLIENT_ID_JST = "59" //const val LIBRUS_API_CLIENT_ID_JST_REFRESH = "42" const val LIBRUS_JST_DEMO_CODE = "68656A21" @@ -56,56 +56,58 @@ const val LIBRUS_SYNERGIA_TOKEN_LOGIN_URL = "https://synergia.librus.pl/loguj/to const val LIBRUS_MESSAGES_URL = "https://wiadomosci.librus.pl/module" const val LIBRUS_SANDBOX_URL = "https://sandbox.librus.pl/index.php?action=" -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 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" -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" +const val LIBRUS_PORTAL_RECAPTCHA_KEY = "6Lf48moUAAAAAB9ClhdvHr46gRWR" +const val LIBRUS_PORTAL_RECAPTCHA_REFERER = "https://portal.librus.pl/rodzina/login" val MOBIDZIENNIK_USER_AGENT = SYSTEM_USER_AGENT -const val VULCAN_API_USER_AGENT = "MobileUserAgent" -const val VULCAN_API_APP_NAME = "VULCAN-Android-ModulUcznia" -const val VULCAN_API_APP_VERSION = "19.4.1.436" -const val VULCAN_API_PASSWORD = "CE75EA598C7743AD9B0B7328DED85B06" -const val VULCAN_API_PASSWORD_FAKELOG = "012345678901234567890123456789AB" -val VULCAN_API_DEVICE_NAME = "Szkolny.eu ${Build.MODEL}" +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 = "22.09.02 (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_API_ENDPOINT_CERTIFICATE = "mobile-api/Uczen.v3.UczenStart/Certyfikat" -const val VULCAN_API_ENDPOINT_STUDENT_LIST = "mobile-api/Uczen.v3.UczenStart/ListaUczniow" -const val VULCAN_API_ENDPOINT_DICTIONARIES = "mobile-api/Uczen.v3.Uczen/Slowniki" -const val VULCAN_API_ENDPOINT_TIMETABLE = "mobile-api/Uczen.v3.Uczen/PlanLekcjiZeZmianami" -const val VULCAN_API_ENDPOINT_GRADES = "mobile-api/Uczen.v3.Uczen/Oceny" -const val VULCAN_API_ENDPOINT_GRADES_PROPOSITIONS = "mobile-api/Uczen.v3.Uczen/OcenyPodsumowanie" -const val VULCAN_API_ENDPOINT_EVENTS = "mobile-api/Uczen.v3.Uczen/Sprawdziany" -const val VULCAN_API_ENDPOINT_HOMEWORK = "mobile-api/Uczen.v3.Uczen/ZadaniaDomowe" -const val VULCAN_API_ENDPOINT_NOTICES = "mobile-api/Uczen.v3.Uczen/UwagiUcznia" -const val VULCAN_API_ENDPOINT_ATTENDANCE = "mobile-api/Uczen.v3.Uczen/Frekwencje" -const val VULCAN_API_ENDPOINT_MESSAGES_RECEIVED = "mobile-api/Uczen.v3.Uczen/WiadomosciOdebrane" -const val VULCAN_API_ENDPOINT_MESSAGES_SENT = "mobile-api/Uczen.v3.Uczen/WiadomosciWyslane" -const val VULCAN_API_ENDPOINT_MESSAGES_CHANGE_STATUS = "mobile-api/Uczen.v3.Uczen/ZmienStatusWiadomosci" -const val VULCAN_API_ENDPOINT_MESSAGES_ADD = "mobile-api/Uczen.v3.Uczen/DodajWiadomosc" -const val VULCAN_API_ENDPOINT_PUSH = "mobile-api/Uczen.v3.Uczen/UstawPushToken" +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_MESSAGEBOX = "api/mobile/messagebox" +const val VULCAN_HEBE_ENDPOINT_MESSAGEBOX_ADDRESSBOOK = "api/mobile/messagebox/addressbook" +const val VULCAN_HEBE_ENDPOINT_MESSAGEBOX_MESSAGES = "api/mobile/messagebox/message" +const val VULCAN_HEBE_ENDPOINT_MESSAGEBOX_STATUS = "api/mobile/messagebox/message/status" +const val VULCAN_HEBE_ENDPOINT_MESSAGEBOX_SEND = "api/mobile/messagebox/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" + +const val USOS_API_OAUTH_REDIRECT_URL = "szkolny://redirect/usos" + +val USOS_API_SCOPES by lazy { listOf( + "offline_access", + "studies", + "grades", + "events", +) } 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 index 8582fc03..6b2b7533 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/EdziennikNotification.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/EdziennikNotification.kt @@ -8,11 +8,13 @@ import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.content.Context -import android.content.Intent 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.ext.pendingIntentFlag +import pl.szczodrzynski.edziennik.receivers.SzkolnyReceiver import kotlin.math.roundToInt @@ -35,16 +37,18 @@ class EdziennikNotification(val app: App) { var serviceClosed = false private fun cancelPendingIntent(taskId: Int): PendingIntent { - val intent = Intent("pl.szczodrzynski.edziennik.SZKOLNY_MAIN") - intent.putExtra("task", "TaskCancelRequest") - intent.putExtra("taskId", taskId) - return PendingIntent.getBroadcast(app, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT) as PendingIntent + val intent = SzkolnyReceiver.getIntent(app, Bundle( + "task" to "TaskCancelRequest", + "taskId" to taskId + )) + return PendingIntent.getBroadcast(app, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or pendingIntentFlag()) as PendingIntent } private val closePendingIntent: PendingIntent get() { - val intent = Intent("pl.szczodrzynski.edziennik.SZKOLNY_MAIN") - intent.putExtra("task", "ServiceCloseRequest") - return PendingIntent.getBroadcast(app, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT) as PendingIntent + val intent = SzkolnyReceiver.getIntent(app, Bundle( + "task" to "ServiceCloseRequest" + )) + return PendingIntent.getBroadcast(app, 0, intent, pendingIntentFlag()) as PendingIntent } private fun errorCountText(): String? { 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 index 1d86abf6..93a7228f 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Errors.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Errors.kt @@ -58,11 +58,31 @@ 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_REQUIRES_USER_ACTION = 114 -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 @@ -126,6 +146,8 @@ 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 @@ -146,46 +168,43 @@ 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 = 309 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_OTHER = 322 -const val ERROR_LOGIN_VULCAN_ONLY_KINDERGARTEN = 330 const val ERROR_LOGIN_VULCAN_NO_PUPILS = 331 -const val ERROR_VULCAN_API_MAINTENANCE = 340 -const val ERROR_VULCAN_API_BAD_REQUEST = 341 -const val ERROR_VULCAN_API_OTHER = 342 +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_IDZIENNIK_WEB_INVALID_LOGIN = 401 -const val ERROR_LOGIN_IDZIENNIK_WEB_INVALID_SCHOOL_NAME = 402 -const val ERROR_LOGIN_IDZIENNIK_WEB_PASSWORD_CHANGE_NEEDED = 403 -const val ERROR_LOGIN_IDZIENNIK_WEB_MAINTENANCE = 404 -const val ERROR_LOGIN_IDZIENNIK_WEB_SERVER_ERROR = 405 -const val ERROR_LOGIN_IDZIENNIK_WEB_OTHER = 410 -const val ERROR_LOGIN_IDZIENNIK_WEB_API_NO_ACCESS = 411 /* {"d":{"__type":"mds.Web.mod_komunikator.WS_mod_wiadomosci+detailWiadomosci","Wiadomosc":{"_recordId":0,"DataNadania":null,"DataOdczytania":null,"Nadawca":null,"ListaOdbiorcow":[],"Tytul":null,"Text":null,"ListaZal":[]},"Bledy":{"__type":"mds.Module.Globalne+sBledy","CzyJestBlad":true,"ListaBledow":["Nie masz dostępu do tych zasobów!"],"ListaKodowBledow":[]},"czyJestWiecej":false}} */ -const val ERROR_LOGIN_IDZIENNIK_WEB_NO_SESSION = 420 -const val ERROR_LOGIN_IDZIENNIK_WEB_NO_AUTH = 421 -const val ERROR_LOGIN_IDZIENNIK_WEB_NO_BEARER = 422 -const val ERROR_IDZIENNIK_WEB_ACCESS_DENIED = 430 -const val ERROR_IDZIENNIK_WEB_OTHER = 431 -const val ERROR_IDZIENNIK_WEB_MAINTENANCE = 432 -const val ERROR_IDZIENNIK_WEB_SERVER_ERROR = 433 -const val ERROR_IDZIENNIK_WEB_PASSWORD_CHANGE_NEEDED = 434 -const val ERROR_LOGIN_IDZIENNIK_FIRST_NO_SCHOOL_YEAR = 440 -const val ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA = 441 -const val ERROR_IDZIENNIK_API_ACCESS_DENIED = 450 -const val ERROR_IDZIENNIK_API_OTHER = 451 -const val ERROR_IDZIENNIK_API_NO_REGISTER = 452 -const val ERROR_IDZIENNIK_WEB_RECIPIENT_LIST_NO_PERMISSION = 453 +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_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_USOS_OAUTH_GOT_DIFFERENT_TOKEN = 702 +const val ERROR_USOS_OAUTH_INCOMPLETE_RESPONSE = 703 +const val ERROR_USOS_NO_STUDENT_PROGRAMMES = 704 +const val ERROR_USOS_API_INCOMPLETE_RESPONSE = 705 +const val ERROR_USOS_API_MISSING_RESPONSE = 706 const val ERROR_TEMPLATE_WEB_OTHER = 801 @@ -196,15 +215,14 @@ 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_VULCAN_API_REQUEST = 907 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_IDZIENNIK_WEB_REQUEST = 912 -const val EXCEPTION_IDZIENNIK_WEB_API_REQUEST = 913 -const val EXCEPTION_IDZIENNIK_API_REQUEST = 914 -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 index 0e75753b..e38b37b5 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Features.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Features.kt @@ -13,8 +13,8 @@ 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.TYPE_RECEIVED -import pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_SENT +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 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 index 66b764cd..9825ea3f 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/LoginMethods.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/LoginMethods.kt @@ -4,43 +4,39 @@ package pl.szczodrzynski.edziennik.data.api -import pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.login.EdudziennikLoginWeb -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.login.IdziennikLoginApi -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.login.IdziennikLoginWeb 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.VulcanLoginApi +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.login.UsosLoginApi +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 +// idziennik [*] // vulcan // mobireg const val SYNERGIA_API_ENABLED = false - - +// the graveyard const val LOGIN_TYPE_IDZIENNIK = 3 +const val LOGIN_TYPE_EDUDZIENNIK = 5 const val LOGIN_TYPE_TEMPLATE = 21 // LOGIN MODES -const val LOGIN_MODE_IDZIENNIK_WEB = 0 - const val LOGIN_MODE_TEMPLATE_WEB = 0 // LOGIN METHODS const val LOGIN_METHOD_NOT_NEEDED = -1 -const val LOGIN_METHOD_IDZIENNIK_WEB = 100 -const val LOGIN_METHOD_IDZIENNIK_API = 200 const val LOGIN_METHOD_TEMPLATE_WEB = 100 const val LOGIN_METHOD_TEMPLATE_API = 200 @@ -97,17 +93,18 @@ val mobidziennikLoginMethods = listOf( 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_API = 500 +const val LOGIN_METHOD_VULCAN_HEBE = 600 val vulcanLoginMethods = listOf( - /*LoginMethod(LOGIN_TYPE_VULCAN, LOGIN_METHOD_VULCAN_WEB_MAIN, VulcanLoginWebMain::class.java) - .withIsPossible { _, _ -> false } + 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) + /*LoginMethod(LOGIN_TYPE_VULCAN, LOGIN_METHOD_VULCAN_WEB_NEW, VulcanLoginWebNew::class.java) .withIsPossible { _, _ -> false } .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_VULCAN_WEB_MAIN }, @@ -115,27 +112,27 @@ val vulcanLoginMethods = listOf( .withIsPossible { _, _ -> false } .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_VULCAN_WEB_MAIN },*/ - LoginMethod(LOGIN_TYPE_VULCAN, LOGIN_METHOD_VULCAN_API, VulcanLoginApi::class.java) - .withIsPossible { _, _ -> true } - .withRequiredLoginMethod { _, loginStore -> - if (loginStore.mode == LOGIN_MODE_VULCAN_WEB) LOGIN_METHOD_VULCAN_WEB_NEW else LOGIN_METHOD_NOT_NEEDED + LoginMethod(LOGIN_TYPE_VULCAN, LOGIN_METHOD_VULCAN_HEBE, VulcanLoginHebe::class.java) + .withIsPossible { _, loginStore -> + loginStore.mode != LOGIN_MODE_VULCAN_API } + .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_NOT_NEEDED } ) -val idziennikLoginMethods = listOf( - LoginMethod(LOGIN_TYPE_IDZIENNIK, LOGIN_METHOD_IDZIENNIK_WEB, IdziennikLoginWeb::class.java) +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 }, - - LoginMethod(LOGIN_TYPE_IDZIENNIK, LOGIN_METHOD_IDZIENNIK_API, IdziennikLoginApi::class.java) - .withIsPossible { _, _ -> true } - .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_IDZIENNIK_WEB } + .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_NOT_NEEDED } ) -const val LOGIN_TYPE_EDUDZIENNIK = 5 -const val LOGIN_METHOD_EDUDZIENNIK_WEB = 100 -val edudziennikLoginMethods = listOf( - LoginMethod(LOGIN_TYPE_EDUDZIENNIK, LOGIN_METHOD_EDUDZIENNIK_WEB, EdudziennikLoginWeb::class.java) +const val LOGIN_TYPE_USOS = 7 +const val LOGIN_MODE_USOS_OAUTH = 0 +const val LOGIN_METHOD_USOS_API = 100 +val usosLoginMethods = listOf( + LoginMethod(LOGIN_TYPE_USOS, LOGIN_METHOD_USOS_API, UsosLoginApi::class.java) .withIsPossible { _, _ -> true } .withRequiredLoginMethod { _, _ -> LOGIN_METHOD_NOT_NEEDED } ) 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 index 633370f5..f3d5a297 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Regexes.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/Regexes.kt @@ -12,6 +12,18 @@ object Regexes { """color: (\w+);?""".toRegex() } + val NOT_DIGITS by lazy { + """[^0-9]""".toRegex() + } + + val HTML_BR by lazy { + """""".toRegex() + } + + val MESSAGE_META by lazy { + """^\[META:([A-z0-9-&=]+)]""".toRegex() + } + val MOBIDZIENNIK_GRADES_SUBJECT_NAME by lazy { @@ -40,21 +52,22 @@ object Regexes { """\(([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) + """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_ATTACHMENT by lazy { - """href="https://.+?\.mobidziennik.pl/.+?&(?:amp;)?zalacznik=([0-9]+)"(?:.+?(.+?)""".toRegex(DOT_MATCHES_ALL) + } val MOBIDZIENNIK_ATTENDANCE_TABLE by lazy { """(.+?)
    """.toRegex(DOT_MATCHES_ALL) } @@ -77,51 +93,64 @@ object Regexes { 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 { - """(.+?) - (.*?).+?.+?\((.+?), .+?(.+?)\)""".toRegex(DOT_MATCHES_ALL) + """(.+?)\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 IDZIENNIK_LOGIN_HIDDEN_FIELDS by lazy { - """""".toRegex(DOT_MATCHES_ALL) + val MOBIDZIENNIK_TIMETABLE_TOP by lazy { + """

    .+?
    """.toRegex(DOT_MATCHES_ALL) } - val IDZIENNIK_LOGIN_ERROR by lazy { - """id="spanErrorMessage">(.*?).+?style="(.+?)".+?title="(.+?)".+?>\s+(.+?)\s+""".toRegex(DOT_MATCHES_ALL) } - val IDZIENNIK_LOGIN_FIRST_ACCOUNT_NAME by lazy { - """Imię i nazwisko:.+?">(.+?)""".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 MOBIDZIENNIK_TIMETABLE_LEFT by lazy { + """
    .+?
    """.toRegex(DOT_MATCHES_ALL) } + val MOBIDZIENNIK_EVENT_CONTENT by lazy { + """

    (.+?) \(wpisał\(a\) (.+?) w dniu ([0-9-]{10})\).+?(.+?)(.*?)""".toRegex() + val LIBRUS_MESSAGE_ID by lazy { + """/wiadomosci/[0-9]+/[0-9]+/([0-9]+?)/""".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_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 { 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 index db8186c9..097ed29e 100644 --- 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 @@ -5,29 +5,36 @@ package pl.szczodrzynski.edziennik.data.api.edziennik import com.google.gson.JsonObject -import pl.szczodrzynski.edziennik.App -import pl.szczodrzynski.edziennik.R +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.idziennik.Idziennik 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.usos.Usos 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.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 +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)) @@ -36,8 +43,9 @@ open class EdziennikTask(override val profileId: Int, val request: Any) : IApiTa 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, message: Message, attachmentId: Long, attachmentName: String) = EdziennikTask(profileId, AttachmentGetRequest(message, attachmentId, attachmentName)) + 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 @@ -58,22 +66,55 @@ open class EdziennikTask(override val profileId: Int, val request: Any) : IApiTa // 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) { - if (profile?.archived == true) { - taskCallback.onError(ApiError(TAG, ERROR_PROFILE_ARCHIVED)) - return + 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_IDZIENNIK -> Idziennik(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) + LOGIN_TYPE_USOS -> Usos(app, profile, loginStore, taskCallback) else -> null } if (edziennikInterface == null) { @@ -92,12 +133,14 @@ open class EdziennikTask(override val profileId: Int, val request: Any) : IApiTa is FirstLoginRequest -> edziennikInterface?.firstLogin() is AnnouncementsReadRequest -> edziennikInterface?.markAllAnnouncementsAsRead() is AnnouncementGetRequest -> edziennikInterface?.getAnnouncement(request.announcement) - is AttachmentGetRequest -> edziennikInterface?.getAttachment(request.message, request.attachmentId, request.attachmentName) + 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() } @@ -113,6 +156,7 @@ open class EdziennikTask(override val profileId: Int, val request: Any) : IApiTa data class MessageSendRequest(val recipients: List, val subject: String, val text: String) class AnnouncementsReadRequest data class AnnouncementGetRequest(val announcement: AnnouncementFull) - data class AttachmentGetRequest(val message: Message, val attachmentId: Long, val attachmentName: String) + 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 deleted file mode 100644 index 40601249..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/DataEdudziennik.kt +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-12-22 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik - -import pl.szczodrzynski.edziennik.* -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.* - -/** - * 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 getSubject(longId: String, name: String): Subject { - val id = longId.crc32() - return subjectList.singleOrNull { it.id == id } ?: run { - val subject = Subject(profileId, id, name, name) - subjectList.put(id, subject) - subject - } - } - - fun getTeacher(firstName: String, lastName: String, longId: String? = null): Teacher { - val name = "$firstName $lastName".fixName() - val id = name.crc32() - return teacherList.singleOrNull { it.id == id }?.also { - if (longId != null && it.loginId == null) it.loginId = longId - } ?: run { - val teacher = Teacher(profileId, id, firstName, lastName, longId) - teacherList.put(id, teacher) - teacher - } - } - - fun getTeacherByFirstLast(nameFirstLast: String, longId: String? = null): Teacher { - val nameParts = nameFirstLast.split(" ") - return getTeacher(nameParts[0], nameParts[1], longId) - } - - fun getTeacherByLastFirst(nameLastFirst: String, longId: String? = null): Teacher { - val nameParts = nameLastFirst.split(" ") - return getTeacher(nameParts[1], nameParts[0], longId) - } - - 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 deleted file mode 100644 index 7bc50511..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/Edudziennik.kt +++ /dev/null @@ -1,133 +0,0 @@ -/* - * 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.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.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.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(message: Message, attachmentId: Long, attachmentName: String) {} - override fun getRecipientList() {} - - 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 deleted file mode 100644 index c3fd17ed..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/EdudziennikFeatures.kt +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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 deleted file mode 100644 index 7eb58d1c..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/EdudziennikData.kt +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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 deleted file mode 100644 index f5adfc5d..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/EdudziennikWeb.kt +++ /dev/null @@ -1,90 +0,0 @@ -/* - * 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 deleted file mode 100644 index 11f048b5..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebAnnouncements.kt +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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.crc32 -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.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, - id, - subject, - null, - startDate, - null, - teacher.id, - longId - ) - - data.announcementIgnoreList.add(announcementObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_ANNOUNCEMENT, - id, - profile.empty, - profile.empty, - addedDate - )) - } - } - - 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 deleted file mode 100644 index 92545117..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebAttendance.kt +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-12-24 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web - -import pl.szczodrzynski.edziennik.crc32 -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.get -import pl.szczodrzynski.edziennik.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() - return@map Triple( - symbol, - name, - when (name?.toLowerCase(Locale.ROOT)) { - "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_CUSTOM - } - ) - } ?: 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().getForDateNow(profileId, date) - val lesson = lessons.firstOrNull { it.lessonNumber == lessonNumber } - - val id = "${date.stringY_m_d}:$lessonNumber:$attendanceSymbol".crc32() - - val (_, name, type) = attendanceTypes.firstOrNull { (symbol, _, _) -> symbol == attendanceSymbol } - ?: return@forEach - - val startTime = data.lessonRanges.singleOrNull { it.lessonNumber == lessonNumber }?.startTime - ?: return@forEach - - val attendanceObject = Attendance( - profileId, - id, - lesson?.displayTeacherId ?: -1, - lesson?.displaySubjectId ?: -1, - profile.currentSemester, - name, - date, - lesson?.displayStartTime ?: startTime, - type - ) - - data.attendanceList.add(attendanceObject) - if(type != Attendance.TYPE_PRESENT) { - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_ATTENDANCE, - id, - profile.empty, - profile.empty, - System.currentTimeMillis() - )) - } - } - - 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 deleted file mode 100644 index cf846fce..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebEvents.kt +++ /dev/null @@ -1,72 +0,0 @@ -/* - * 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.crc32 -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.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, - id, - date, - null, - title, - -1, - Event.TYPE_CLASS_EVENT, - false, - -1, - -1, - data.teamClass?.id ?: -1 - ) - - data.eventList.add(eventObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_EVENT, - id, - profile.empty, - profile.empty, - System.currentTimeMillis() - )) - } - - 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 deleted file mode 100644 index 8eb7d04e..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebExams.kt +++ /dev/null @@ -1,92 +0,0 @@ -/* - * 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.crc32 -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.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, 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().getForDateNow(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, - id, - date, - startTime, - topic, - -1, - eventType.id, - false, - -1, - subject.id, - data.teamClass?.id ?: -1 - ) - - data.eventList.add(eventObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_EVENT, - id, - profile.empty, - profile.empty, - System.currentTimeMillis() - )) - } - - 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 deleted file mode 100644 index 5d915e64..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebGetAnnouncement.kt +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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.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/EdudziennikWebGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebGrades.kt deleted file mode 100644 index 50557333..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebGrades.kt +++ /dev/null @@ -1,232 +0,0 @@ -/* - * 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.colorFromCssName -import pl.szczodrzynski.edziennik.crc32 -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.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, 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) - } - } 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 - ) - - data.gradeList.add(gradeObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_GRADE, - id, - profile.empty, - profile.empty, - addedDate - )) - } - - 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, - System.currentTimeMillis() - )) - } - - 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, - System.currentTimeMillis() - )) - } - } - - 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 deleted file mode 100644 index 9d9a336a..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebHomework.kt +++ /dev/null @@ -1,86 +0,0 @@ -/* - * 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.crc32 -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.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) - val id = EDUDZIENNIK_HOMEWORK_ID.find(dateElement.attr("href"))?.get(1)?.crc32() - ?: return@forEach - 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, subjectName) - - val lessons = data.app.db.timetableDao().getForDateNow(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() - - val eventObject = Event( - profileId, - id, - date, - startTime, - topic, - -1, - Event.TYPE_HOMEWORK, - false, - teacher.id, - subject.id, - data.teamClass?.id ?: -1 - ) - - data.eventList.add(eventObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_HOMEWORK, - id, - profile.empty, - profile.empty, - System.currentTimeMillis() - )) - } - } - - 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 deleted file mode 100644 index 70c6849a..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebLuckyNumber.kt +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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, - Date.getToday(), - luckyNumber - ) - - data.luckyNumberList.add(luckyNumberObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_LUCKY_NUMBER, - luckyNumberObject.date.value.toLong(), - true, - profile.empty, - System.currentTimeMillis() - )) - } - - 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 deleted file mode 100644 index a111ef79..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebNotes.kt +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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.crc32 -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.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) - 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, - id, - description, - profile.currentSemester, - Notice.TYPE_NEUTRAL, - teacher.id - ) - - data.noticeList.add(noticeObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_NOTICE, - id, - profile.empty, - profile.empty, - addedDate - )) - } - - 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 deleted file mode 100644 index 66cb7a59..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebStart.kt +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-12-23 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web - -import pl.szczodrzynski.edziennik.MONTH -import pl.szczodrzynski.edziennik.crc32 -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.firstLettersName -import pl.szczodrzynski.edziennik.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, 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 deleted file mode 100644 index d2f3ba15..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebTeachers.kt +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-12-25 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.data.web - -import pl.szczodrzynski.edziennik.MONTH -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.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 deleted file mode 100644 index 3a31e208..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/data/web/EdudziennikWebTimetable.kt +++ /dev/null @@ -1,150 +0,0 @@ -/* - * 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.get -import pl.szczodrzynski.edziennik.getString -import pl.szczodrzynski.edziennik.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.")) { - 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, 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, - System.currentTimeMillis() - )) - } - } - } - } - - 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 deleted file mode 100644 index e47c7842..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/firstlogin/EdudziennikFirstLogin.kt +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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.fixName -import pl.szczodrzynski.edziennik.get -import pl.szczodrzynski.edziennik.getShortName -import pl.szczodrzynski.edziennik.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().post(FirstLoginFinishedEvent(profileList, data.loginStore)) - onSuccess() - } - } - } -} 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 deleted file mode 100644 index 6b1615a2..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/login/EdudziennikLoginWeb.kt +++ /dev/null @@ -1,97 +0,0 @@ -/* - * 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.getUnixDate -import pl.szczodrzynski.edziennik.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/idziennik/DataIdziennik.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/DataIdziennik.kt deleted file mode 100644 index 3e974539..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/DataIdziennik.kt +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-25. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik - -import androidx.core.util.set -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_IDZIENNIK_API -import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_IDZIENNIK_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.data.db.entity.Subject -import pl.szczodrzynski.edziennik.data.db.entity.Teacher - -class DataIdziennik(app: App, profile: Profile?, loginStore: LoginStore) : Data(app, profile, loginStore) { - - fun isWebLoginValid() = loginExpiryTime-30 > currentTimeUnix() && webSessionId.isNotNullNorEmpty() && webAuth.isNotNullNorEmpty() - fun isApiLoginValid() = apiExpiryTime-30 > currentTimeUnix() && apiBearer.isNotNullNorEmpty() - - override fun satisfyLoginMethods() { - loginMethods.clear() - if (isWebLoginValid()) { - loginMethods += LOGIN_METHOD_IDZIENNIK_WEB - app.cookieJar.set("iuczniowie.progman.pl", "ASP.NET_SessionId_iDziennik", webSessionId) - app.cookieJar.set("iuczniowie.progman.pl", ".ASPXAUTH", webAuth) - } - if (isApiLoginValid()) - loginMethods += LOGIN_METHOD_IDZIENNIK_API - } - - override fun generateUserCode() = "$webSchoolName:$webUsername:$registerId" - - private var mLoginExpiryTime: Long? = null - var loginExpiryTime: Long - get() { mLoginExpiryTime = mLoginExpiryTime ?: loginStore.getLoginData("loginExpiryTime", 0L); return mLoginExpiryTime ?: 0L } - set(value) { loginStore.putLoginData("loginExpiryTime", value); mLoginExpiryTime = value } - - private var mApiExpiryTime: Long? = null - var apiExpiryTime: Long - get() { mApiExpiryTime = mApiExpiryTime ?: loginStore.getLoginData("apiExpiryTime", 0L); return mApiExpiryTime ?: 0L } - set(value) { loginStore.putLoginData("apiExpiryTime", value); mApiExpiryTime = value } - - /* __ __ _ - \ \ / / | | - \ \ /\ / /__| |__ - \ \/ \/ / _ \ '_ \ - \ /\ / __/ |_) | - \/ \/ \___|_._*/ - private var mWebSchoolName: String? = null - var webSchoolName: String? - get() { mWebSchoolName = mWebSchoolName ?: loginStore.getLoginData("schoolName", null); return mWebSchoolName } - set(value) { loginStore.putLoginData("schoolName", value); mWebSchoolName = value } - private var mWebUsername: String? = null - var webUsername: String? - get() { mWebUsername = mWebUsername ?: loginStore.getLoginData("username", null); return mWebUsername } - set(value) { loginStore.putLoginData("username", value); mWebUsername = value } - private var mWebPassword: String? = null - var webPassword: String? - get() { mWebPassword = mWebPassword ?: loginStore.getLoginData("password", null); return mWebPassword } - set(value) { loginStore.putLoginData("password", value); mWebPassword = 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 mWebAuth: String? = null - var webAuth: String? - get() { mWebAuth = mWebAuth ?: loginStore.getLoginData("webAuth", null); return mWebAuth } - set(value) { loginStore.putLoginData("webAuth", value); mWebAuth = value } - - private var mWebSelectedRegister: Int? = null - var webSelectedRegister: Int - get() { mWebSelectedRegister = mWebSelectedRegister ?: loginStore.getLoginData("webSelectedRegister", 0); return mWebSelectedRegister ?: 0 } - set(value) { loginStore.putLoginData("webSelectedRegister", value); mWebSelectedRegister = value } - - /* _ - /\ (_) - / \ _ __ _ - / /\ \ | '_ \| | - / ____ \| |_) | | - /_/ \_\ .__/|_| - | | - |*/ - private var mApiBearer: String? = null - var apiBearer: String? - get() { mApiBearer = mApiBearer ?: loginStore.getLoginData("apiBearer", null); return mApiBearer } - set(value) { loginStore.putLoginData("apiBearer", value); mApiBearer = 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 mRegisterId: Int? = null - var registerId: Int - get() { mRegisterId = mRegisterId ?: profile?.getStudentData("registerId", 0); return mRegisterId ?: 0 } - set(value) { profile?.putStudentData("registerId", value) ?: return; mRegisterId = value } - - private var mSchoolYearId: Int? = null - var schoolYearId: Int - get() { mSchoolYearId = mSchoolYearId ?: profile?.getStudentData("schoolYearId", 0); return mSchoolYearId ?: 0 } - set(value) { profile?.putStudentData("schoolYearId", value) ?: return; mSchoolYearId = value } - - - - /* _ _ _ _ _ - | | | | | (_) | - | | | | |_ _| |___ - | | | | __| | / __| - | |__| | |_| | \__ \ - \____/ \__|_|_|__*/ - fun getSubject(name: String, id: Long?, shortName: String): Subject { - var subject = if (id == null) - subjectList.singleOrNull { it.longName == name } - else - subjectList.singleOrNull { it.id == id } - - if (subject == null) { - subject = Subject(profileId, id - ?: name.crc16().toLong(), name, shortName) - subjectList[subject.id] = subject - } - return subject - } - - fun getTeacher(firstName: String, lastName: String): Teacher { - val teacher = teacherList.singleOrNull { it.fullName == "$firstName $lastName" } - return validateTeacher(teacher, firstName, lastName) - } - - fun getTeacher(firstNameChar: Char, lastName: String): Teacher { - val teacher = teacherList.singleOrNull { it.shortName == "$firstNameChar.$lastName" } - return validateTeacher(teacher, firstNameChar.toString(), lastName) - } - - fun getTeacherByLastFirst(nameLastFirst: String): Teacher { - val nameParts = nameLastFirst.split(" ") - return if (nameParts.size == 1) getTeacher(nameParts[0], "") else getTeacher(nameParts[1], nameParts[0]) - } - - fun getTeacherByFirstLast(nameFirstLast: String): Teacher { - val nameParts = nameFirstLast.split(" ") - return if (nameParts.size == 1) getTeacher(nameParts[0], "") else getTeacher(nameParts[0], nameParts[1]) - } - - fun getTeacherByFDotLast(nameFDotLast: String): Teacher { - val nameParts = nameFDotLast.split(".") - return if (nameParts.size == 1) getTeacher(nameParts[0], "") else getTeacher(nameParts[0][0], nameParts[1]) - } - - fun getTeacherByFDotSpaceLast(nameFDotSpaceLast: String): Teacher { - val nameParts = nameFDotSpaceLast.split(".") - return if (nameParts.size == 1) getTeacher(nameParts[0], "") else getTeacher(nameParts[0][0], nameParts[1]) - } - - private fun validateTeacher(teacher: Teacher?, firstName: String, lastName: String): Teacher { - (teacher ?: Teacher(profileId, -1, firstName, lastName).apply { - id = shortName.crc16().toLong() - teacherList[id] = this - }).apply { - if (firstName.length > 1) - name = firstName - surname = lastName - return this - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/Idziennik.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/Idziennik.kt deleted file mode 100644 index be0d0d1c..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/Idziennik.kt +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-25. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik - -import com.google.gson.JsonObject -import pl.szczodrzynski.edziennik.App -import pl.szczodrzynski.edziennik.data.api.* -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikData -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web.IdziennikWebGetAttachment -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web.IdziennikWebGetMessage -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web.IdziennikWebGetRecipientList -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web.IdziennikWebSendMessage -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.firstlogin.IdziennikFirstLogin -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.login.IdziennikLogin -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.MessageFull -import pl.szczodrzynski.edziennik.utils.Utils.d - -class Idziennik(val app: App, val profile: Profile?, val loginStore: LoginStore, val callback: EdziennikCallback) : EdziennikInterface { - companion object { - private const val TAG = "Idziennik" - } - - val internalErrorList = mutableListOf() - val data: DataIdziennik - private var afterLogin: (() -> Unit)? = null - - init { - data = DataIdziennik(app, profile, loginStore).apply { - callback = wrapCallback(this@Idziennik.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(idziennikLoginMethods, IdziennikFeatures, 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(idziennikLoginMethods, it) } - afterLogin?.let { this.afterLogin = it } - IdziennikLogin(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() ?: IdziennikData(data) { - completed() - } - } - - override fun getMessage(message: MessageFull) { - login(LOGIN_METHOD_IDZIENNIK_WEB) { - IdziennikWebGetMessage(data, message) { - completed() - } - } - } - - override fun sendMessage(recipients: List, subject: String, text: String) { - login(LOGIN_METHOD_IDZIENNIK_API) { - IdziennikWebSendMessage(data, recipients, subject, text) { - completed() - } - } - } - - override fun markAllAnnouncementsAsRead() {} - override fun getAnnouncement(announcement: AnnouncementFull) {} - - override fun getAttachment(message: Message, attachmentId: Long, attachmentName: String) { - login(LOGIN_METHOD_IDZIENNIK_WEB) { - IdziennikWebGetAttachment(data, message, attachmentId, attachmentName) { - completed() - } - } - } - - override fun getRecipientList() { - login(LOGIN_METHOD_IDZIENNIK_WEB) { - IdziennikWebGetRecipientList(data) { - completed() - } - } - } - - override fun firstLogin() { IdziennikFirstLogin(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_LOGIN_IDZIENNIK_WEB_NO_SESSION, - ERROR_LOGIN_IDZIENNIK_WEB_NO_AUTH, - ERROR_LOGIN_IDZIENNIK_WEB_NO_BEARER, - ERROR_IDZIENNIK_WEB_ACCESS_DENIED, - ERROR_IDZIENNIK_API_ACCESS_DENIED -> { - data.loginMethods.remove(LOGIN_METHOD_IDZIENNIK_WEB) - data.prepareFor(idziennikLoginMethods, LOGIN_METHOD_IDZIENNIK_WEB) - data.loginExpiryTime = 0 - login() - } - ERROR_IDZIENNIK_API_NO_REGISTER -> { - data() - } - else -> callback.onError(apiError) - } - } - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/IdziennikFeatures.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/IdziennikFeatures.kt deleted file mode 100644 index 02aaabb2..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/IdziennikFeatures.kt +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-25. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik - -import pl.szczodrzynski.edziennik.data.api.* -import pl.szczodrzynski.edziennik.data.api.models.Feature - -const val ENDPOINT_IDZIENNIK_WEB_TIMETABLE = 1030 -const val ENDPOINT_IDZIENNIK_WEB_GRADES = 1040 -const val ENDPOINT_IDZIENNIK_WEB_PROPOSED_GRADES = 1050 -const val ENDPOINT_IDZIENNIK_WEB_EXAMS = 1060 -const val ENDPOINT_IDZIENNIK_WEB_HOMEWORK = 1061 -const val ENDPOINT_IDZIENNIK_WEB_NOTICES = 1070 -const val ENDPOINT_IDZIENNIK_WEB_ANNOUNCEMENTS = 1080 -const val ENDPOINT_IDZIENNIK_WEB_ATTENDANCE = 1090 -const val ENDPOINT_IDZIENNIK_WEB_MESSAGES_INBOX = 1110 -const val ENDPOINT_IDZIENNIK_WEB_MESSAGES_SENT = 1120 -const val ENDPOINT_IDZIENNIK_API_CURRENT_REGISTER = 2010 -const val ENDPOINT_IDZIENNIK_API_MESSAGES_INBOX = 2110 -const val ENDPOINT_IDZIENNIK_API_MESSAGES_SENT = 2120 - -val IdziennikFeatures = listOf( - Feature(LOGIN_TYPE_IDZIENNIK, FEATURE_TIMETABLE, listOf( - ENDPOINT_IDZIENNIK_WEB_TIMETABLE to LOGIN_METHOD_IDZIENNIK_WEB - ), listOf(LOGIN_METHOD_IDZIENNIK_WEB)), - - Feature(LOGIN_TYPE_IDZIENNIK, FEATURE_GRADES, listOf( - ENDPOINT_IDZIENNIK_WEB_GRADES to LOGIN_METHOD_IDZIENNIK_WEB, - ENDPOINT_IDZIENNIK_WEB_PROPOSED_GRADES to LOGIN_METHOD_IDZIENNIK_WEB - ), listOf(LOGIN_METHOD_IDZIENNIK_WEB)), - - Feature(LOGIN_TYPE_IDZIENNIK, FEATURE_AGENDA, listOf( - ENDPOINT_IDZIENNIK_WEB_EXAMS to LOGIN_METHOD_IDZIENNIK_WEB - ), listOf(LOGIN_METHOD_IDZIENNIK_WEB)), - - Feature(LOGIN_TYPE_IDZIENNIK, FEATURE_HOMEWORK, listOf( - ENDPOINT_IDZIENNIK_WEB_HOMEWORK to LOGIN_METHOD_IDZIENNIK_WEB - ), listOf(LOGIN_METHOD_IDZIENNIK_WEB)), - - Feature(LOGIN_TYPE_IDZIENNIK, FEATURE_BEHAVIOUR, listOf( - ENDPOINT_IDZIENNIK_WEB_NOTICES to LOGIN_METHOD_IDZIENNIK_WEB - ), listOf(LOGIN_METHOD_IDZIENNIK_WEB)), - - Feature(LOGIN_TYPE_IDZIENNIK, FEATURE_ATTENDANCE, listOf( - ENDPOINT_IDZIENNIK_WEB_ATTENDANCE to LOGIN_METHOD_IDZIENNIK_WEB - ), listOf(LOGIN_METHOD_IDZIENNIK_WEB)), - - Feature(LOGIN_TYPE_IDZIENNIK, FEATURE_ANNOUNCEMENTS, listOf( - ENDPOINT_IDZIENNIK_WEB_ANNOUNCEMENTS to LOGIN_METHOD_IDZIENNIK_WEB - ), listOf(LOGIN_METHOD_IDZIENNIK_WEB)), - - /*Feature(LOGIN_TYPE_IDZIENNIK, FEATURE_MESSAGES_INBOX, listOf( - ENDPOINT_IDZIENNIK_WEB_MESSAGES_INBOX to LOGIN_METHOD_IDZIENNIK_WEB - ), listOf(LOGIN_METHOD_IDZIENNIK_WEB)).withPriority(2), - Feature(LOGIN_TYPE_IDZIENNIK, FEATURE_MESSAGES_SENT, listOf( - ENDPOINT_IDZIENNIK_WEB_MESSAGES_SENT to LOGIN_METHOD_IDZIENNIK_WEB - ), listOf(LOGIN_METHOD_IDZIENNIK_WEB)).withPriority(2),*/ - - Feature(LOGIN_TYPE_IDZIENNIK, FEATURE_MESSAGES_INBOX, listOf( - ENDPOINT_IDZIENNIK_API_MESSAGES_INBOX to LOGIN_METHOD_IDZIENNIK_API - ), listOf(LOGIN_METHOD_IDZIENNIK_API)), - Feature(LOGIN_TYPE_IDZIENNIK, FEATURE_MESSAGES_SENT, listOf( - ENDPOINT_IDZIENNIK_API_MESSAGES_SENT to LOGIN_METHOD_IDZIENNIK_API - ), listOf(LOGIN_METHOD_IDZIENNIK_API)), - - Feature(LOGIN_TYPE_IDZIENNIK, FEATURE_LUCKY_NUMBER, listOf( - ENDPOINT_IDZIENNIK_API_CURRENT_REGISTER to LOGIN_METHOD_IDZIENNIK_API - ), listOf(LOGIN_METHOD_IDZIENNIK_API)) -) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/IdziennikApi.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/IdziennikApi.kt deleted file mode 100644 index 8da75603..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/IdziennikApi.kt +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-29. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data - -import com.google.gson.JsonArray -import com.google.gson.JsonElement -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.szczodrzynski.edziennik.data.api.* -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.models.ApiError -import pl.szczodrzynski.edziennik.getString -import pl.szczodrzynski.edziennik.utils.Utils -import java.net.HttpURLConnection - -open class IdziennikApi(open val data: DataIdziennik, open val lastSync: Long?) { - companion object { - const val TAG = "IdziennikApi" - } - - val profileId - get() = data.profile?.id ?: -1 - - val profile - get() = data.profile - - fun apiGet(tag: String, endpointTemplate: String, method: Int = GET, parameters: Map = emptyMap(), onSuccess: (json: JsonElement) -> Unit) { - val endpoint = endpointTemplate.replace("\$STUDENT_ID", data.studentId ?: "") - Utils.d(tag, "Request: Idziennik/API - $IDZIENNIK_API_URL/$endpoint") - - val callback = object : TextCallbackHandler() { - override fun onSuccess(text: String?, response: Response?) { - if (text == null) { - data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) - .withResponse(response)) - return - } - - val json = try { - JsonParser().parse(text) - } catch (_: Exception) { null } - - var error: String? = null - if (json == null) { - error = text - } - else if (json is JsonObject) { - error = if (response?.code() == 200) null else - json.getString("message") ?: json.toString() - } - error?.let { code -> - when (code) { - "Uczeń nie posiada aktywnej pozycji w dzienniku" -> ERROR_IDZIENNIK_API_NO_REGISTER - "Authorization has been denied for this request." -> ERROR_IDZIENNIK_API_ACCESS_DENIED - else -> ERROR_IDZIENNIK_API_OTHER - }.let { errorCode -> - data.error(ApiError(tag, errorCode) - .withApiResponse(text) - .withResponse(response)) - return - } - } - - try { - onSuccess(json!!) - } catch (e: Exception) { - data.error(ApiError(tag, EXCEPTION_IDZIENNIK_API_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("$IDZIENNIK_API_URL/$endpoint") - .userAgent(IDZIENNIK_API_USER_AGENT) - .addHeader("Authorization", "Bearer ${data.apiBearer}") - .apply { - when (method) { - GET -> get() - POST -> { - postJson() - val json = JsonObject() - parameters.map { (name, value) -> - when (value) { - is JsonObject -> json.add(name, value) - is JsonArray -> json.add(name, value) - is String -> json.addProperty(name, value) - is Int -> json.addProperty(name, value) - is Long -> json.addProperty(name, value) - is Float -> json.addProperty(name, value) - is Char -> json.addProperty(name, value) - } - } - setJsonBody(json) - } - } - } - .allowErrorCode(HttpURLConnection.HTTP_BAD_REQUEST) - .allowErrorCode(HttpURLConnection.HTTP_UNAUTHORIZED) - .allowErrorCode(HttpURLConnection.HTTP_INTERNAL_ERROR) - .callback(callback) - .build() - .enqueue() - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/IdziennikData.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/IdziennikData.kt deleted file mode 100644 index 8acb04cb..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/IdziennikData.kt +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-25. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data - -import pl.szczodrzynski.edziennik.R -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.* -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.api.IdziennikApiCurrentRegister -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.api.IdziennikApiMessagesInbox -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.api.IdziennikApiMessagesSent -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web.* -import pl.szczodrzynski.edziennik.utils.Utils - -class IdziennikData(val data: DataIdziennik, val onSuccess: () -> Unit) { - companion object { - private const val TAG = "IdziennikData" - } - - 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_IDZIENNIK_WEB_TIMETABLE -> { - data.startProgress(R.string.edziennik_progress_endpoint_timetable) - IdziennikWebTimetable(data, lastSync, onSuccess) - } - ENDPOINT_IDZIENNIK_WEB_GRADES -> { - data.startProgress(R.string.edziennik_progress_endpoint_grades) - IdziennikWebGrades(data, lastSync, onSuccess) - } - ENDPOINT_IDZIENNIK_WEB_PROPOSED_GRADES -> { - data.startProgress(R.string.edziennik_progress_endpoint_proposed_grades) - IdziennikWebProposedGrades(data, lastSync, onSuccess) - } - ENDPOINT_IDZIENNIK_WEB_EXAMS -> { - data.startProgress(R.string.edziennik_progress_endpoint_exams) - IdziennikWebExams(data, lastSync, onSuccess) - } - ENDPOINT_IDZIENNIK_WEB_HOMEWORK -> { - data.startProgress(R.string.edziennik_progress_endpoint_homework) - IdziennikWebHomework(data, lastSync, onSuccess) - } - ENDPOINT_IDZIENNIK_WEB_NOTICES -> { - data.startProgress(R.string.edziennik_progress_endpoint_notices) - IdziennikWebNotices(data, lastSync, onSuccess) - } - ENDPOINT_IDZIENNIK_WEB_ANNOUNCEMENTS -> { - data.startProgress(R.string.edziennik_progress_endpoint_announcements) - IdziennikWebAnnouncements(data, lastSync, onSuccess) - } - ENDPOINT_IDZIENNIK_WEB_ATTENDANCE -> { - data.startProgress(R.string.edziennik_progress_endpoint_attendance) - IdziennikWebAttendance(data, lastSync, onSuccess) - } - ENDPOINT_IDZIENNIK_API_CURRENT_REGISTER -> { - data.startProgress(R.string.edziennik_progress_endpoint_lucky_number) - IdziennikApiCurrentRegister(data, lastSync, onSuccess) - } - ENDPOINT_IDZIENNIK_API_MESSAGES_INBOX -> { - data.startProgress(R.string.edziennik_progress_endpoint_messages_inbox) - IdziennikApiMessagesInbox(data, lastSync, onSuccess) - } - ENDPOINT_IDZIENNIK_API_MESSAGES_SENT -> { - data.startProgress(R.string.edziennik_progress_endpoint_messages_outbox) - IdziennikApiMessagesSent(data, lastSync, onSuccess) - } - else -> onSuccess(endpointId) - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/IdziennikWeb.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/IdziennikWeb.kt deleted file mode 100644 index 907e1f50..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/IdziennikWeb.kt +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-25. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data - -import com.google.gson.JsonArray -import com.google.gson.JsonObject -import im.wangchao.mhttp.Request -import im.wangchao.mhttp.Response -import im.wangchao.mhttp.callback.FileCallbackHandler -import im.wangchao.mhttp.callback.JsonCallbackHandler -import im.wangchao.mhttp.callback.TextCallbackHandler -import pl.szczodrzynski.edziennik.data.api.* -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web.IdziennikWebSwitchRegister -import pl.szczodrzynski.edziennik.data.api.models.ApiError -import pl.szczodrzynski.edziennik.utils.Utils.d -import java.io.File -import java.net.HttpURLConnection.HTTP_INTERNAL_ERROR -import java.net.HttpURLConnection.HTTP_UNAUTHORIZED - -open class IdziennikWeb(open val data: DataIdziennik, open val lastSync: Long?) { - companion object { - const val TAG = "IdziennikWeb" - } - - val profileId - get() = data.profile?.id ?: -1 - - val profile - get() = data.profile - - fun webApiGet(tag: String, endpoint: String, parameters: Map = emptyMap(), onSuccess: (json: JsonObject) -> Unit) { - d(tag, "Request: Idziennik/Web/API - $IDZIENNIK_WEB_URL/$endpoint") - - val callback = object : JsonCallbackHandler() { - override fun onSuccess(json: JsonObject?, response: Response?) { - if (json == null && response?.parserErrorBody == null) { - data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) - .withResponse(response)) - return - } - - if (response?.code() == HTTP_INTERNAL_ERROR && endpoint == IDZIENNIK_WEB_GET_RECIPIENT_LIST) { - data.error(ApiError(tag, ERROR_IDZIENNIK_WEB_RECIPIENT_LIST_NO_PERMISSION) - .withResponse(response) - .withApiResponse(json)) - return - } - - if (response?.code() == HTTP_INTERNAL_ERROR && endpoint == IDZIENNIK_WEB_GRADES) { - // special override for accounts where displaying grades - // for another student requires switching it manually - if (data.registerId != data.webSelectedRegister) { - IdziennikWebSwitchRegister(data, data.registerId) { - webApiGet(tag, endpoint, parameters, onSuccess) - } - return - } - } - - when { - response?.code() == HTTP_UNAUTHORIZED -> ERROR_IDZIENNIK_WEB_ACCESS_DENIED - response?.code() == HTTP_INTERNAL_ERROR -> ERROR_IDZIENNIK_WEB_SERVER_ERROR - response?.parserErrorBody != null -> when { - response.parserErrorBody.contains("Identyfikator zgłoszenia") -> ERROR_IDZIENNIK_WEB_SERVER_ERROR - response.parserErrorBody.contains("Hasło dostępu do systemu wygasło") -> ERROR_IDZIENNIK_WEB_PASSWORD_CHANGE_NEEDED - response.parserErrorBody.contains("Trwają prace konserwacyjne") -> ERROR_IDZIENNIK_WEB_MAINTENANCE - else -> ERROR_IDZIENNIK_WEB_OTHER - } - else -> null - }?.let { errorCode -> - data.error(ApiError(TAG, errorCode) - .withApiResponse(json?.toString() ?: response?.parserErrorBody) - .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_IDZIENNIK_WEB_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("$IDZIENNIK_WEB_URL/$endpoint") - .userAgent(IDZIENNIK_USER_AGENT) - .postJson() - .apply { - val json = JsonObject() - parameters.map { (name, value) -> - when (value) { - is JsonObject -> json.add(name, value) - is JsonArray -> json.add(name, value) - is String -> json.addProperty(name, value) - is Int -> json.addProperty(name, value) - is Long -> json.addProperty(name, value) - is Float -> json.addProperty(name, value) - is Char -> json.addProperty(name, value) - is Boolean -> json.addProperty(name, value) - } - } - setJsonBody(json) - } - .allowErrorCode(HTTP_UNAUTHORIZED) - .allowErrorCode(HTTP_INTERNAL_ERROR) - .callback(callback) - .build() - .enqueue() - } - - fun webGet(tag: String, endpoint: String, parameters: Map = emptyMap(), onSuccess: (text: String) -> Unit) { - d(tag, "Request: Idziennik/Web - $IDZIENNIK_WEB_URL/$endpoint") - - val callback = object : TextCallbackHandler() { - override fun onSuccess(text: String?, response: Response?) { - if (text == null) { - data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) - .withResponse(response)) - return - } - - if (!text.contains("czyWyswietlicDostepMobilny")) { - when { - text.contains("Identyfikator zgłoszenia") -> ERROR_IDZIENNIK_WEB_SERVER_ERROR - text.contains("Hasło dostępu do systemu wygasło") -> ERROR_IDZIENNIK_WEB_PASSWORD_CHANGE_NEEDED - text.contains("Trwają prace konserwacyjne") -> ERROR_IDZIENNIK_WEB_MAINTENANCE - else -> ERROR_IDZIENNIK_WEB_OTHER - }.let { errorCode -> - data.error(ApiError(TAG, errorCode) - .withApiResponse(text) - .withResponse(response)) - return - } - } - - try { - onSuccess(text) - } catch (e: Exception) { - data.error(ApiError(tag, EXCEPTION_IDZIENNIK_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("$IDZIENNIK_WEB_URL/$endpoint") - .userAgent(IDZIENNIK_USER_AGENT) - .apply { - if (parameters.isEmpty()) get() - else post() - - parameters.map { (name, value) -> - addParameter(name, value) - } - } - .callback(callback) - .build() - .enqueue() - } - - fun webGetFile(tag: String, endpoint: String, targetFile: File, parameters: Map, - onSuccess: (file: File) -> Unit, onProgress: (written: Long, total: Long) -> Unit) { - - d(tag, "Request: Idziennik/Web - $IDZIENNIK_WEB_URL/$endpoint") - - 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_EDUDZIENNIK_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_EDUDZIENNIK_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("$IDZIENNIK_WEB_URL/$endpoint") - .userAgent(IDZIENNIK_USER_AGENT) - .apply { - parameters.forEach { (k, v) -> addParameter(k, v) } - } - .post() - .callback(callback) - .build() - .enqueue() - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/api/IdziennikApiCurrentRegister.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/api/IdziennikApiCurrentRegister.kt deleted file mode 100644 index 0e000fb1..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/api/IdziennikApiCurrentRegister.kt +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-29. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.api - -import com.google.gson.JsonObject -import pl.szczodrzynski.edziennik.DAY -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_API_CURRENT_REGISTER -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.ENDPOINT_IDZIENNIK_API_CURRENT_REGISTER -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikApi -import pl.szczodrzynski.edziennik.data.db.entity.LuckyNumber -import pl.szczodrzynski.edziennik.data.db.entity.Metadata -import pl.szczodrzynski.edziennik.getInt -import pl.szczodrzynski.edziennik.getJsonObject -import pl.szczodrzynski.edziennik.getString -import pl.szczodrzynski.edziennik.utils.models.Date -import pl.szczodrzynski.edziennik.utils.models.Time - -class IdziennikApiCurrentRegister(override val data: DataIdziennik, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : IdziennikApi(data, lastSync) { - companion object { - private const val TAG = "IdziennikApiCurrentRegister" - } - - init { - apiGet(TAG, IDZIENNIK_API_CURRENT_REGISTER) { json -> - if (json !is JsonObject) { - onSuccess(ENDPOINT_IDZIENNIK_API_CURRENT_REGISTER) - return@apiGet - } - - var nextSync = System.currentTimeMillis() + 14*DAY*1000 - - val settings = json.getJsonObject("ustawienia")?.apply { - getString("poczatekSemestru1")?.let { profile?.dateSemester1Start = Date.fromY_m_d(it) } - getString("koniecSemestru1")?.let { profile?.dateSemester2Start = Date.fromY_m_d(it).stepForward(0, 0, 1) } - getString("koniecSemestru2")?.let { profile?.dateYearEnd = Date.fromY_m_d(it) } - } - - json.getInt("szczesliwyNumerek")?.let { luckyNumber -> - val luckyNumberDate = Date.getToday() - settings.getString("godzinaPublikacjiSzczesliwegoLosu") - ?.let { Time.fromH_m(it) } - ?.let { publishTime -> - val now = Time.getNow() - if (publishTime.value < 150000 && now.value < publishTime.value) { - nextSync = luckyNumberDate.combineWith(publishTime) - luckyNumberDate.stepForward(0, 0, -1) // the lucky number is still for yesterday - } - else if (publishTime.value >= 150000 && now.value > publishTime.value) { - luckyNumberDate.stepForward(0, 0, 1) // the lucky number is already for tomorrow - nextSync = luckyNumberDate.combineWith(publishTime) - } - else if (publishTime.value < 150000) { - nextSync = luckyNumberDate - .clone() - .stepForward(0, 0, 1) - .combineWith(publishTime) - } - else { - nextSync = luckyNumberDate.combineWith(publishTime) - } - } - - - val luckyNumberObject = LuckyNumber( - data.profileId, - luckyNumberDate, - luckyNumber - ) - - data.luckyNumberList.add(luckyNumberObject) - data.metadataList.add( - Metadata( - profileId, - Metadata.TYPE_LUCKY_NUMBER, - luckyNumberObject.date.value.toLong(), - true, - data.profile?.empty ?: false, - System.currentTimeMillis() - )) - } - - - data.setSyncNext(ENDPOINT_IDZIENNIK_API_CURRENT_REGISTER, syncAt = nextSync) - onSuccess(ENDPOINT_IDZIENNIK_API_CURRENT_REGISTER) - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/api/IdziennikApiMessagesInbox.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/api/IdziennikApiMessagesInbox.kt deleted file mode 100644 index c8d756fe..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/api/IdziennikApiMessagesInbox.kt +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-30. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.api - -import com.google.gson.JsonArray -import pl.szczodrzynski.edziennik.asJsonObjectList -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_API_MESSAGES_INBOX -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.ENDPOINT_IDZIENNIK_API_MESSAGES_INBOX -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikApi -import pl.szczodrzynski.edziennik.data.db.entity.* -import pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_DELETED -import pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_RECEIVED -import pl.szczodrzynski.edziennik.getBoolean -import pl.szczodrzynski.edziennik.getString -import pl.szczodrzynski.edziennik.utils.Utils.crc32 -import pl.szczodrzynski.edziennik.utils.models.Date - -class IdziennikApiMessagesInbox(override val data: DataIdziennik, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : IdziennikApi(data, lastSync) { - companion object { - private const val TAG = "IdziennikApiMessagesInbox" - } - - init { - apiGet(TAG, IDZIENNIK_API_MESSAGES_INBOX) { json -> - if (json !is JsonArray) { - onSuccess(ENDPOINT_IDZIENNIK_API_MESSAGES_INBOX) - return@apiGet - } - - json.asJsonObjectList()?.forEach { jMessage -> - val subject = jMessage.getString("tytul") - if (subject?.contains("(") == true && subject.startsWith("iDziennik - ")) - return@forEach - if (subject?.startsWith("Uwaga dla ucznia (klasa:") == true) - return@forEach - - val messageIdStr = jMessage.getString("id") - val messageId = crc32((messageIdStr + "0").toByteArray()) - - var body = "[META:$messageIdStr;-1]" - body += jMessage.getString("tresc")?.replace("\n".toRegex(), "
    ") - - val readDate = if (jMessage.getBoolean("odczytana") == true) Date.fromIso(jMessage.getString("wersjaRekordu")) else 0 - val sentDate = Date.fromIso(jMessage.getString("dataWyslania")) - - val sender = jMessage.getAsJsonObject("nadawca") - var firstName = sender.getString("imie") - var lastName = sender.getString("nazwisko") - if (firstName.isNullOrEmpty() || lastName.isNullOrEmpty()) { - firstName = "usunięty" - lastName = "użytkownik" - } - val rTeacher = data.getTeacher( - firstName, - lastName - ) - rTeacher.loginId = /*sender.getString("id") + ":" + */sender.getString("usr") - rTeacher.setTeacherType(Teacher.TYPE_OTHER) - - val message = Message( - profileId, - messageId, - subject, - body, - if (jMessage.getBoolean("rekordUsuniety") == true) TYPE_DELETED else TYPE_RECEIVED, - rTeacher.id, - -1 - ) - - val messageRecipient = MessageRecipient( - profileId, - -1 /* me */, - -1, - readDate, - /*messageId*/ messageId - ) - - data.messageIgnoreList.add(message) - data.messageRecipientList.add(messageRecipient) - data.setSeenMetadataList.add(Metadata( - profileId, - Metadata.TYPE_MESSAGE, - message.id, - readDate > 0, - readDate > 0 || profile?.empty ?: false, - sentDate - )) - } - - data.setSyncNext(ENDPOINT_IDZIENNIK_API_MESSAGES_INBOX, SYNC_ALWAYS) - onSuccess(ENDPOINT_IDZIENNIK_API_MESSAGES_INBOX) - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/api/IdziennikApiMessagesSent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/api/IdziennikApiMessagesSent.kt deleted file mode 100644 index b0b17689..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/api/IdziennikApiMessagesSent.kt +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-30. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.api - -import com.google.gson.JsonArray -import pl.szczodrzynski.edziennik.DAY -import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_MESSAGES -import pl.szczodrzynski.edziennik.asJsonObjectList -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_API_MESSAGES_SENT -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.ENDPOINT_IDZIENNIK_API_MESSAGES_SENT -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikApi -import pl.szczodrzynski.edziennik.data.db.entity.Message -import pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_SENT -import pl.szczodrzynski.edziennik.data.db.entity.MessageRecipient -import pl.szczodrzynski.edziennik.data.db.entity.Metadata -import pl.szczodrzynski.edziennik.utils.Utils.crc32 -import pl.szczodrzynski.edziennik.utils.models.Date - -class IdziennikApiMessagesSent(override val data: DataIdziennik, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : IdziennikApi(data, lastSync) { - companion object { - private const val TAG = "IdziennikApiMessagesSent" - } - - init { - apiGet(TAG, IDZIENNIK_API_MESSAGES_SENT) { json -> - if (json !is JsonArray) { - onSuccess(ENDPOINT_IDZIENNIK_API_MESSAGES_SENT) - return@apiGet - } - - json.asJsonObjectList()?.forEach { jMessage -> - val messageIdStr = jMessage.get("id").asString - val messageId = crc32((messageIdStr + "1").toByteArray()) - - val subject = jMessage.get("tytul").asString - - var body = "[META:$messageIdStr;-1]" - body += jMessage.get("tresc").asString.replace("\n".toRegex(), "
    ") - - val sentDate = Date.fromIso(jMessage.get("dataWyslania").asString) - - val message = Message( - profileId, - messageId, - subject, - body, - TYPE_SENT, - -1, - -1 - ) - - for (recipientEl in jMessage.getAsJsonArray("odbiorcy")) { - val recipient = recipientEl.asJsonObject - var firstName = recipient.get("imie").asString - var lastName = recipient.get("nazwisko").asString - if (firstName.isEmpty() || lastName.isEmpty()) { - firstName = "usunięty" - lastName = "użytkownik" - } - val rTeacher = data.getTeacher(firstName, lastName) - rTeacher.loginId = /*recipient.get("id").asString + ":" + */recipient.get("usr").asString - - val messageRecipient = MessageRecipient( - profileId, - rTeacher.id, - -1, - -1, - /*messageId*/ messageId - ) - data.messageRecipientIgnoreList.add(messageRecipient) - } - - data.messageIgnoreList.add(message) - data.metadataList.add(Metadata(profileId, Metadata.TYPE_MESSAGE, message.id, true, true, sentDate)) - } - - data.setSyncNext(ENDPOINT_IDZIENNIK_API_MESSAGES_SENT, DAY, DRAWER_ITEM_MESSAGES) - onSuccess(ENDPOINT_IDZIENNIK_API_MESSAGES_SENT) - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebAnnouncements.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebAnnouncements.kt deleted file mode 100644 index f8744efa..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebAnnouncements.kt +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-28. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web - -import com.google.gson.JsonArray -import com.google.gson.JsonObject -import pl.szczodrzynski.edziennik.data.api.ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_WEB_ANNOUNCEMENTS -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.ENDPOINT_IDZIENNIK_WEB_ANNOUNCEMENTS -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikWeb -import pl.szczodrzynski.edziennik.data.api.models.ApiError -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.getJsonObject -import pl.szczodrzynski.edziennik.getLong -import pl.szczodrzynski.edziennik.getString -import pl.szczodrzynski.edziennik.utils.models.Date - -class IdziennikWebAnnouncements(override val data: DataIdziennik, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : IdziennikWeb(data, lastSync) { - companion object { - private const val TAG = "IdziennikWebAnnouncements" - } - - init { - val param = JsonObject() - param.add("parametryFiltrow", JsonArray()) - - webApiGet(TAG, IDZIENNIK_WEB_ANNOUNCEMENTS, mapOf( - "uczenId" to (data.studentId ?: ""), - "param" to param - )) { result -> - val json = result.getJsonObject("d") ?: run { - data.error(ApiError(TAG, ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA) - .withApiResponse(result)) - return@webApiGet - } - - for (jAnnouncementEl in json.getAsJsonArray("ListK")) { - val jAnnouncement = jAnnouncementEl.asJsonObject - // jAnnouncement - val announcementId = jAnnouncement.getLong("Id") ?: -1 - - val rTeacher = data.getTeacherByFirstLast(jAnnouncement.getString("Autor") ?: "") - val addedDate = jAnnouncement.getString("DataDodania")?.replace("[^\\d]".toRegex(), "")?.toLongOrNull() ?: System.currentTimeMillis() - val startDate = jAnnouncement.getString("DataWydarzenia")?.replace("[^\\d]".toRegex(), "")?.toLongOrNull()?.let { Date.fromMillis(it) } - - val announcementObject = Announcement( - profileId, - announcementId, - jAnnouncement.get("Temat").asString, - jAnnouncement.get("Tresc").asString, - startDate, - null, - rTeacher.id, - null - ) - data.announcementList.add(announcementObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_ANNOUNCEMENT, - announcementObject.id, - profile?.empty ?: false, - profile?.empty ?: false, - addedDate - )) - } - - data.setSyncNext(ENDPOINT_IDZIENNIK_WEB_ANNOUNCEMENTS, SYNC_ALWAYS) - onSuccess(ENDPOINT_IDZIENNIK_WEB_ANNOUNCEMENTS) - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebAttendance.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebAttendance.kt deleted file mode 100644 index aa0a9998..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebAttendance.kt +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-28. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web - -import pl.szczodrzynski.edziennik.crc16 -import pl.szczodrzynski.edziennik.data.api.ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_WEB_ATTENDANCE -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.ENDPOINT_IDZIENNIK_WEB_ATTENDANCE -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikWeb -import pl.szczodrzynski.edziennik.data.api.models.ApiError -import pl.szczodrzynski.edziennik.data.db.entity.Attendance -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.getJsonObject -import pl.szczodrzynski.edziennik.utils.models.Date -import pl.szczodrzynski.edziennik.utils.models.Time - -class IdziennikWebAttendance(override val data: DataIdziennik, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : IdziennikWeb(data, lastSync) { - companion object { - private const val TAG = "IdziennikWebAttendance" - } - - private var attendanceYear = Date.getToday().year - private var attendanceMonth = Date.getToday().month - private var attendancePrevMonthChecked = false - - init { - getAttendance() - } - - private fun getAttendance() { - webApiGet(TAG, IDZIENNIK_WEB_ATTENDANCE, mapOf( - "idPozDziennika" to data.registerId, - "mc" to attendanceMonth, - "rok" to attendanceYear, - "dataTygodnia" to "" - )) { result -> - val json = result.getJsonObject("d") ?: run { - data.error(ApiError(TAG, ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA) - .withApiResponse(result)) - return@webApiGet - } - - for (jAttendanceEl in json.getAsJsonArray("Obecnosci")) { - val jAttendance = jAttendanceEl.asJsonObject - // jAttendance - val attendanceTypeIdziennik = jAttendance.get("TypObecnosci").asInt - if (attendanceTypeIdziennik == 5 || attendanceTypeIdziennik == 7) - continue - val attendanceDate = Date.fromY_m_d(jAttendance.get("Data").asString) - val attendanceTime = Time.fromH_m(jAttendance.get("OdDoGodziny").asString) - if (attendanceDate.combineWith(attendanceTime) > System.currentTimeMillis()) - continue - - val attendanceId = jAttendance.get("IdLesson").asString.crc16().toLong() - val rSubject = data.getSubject(jAttendance.get("Przedmiot").asString, jAttendance.get("IdPrzedmiot").asLong, "") - val rTeacher = data.getTeacherByFDotSpaceLast(jAttendance.get("PrzedmiotNauczyciel").asString) - - var attendanceName = "obecność" - var attendanceType = Attendance.TYPE_CUSTOM - - when (attendanceTypeIdziennik) { - 1 /* nieobecność usprawiedliwiona */ -> { - attendanceName = "nieobecność usprawiedliwiona" - attendanceType = TYPE_ABSENT_EXCUSED - } - 2 /* spóźnienie */ -> { - attendanceName = "spóźnienie" - attendanceType = TYPE_BELATED - } - 3 /* nieobecność nieusprawiedliwiona */ -> { - attendanceName = "nieobecność nieusprawiedliwiona" - attendanceType = TYPE_ABSENT - } - 4 /* zwolnienie */, 9 /* zwolniony / obecny */ -> { - attendanceType = TYPE_RELEASED - if (attendanceTypeIdziennik == 4) - attendanceName = "zwolnienie" - if (attendanceTypeIdziennik == 9) - attendanceName = "zwolnienie / obecność" - } - 0 /* obecny */, 8 /* Wycieczka */ -> { - attendanceType = TYPE_PRESENT - if (attendanceTypeIdziennik == 8) - attendanceName = "wycieczka" - } - } - - val semester = profile?.dateToSemester(attendanceDate) ?: 1 - - val attendanceObject = Attendance( - profileId, - attendanceId, - rTeacher.id, - rSubject.id, - semester, - attendanceName, - attendanceDate, - attendanceTime, - attendanceType - ) - - data.attendanceList.add(attendanceObject) - if (attendanceObject.type != TYPE_PRESENT) { - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_ATTENDANCE, - attendanceObject.id, - profile?.empty ?: false, - profile?.empty ?: false, - System.currentTimeMillis() - )) - } - } - - val attendanceDateValue = attendanceYear * 10000 + attendanceMonth * 100 - if (profile?.empty == true && attendanceDateValue > profile?.getSemesterStart(1)?.value ?: 99999999) { - attendancePrevMonthChecked = true // do not need to check prev month later - attendanceMonth-- - if (attendanceMonth < 1) { - attendanceMonth = 12 - attendanceYear-- - } - getAttendance() - } else if (!attendancePrevMonthChecked /* get also the previous month */) { - attendanceMonth-- - if (attendanceMonth < 1) { - attendanceMonth = 12 - attendanceYear-- - } - attendancePrevMonthChecked = true - getAttendance() - } else { - data.setSyncNext(ENDPOINT_IDZIENNIK_WEB_ATTENDANCE, SYNC_ALWAYS) - onSuccess(ENDPOINT_IDZIENNIK_WEB_ATTENDANCE) - } - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebExams.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebExams.kt deleted file mode 100644 index 42202f4e..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebExams.kt +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-28. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web - -import com.google.gson.JsonObject -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_WEB_EXAMS -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.ENDPOINT_IDZIENNIK_WEB_EXAMS -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikWeb -import pl.szczodrzynski.edziennik.data.api.models.ApiError -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.utils.models.Date -import java.util.* - -class IdziennikWebExams(override val data: DataIdziennik, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : IdziennikWeb(data, lastSync) { - companion object { - private const val TAG = "IdziennikWebExams" - } - - private var examsYear = Date.getToday().year - private var examsMonth = Date.getToday().month - private var examsMonthsChecked = 0 - private var examsNextMonthChecked = false // TO DO temporary // no more // idk - - init { - getExams() - } - - private fun getExams() { - val param = JsonObject().apply { - addProperty("strona", 1) - addProperty("iloscNaStrone", "99") - addProperty("iloscRekordow", -1) - addProperty("kolumnaSort", "ss.Nazwa,sp.Data_sprawdzianu") - addProperty("kierunekSort", 0) - addProperty("maxIloscZaznaczonych", 0) - addProperty("panelFiltrow", 0) - } - - webApiGet(TAG, IDZIENNIK_WEB_EXAMS, mapOf( - "idP" to data.registerId, - "rok" to examsYear, - "miesiac" to examsMonth, - "param" to param - )) { result -> - val json = result.getJsonObject("d") ?: run { - data.error(ApiError(TAG, ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA) - .withApiResponse(result)) - return@webApiGet - } - - json.getJsonArray("ListK")?.asJsonObjectList()?.forEach { exam -> - val id = exam.getLong("_recordId") ?: return@forEach - val examDate = Date.fromY_m_d(exam.getString("data") ?: return@forEach) - val subjectName = exam.getString("przedmiot") ?: return@forEach - val subjectId = data.getSubject(subjectName, null, subjectName).id - val teacherName = exam.getString("wpisal") ?: return@forEach - val teacherId = data.getTeacherByLastFirst(teacherName).id - val topic = exam.getString("zakres") ?: "" - - val lessonList = data.db.timetableDao().getForDateNow(profileId, examDate) - val startTime = lessonList.firstOrNull { it.subjectId == subjectId }?.startTime - - val eventType = when (exam.getString("rodzaj")?.toLowerCase(Locale.getDefault())) { - "sprawdzian/praca klasowa", - "sprawdzian", - "praca klasowa" -> Event.TYPE_EXAM - "kartkówka" -> Event.TYPE_SHORT_QUIZ - else -> Event.TYPE_EXAM - } - - val eventObject = Event( - profileId, - id, - examDate, - startTime, - topic, - -1, - eventType, - false, - teacherId, - subjectId, - data.teamClass?.id ?: -1 - ) - - data.eventList.add(eventObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_EVENT, - eventObject.id, - profile?.empty ?: false, - profile?.empty ?: false, - System.currentTimeMillis() - )) - } - - if (profile?.empty == true && examsMonthsChecked < 3 /* how many months backwards to check? */) { - examsMonthsChecked++ - examsMonth-- - if (examsMonth < 1) { - examsMonth = 12 - examsYear-- - } - getExams() - } else if (!examsNextMonthChecked /* get also one month forward */) { - val showDate = Date.getToday().stepForward(0, 1, 0) - examsYear = showDate.year - examsMonth = showDate.month - examsNextMonthChecked = true - getExams() - } else { - data.toRemove.add(DataRemoveModel.Events.futureExceptType(Event.TYPE_HOMEWORK)) - - data.setSyncNext(ENDPOINT_IDZIENNIK_WEB_EXAMS, SYNC_ALWAYS) - onSuccess(ENDPOINT_IDZIENNIK_WEB_EXAMS) - } - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebGetAttachment.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebGetAttachment.kt deleted file mode 100644 index 562f527c..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebGetAttachment.kt +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-12-28 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web - -import org.greenrobot.eventbus.EventBus -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_WEB_GET_ATTACHMENT -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikWeb -import pl.szczodrzynski.edziennik.data.api.events.AttachmentGetEvent -import pl.szczodrzynski.edziennik.data.db.entity.Message -import pl.szczodrzynski.edziennik.get -import pl.szczodrzynski.edziennik.utils.Utils -import java.io.File - -class IdziennikWebGetAttachment(override val data: DataIdziennik, - val message: Message, - val attachmentId: Long, - val attachmentName: String, - val onSuccess: () -> Unit -) : IdziennikWeb(data, null) { - companion object { - const val TAG = "IdziennikWebGetAttachment" - } - - init { - val messageId = "\\[META:([A-z0-9]+);([0-9-]+)]".toRegex().find(message.body ?: "")?.get(2) ?: -1 - val targetFile = File(Utils.getStorageDir(), attachmentName) - - webGetFile(TAG, IDZIENNIK_WEB_GET_ATTACHMENT, targetFile, mapOf( - "id" to messageId, - "fileName" to attachmentName - ), { file -> - val event = AttachmentGetEvent( - profileId, - message.id, - attachmentId, - AttachmentGetEvent.TYPE_FINISHED, - file.absolutePath - ) - - val attachmentDataFile = File(Utils.getStorageDir(), ".${profileId}_${event.messageId}_${event.attachmentId}") - Utils.writeStringToFile(attachmentDataFile, event.fileName) - - EventBus.getDefault().post(event) - - onSuccess() - - }) { written, _ -> - val event = AttachmentGetEvent( - profileId, - message.id, - attachmentId, - AttachmentGetEvent.TYPE_PROGRESS, - bytesWritten = written - ) - - EventBus.getDefault().post(event) - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebGetMessage.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebGetMessage.kt deleted file mode 100644 index dfe9fba3..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebGetMessage.kt +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-12-28 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web - -import org.greenrobot.eventbus.EventBus -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_WEB_GET_MESSAGE -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikWeb -import pl.szczodrzynski.edziennik.data.api.events.MessageGetEvent -import pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_RECEIVED -import pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_SENT -import pl.szczodrzynski.edziennik.data.db.entity.Metadata -import pl.szczodrzynski.edziennik.data.db.full.MessageFull -import pl.szczodrzynski.edziennik.data.db.full.MessageRecipientFull -import pl.szczodrzynski.edziennik.utils.models.Date - -class IdziennikWebGetMessage(override val data: DataIdziennik, - private val message: MessageFull, - val onSuccess: () -> Unit -) : IdziennikWeb(data, null) { - companion object { - const val TAG = "IdziennikWebGetMessage" - } - - init { data.profile?.also { profile -> - val metaPattern = "\\[META:([A-z0-9]+);([0-9-]+)]".toRegex() - val meta = metaPattern.find(message.body!!) - val messageIdString = meta?.get(1) ?: "" - - webApiGet(TAG, IDZIENNIK_WEB_GET_MESSAGE, parameters = mapOf( - "idWiadomosci" to messageIdString, - "typWiadomosci" to if (message.type == TYPE_SENT) 1 else 0 - )) { json -> - json.getJsonObject("d")?.getJsonObject("Wiadomosc")?.also { - val id = it.getLong("_recordId") - message.body = message.body?.replace(metaPattern, "[META:$messageIdString;$id]") - - message.clearAttachments() - it.getJsonArray("ListaZal")?.asJsonObjectList()?.forEach { attachment -> - message.addAttachment( - attachment.getLong("Id") ?: return@forEach, - attachment.getString("Nazwa") ?: return@forEach, - -1 - ) - } - - message.recipients?.clear() - when (message.type) { - TYPE_RECEIVED -> { - val recipientObject = MessageRecipientFull(profileId, -1, message.id) - - val readDateString = it.getString("DataOdczytania") - recipientObject.readDate = if (readDateString.isNullOrBlank()) System.currentTimeMillis() - else Date.fromIso(readDateString) - - recipientObject.fullName = profile.accountName ?: profile.studentNameLong - - data.messageRecipientList.add(recipientObject) - message.addRecipient(recipientObject) - } - - TYPE_SENT -> { - it.getJsonArray("ListaOdbiorcow")?.asJsonObjectList()?.forEach { recipient -> - val recipientName = recipient.getString("NazwaOdbiorcy") ?: return@forEach - val teacher = data.getTeacherByLastFirst(recipientName) - - val recipientObject = MessageRecipientFull(profileId, teacher.id, message.id) - - recipientObject.readDate = recipient.getLong("Status") ?: return@forEach - recipientObject.fullName = teacher.fullName - - data.messageRecipientList.add(recipientObject) - message.addRecipient(recipientObject) - } - } - } - - if (!message.seen) { - message.seen = true - - data.setSeenMetadataList.add(Metadata( - profileId, - Metadata.TYPE_MESSAGE, - message.id, - message.seen, - message.notified, - message.addedDate - )) - } - - EventBus.getDefault().postSticky(MessageGetEvent(message)) - - data.messageList.add(message) - onSuccess() - } - } - } ?: onSuccess() } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebGetRecipientList.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebGetRecipientList.kt deleted file mode 100644 index a14efc24..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebGetRecipientList.kt +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-12-30. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web - -import androidx.room.OnConflictStrategy -import org.greenrobot.eventbus.EventBus -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_WEB_GET_RECIPIENT_LIST -import pl.szczodrzynski.edziennik.data.api.Regexes -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikWeb -import pl.szczodrzynski.edziennik.data.api.events.RecipientListGetEvent -import pl.szczodrzynski.edziennik.data.api.models.ApiError -import pl.szczodrzynski.edziennik.data.db.entity.Teacher - -class IdziennikWebGetRecipientList(override val data: DataIdziennik, - val onSuccess: () -> Unit -) : IdziennikWeb(data, null) { - companion object { - private const val TAG = "IdziennikWebGetRecipientList" - } - - init { - webApiGet(TAG, IDZIENNIK_WEB_GET_RECIPIENT_LIST, mapOf( - "idP" to data.registerId - )) { result -> - val json = result.getJsonObject("d") ?: run { - data.error(ApiError(TAG, ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA) - .withApiResponse(result)) - return@webApiGet - } - - json.getJsonArray("ListK_Pracownicy")?.asJsonObjectList()?.forEach { recipient -> - val name = recipient.getString("ImieNazwisko") ?: ": " - val (fullName, subject) = name.split(": ").let { - Pair(it.getOrNull(0), it.getOrNull(1)) - } - val guid = recipient.getString("Id") ?: "" - // get teacher by ID or create it - val teacher = data.getTeacherByFirstLast(fullName ?: " ") - teacher.loginId = guid - teacher.setTeacherType(Teacher.TYPE_TEACHER) - // unset OTHER that is automatically set in IdziennikApiMessages* - teacher.unsetTeacherType(Teacher.TYPE_OTHER) - teacher.typeDescription = subject - } - - json.getJsonArray("ListK_Opiekunowie")?.asJsonObjectList()?.forEach { recipient -> - val name = recipient.getString("ImieNazwisko") ?: ": " - val (fullName, parentOf) = Regexes.IDZIENNIK_MESSAGES_RECIPIENT_PARENT.find(name)?.let { - Pair(it.groupValues.getOrNull(1), it.groupValues.getOrNull(2)) - } ?: Pair(null, null) - val guid = recipient.getString("Id") ?: "" - // get teacher by ID or create it - val teacher = data.getTeacherByFirstLast(fullName ?: " ") - teacher.loginId = guid - teacher.setTeacherType(Teacher.TYPE_PARENT) - // unset OTHER that is automatically set in IdziennikApiMessages* - teacher.unsetTeacherType(Teacher.TYPE_OTHER) - teacher.typeDescription = parentOf - } - - 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/idziennik/data/web/IdziennikWebGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebGrades.kt deleted file mode 100644 index b3237c82..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebGrades.kt +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-28. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web - -import android.graphics.Color -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_WEB_GRADES -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.ENDPOINT_IDZIENNIK_WEB_GRADES -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikWeb -import pl.szczodrzynski.edziennik.data.api.models.ApiError -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.Metadata -import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS -import pl.szczodrzynski.edziennik.utils.models.Date - -class IdziennikWebGrades(override val data: DataIdziennik, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : IdziennikWeb(data, lastSync) { - companion object { - private const val TAG = "IdziennikWebGrades" - } - - init { data.profile?.also { profile -> - webApiGet(TAG, IDZIENNIK_WEB_GRADES, mapOf( - "idPozDziennika" to data.registerId - )) { result -> - val json = result.getJsonObject("d") ?: run { - data.error(ApiError(TAG, ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA) - .withApiResponse(result)) - return@webApiGet - } - - json.getJsonArray("Przedmioty")?.asJsonObjectList()?.onEach { subjectJson -> - val subject = data.getSubject( - subjectJson.getString("Przedmiot") ?: return@onEach, - subjectJson.getLong("IdPrzedmiotu") ?: return@onEach, - subjectJson.getString("Przedmiot") ?: return@onEach - ) - subjectJson.getJsonArray("Oceny")?.asJsonObjectList()?.forEach { grade -> - val id = grade.getLong("idK") ?: return@forEach - val category = grade.getString("Kategoria") ?: "" - val name = grade.getString("Ocena") ?: "?" - val semester = grade.getInt("Semestr") ?: 1 - val teacher = data.getTeacherByLastFirst(grade.getString("Wystawil") ?: return@forEach) - - val countToAverage = grade.getBoolean("DoSredniej") ?: true - var value = grade.getFloat("WartoscDoSred") ?: 0.0f - val weight = if (countToAverage) - grade.getFloat("Waga") ?: 0.0f - else - 0.0f - - val gradeColor = grade.getString("Kolor") ?: "" - var colorInt = 0xff2196f3.toInt() - if (gradeColor.isNotEmpty()) { - colorInt = Color.parseColor("#$gradeColor") - } - - val gradeObject = Grade( - profileId = profileId, - id = id, - name = name, - type = TYPE_NORMAL, - value = value, - weight = weight, - color = colorInt, - category = category, - description = null, - comment = null, - semester = semester, - teacherId = teacher.id, - subjectId = subject.id) - - when (grade.getInt("Typ")) { - 0 -> { - val history = grade.getJsonArray("Historia")?.asJsonObjectList() - if (history?.isNotEmpty() == true) { - var sum = gradeObject.value * gradeObject.weight - var count = gradeObject.weight - for (historyItem in history) { - val countToTheAverage = historyItem.getBoolean("DoSredniej") ?: false - value = historyItem.get("WartoscDoSred").asFloat - val weight = historyItem.get("Waga").asFloat - - if (value > 0 && countToTheAverage) { - sum += value * weight - count += weight - } - - val historyColor = historyItem.getString("Kolor") ?: "" - colorInt = 0xff2196f3.toInt() - if (historyColor.isNotEmpty()) { - colorInt = Color.parseColor("#$historyColor") - } - - val historyObject = Grade( - profileId = profileId, - id = gradeObject.id * -1, - name = historyItem.getString("Ocena") ?: "", - type = TYPE_NORMAL, - value = value, - weight = if (value > 0f && countToTheAverage) weight * -1f else 0f, - color = colorInt, - category = historyItem.getString("Kategoria"), - description = historyItem.getString("Uzasadnienie"), - comment = null, - semester = historyItem.getInt("Semestr") ?: 1, - teacherId = teacher.id, - subjectId = subject.id) - historyObject.parentId = gradeObject.id - - val addedDate = historyItem.getString("Data_wystaw")?.let { Date.fromY_m_d(it).inMillis } ?: System.currentTimeMillis() - - data.gradeList.add(historyObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_GRADE, - historyObject.id, - true, - true, - addedDate - )) - } - // 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 - } - } - 1 -> { - gradeObject.type = Grade.TYPE_SEMESTER1_FINAL - gradeObject.name = value.toInt().toString() - gradeObject.weight = 0f - } - 2 -> { - gradeObject.type = Grade.TYPE_YEAR_FINAL - gradeObject.name = value.toInt().toString() - gradeObject.weight = 0f - } - } - - val addedDate = grade.getString("Data_wystaw")?.let { Date.fromY_m_d(it).inMillis } ?: System.currentTimeMillis() - - data.gradeList.add(gradeObject) - data.metadataList.add( - Metadata( - profileId, - Metadata.TYPE_GRADE, - id, - data.profile.empty, - data.profile.empty, - addedDate - )) - } - } - - data.toRemove.addAll(listOf( - Grade.TYPE_NORMAL, - Grade.TYPE_SEMESTER1_FINAL, - Grade.TYPE_YEAR_FINAL - ).map { - DataRemoveModel.Grades.semesterWithType(profile.currentSemester, it) - }) - data.setSyncNext(ENDPOINT_IDZIENNIK_WEB_GRADES, SYNC_ALWAYS) - onSuccess(ENDPOINT_IDZIENNIK_WEB_GRADES) - } - } ?: onSuccess(ENDPOINT_IDZIENNIK_WEB_GRADES) } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebHomework.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebHomework.kt deleted file mode 100644 index 345e7da4..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebHomework.kt +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-11-25 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web - -import com.google.gson.JsonObject -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_WEB_HOMEWORK -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.ENDPOINT_IDZIENNIK_WEB_HOMEWORK -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikWeb -import pl.szczodrzynski.edziennik.data.api.models.ApiError -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.utils.models.Date - -class IdziennikWebHomework(override val data: DataIdziennik, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : IdziennikWeb(data, lastSync) { - companion object { - private const val TAG = "IdziennikWebHomework" - } - - init { - val param = JsonObject().apply { - addProperty("strona", 1) - addProperty("iloscNaStrone", 997) - addProperty("iloscRekordow", -1) - addProperty("kolumnaSort", "DataZadania") - addProperty("kierunekSort", 0) - addProperty("maxIloscZaznaczonych", 0) - addProperty("panelFiltrow", 0) - } - - webApiGet(TAG, IDZIENNIK_WEB_HOMEWORK, mapOf( - "idP" to data.registerId, - "data" to Date.getToday().stringY_m_d, - "wszystkie" to true, - "param" to param - )) { result -> - val json = result.getJsonObject("d") ?: run { - data.error(ApiError(TAG, ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA) - .withApiResponse(result)) - return@webApiGet - } - - json.getJsonArray("ListK")?.asJsonObjectList()?.forEach { homework -> - val id = homework.getLong("_recordId") ?: return@forEach - val eventDate = Date.fromY_m_d(homework.getString("dataO") ?: return@forEach) - val subjectName = homework.getString("przed") ?: return@forEach - val subjectId = data.getSubject(subjectName, null, subjectName).id - val teacherName = homework.getString("usr") ?: return@forEach - val teacherId = data.getTeacherByLastFirst(teacherName).id - val lessonList = data.db.timetableDao().getForDateNow(profileId, eventDate) - val startTime = lessonList.firstOrNull { it.subjectId == subjectId }?.displayStartTime - val topic = homework.getString("tytul") ?: "" - - val seen = when (profile?.empty) { - true -> true - else -> eventDate < Date.getToday() - } - - - val eventObject = Event( - profileId, - id, - eventDate, - startTime, - topic, - -1, - Event.TYPE_HOMEWORK, - false, - teacherId, - subjectId, - data.teamClass?.id ?: -1 - ) - - data.eventList.add(eventObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_HOMEWORK, - eventObject.id, - seen, - seen, - System.currentTimeMillis() - )) - } - - data.toRemove.add(DataRemoveModel.Events.futureWithType(Event.TYPE_HOMEWORK)) - - data.setSyncNext(ENDPOINT_IDZIENNIK_WEB_HOMEWORK, SYNC_ALWAYS) - onSuccess(ENDPOINT_IDZIENNIK_WEB_HOMEWORK) - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebNotices.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebNotices.kt deleted file mode 100644 index dcc560d5..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebNotices.kt +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-28. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web - -import pl.szczodrzynski.edziennik.crc16 -import pl.szczodrzynski.edziennik.data.api.ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_WEB_NOTICES -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.ENDPOINT_IDZIENNIK_WEB_NOTICES -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikWeb -import pl.szczodrzynski.edziennik.data.api.models.ApiError -import pl.szczodrzynski.edziennik.data.db.entity.Metadata -import pl.szczodrzynski.edziennik.data.db.entity.Notice -import pl.szczodrzynski.edziennik.data.db.entity.Notice.* -import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS -import pl.szczodrzynski.edziennik.getJsonObject -import pl.szczodrzynski.edziennik.utils.models.Date - -class IdziennikWebNotices(override val data: DataIdziennik, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : IdziennikWeb(data, lastSync) { - companion object { - private const val TAG = "IdziennikWebNotices" - } - - init { - webApiGet(TAG, IDZIENNIK_WEB_NOTICES, mapOf( - "idPozDziennika" to data.registerId - )) { result -> - val json = result.getJsonObject("d") ?: run { - data.error(ApiError(TAG, ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA) - .withApiResponse(result)) - return@webApiGet - } - - for (jNoticeEl in json.getAsJsonArray("SUwaga")) { - val jNotice = jNoticeEl.asJsonObject - // jNotice - val noticeId = jNotice.get("id").asString.crc16().toLong() - - val rTeacher = data.getTeacherByLastFirst(jNotice.get("Nauczyciel").asString) - val addedDate = Date.fromY_m_d(jNotice.get("Data").asString) - - var nType = TYPE_NEUTRAL - val jType = jNotice.get("Typ").asString - if (jType == "n") { - nType = TYPE_NEGATIVE - } else if (jType == "p") { - nType = TYPE_POSITIVE - } - - val noticeObject = Notice( - profileId, - noticeId, - jNotice.get("Tresc").asString, - jNotice.get("Semestr").asInt, - nType, - rTeacher.id) - data.noticeList.add(noticeObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_NOTICE, - noticeObject.id, - profile?.empty ?: false, - profile?.empty ?: false, - addedDate.inMillis - )) - } - - data.setSyncNext(ENDPOINT_IDZIENNIK_WEB_NOTICES, SYNC_ALWAYS) - onSuccess(ENDPOINT_IDZIENNIK_WEB_NOTICES) - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebProposedGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebProposedGrades.kt deleted file mode 100644 index fe5a0156..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebProposedGrades.kt +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-28. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web - -import pl.szczodrzynski.edziennik.asJsonObjectList -import pl.szczodrzynski.edziennik.data.api.ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_WEB_MISSING_GRADES -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.ENDPOINT_IDZIENNIK_WEB_PROPOSED_GRADES -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikWeb -import pl.szczodrzynski.edziennik.data.api.models.ApiError -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_PROPOSED -import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_YEAR_PROPOSED -import pl.szczodrzynski.edziennik.data.db.entity.Metadata -import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS -import pl.szczodrzynski.edziennik.getJsonArray -import pl.szczodrzynski.edziennik.getJsonObject -import pl.szczodrzynski.edziennik.getString -import pl.szczodrzynski.edziennik.utils.Utils.getWordGradeValue - -class IdziennikWebProposedGrades(override val data: DataIdziennik, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : IdziennikWeb(data, lastSync) { - companion object { - private const val TAG = "IdziennikWebProposedGrades" - } - - init { data.profile?.also { profile -> - webApiGet(TAG, IDZIENNIK_WEB_MISSING_GRADES, mapOf( - "idPozDziennika" to data.registerId - )) { result -> - val json = result.getJsonObject("d") ?: run { - data.error(ApiError(TAG, ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA) - .withApiResponse(result)) - return@webApiGet - } - - json.getJsonArray("Przedmioty")?.asJsonObjectList()?.forEach { subject -> - val subjectName = subject.getString("Przedmiot") ?: return@forEach - val subjectObject = data.getSubject(subjectName, null, subjectName) - - val semester1Proposed = subject.getString("OcenaSem1") ?: "" - val semester1Value = getWordGradeValue(semester1Proposed) - val semester1Id = subjectObject.id * (-100) - 1 - - val semester2Proposed = subject.getString("OcenaSem2") ?: "" - val semester2Value = getWordGradeValue(semester2Proposed) - val semester2Id = subjectObject.id * (-100) - 2 - - if (semester1Proposed != "") { - val gradeObject = Grade( - profileId = profileId, - id = semester1Id, - name = semester1Value.toString(), - type = TYPE_SEMESTER1_PROPOSED, - value = semester1Value.toFloat(), - weight = 0f, - color = -1, - category = null, - description = null, - comment = null, - semester = 1, - teacherId = -1, - subjectId = subjectObject.id - ) - - data.gradeList.add(gradeObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_GRADE, - gradeObject.id, - profile.empty, - profile.empty, - System.currentTimeMillis() - )) - } - - if (semester2Proposed != "") { - val gradeObject = Grade( - profileId = profileId, - id = semester2Id, - name = semester2Value.toString(), - type = TYPE_YEAR_PROPOSED, - value = semester2Value.toFloat(), - weight = 0f, - color = -1, - category = null, - description = null, - comment = null, - semester = 2, - teacherId = -1, - subjectId = subjectObject.id - ) - - val addedDate = if (data.profile.empty) - data.profile.dateSemester1Start.inMillis - else - System.currentTimeMillis() - - data.gradeList.add(gradeObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_GRADE, - gradeObject.id, - profile.empty, - profile.empty, - addedDate - )) - } - } - - data.toRemove.addAll(listOf(TYPE_SEMESTER1_PROPOSED, TYPE_YEAR_PROPOSED).map { - DataRemoveModel.Grades.semesterWithType(profile.currentSemester, it) - }) - data.setSyncNext(ENDPOINT_IDZIENNIK_WEB_PROPOSED_GRADES, SYNC_ALWAYS) - onSuccess(ENDPOINT_IDZIENNIK_WEB_PROPOSED_GRADES) - } - } ?: onSuccess(ENDPOINT_IDZIENNIK_WEB_PROPOSED_GRADES) } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebSendMessage.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebSendMessage.kt deleted file mode 100644 index 9a997a32..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebSendMessage.kt +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-12-30. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web - -import org.greenrobot.eventbus.EventBus -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_WEB_SEND_MESSAGE -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikWeb -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.api.IdziennikApiMessagesSent -import pl.szczodrzynski.edziennik.data.api.events.MessageSentEvent -import pl.szczodrzynski.edziennik.data.api.models.ApiError -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 java.util.* - -class IdziennikWebSendMessage(override val data: DataIdziennik, - val recipients: List, - val subject: String, - val text: String, - val onSuccess: () -> Unit -) : IdziennikWeb(data, null) { - companion object { - private const val TAG = "IdziennikWebSendMessage" - } - - init { - val recipientsArray = JsonArray() - for (teacher in recipients) { - teacher.loginId?.let { - recipientsArray += it - } - } - - webApiGet(TAG, IDZIENNIK_WEB_SEND_MESSAGE, mapOf( - "Wiadomosc" to JsonObject( - "Tytul" to subject, - "Tresc" to text, - "Confirmation" to false, - "GuidMessage" to UUID.randomUUID().toString().toUpperCase(Locale.ROOT), - "Odbiorcy" to recipientsArray - ) - )) { result -> - val json = result.getJsonObject("d") ?: run { - data.error(ApiError(TAG, ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA) - .withApiResponse(result)) - return@webApiGet - } - - if (json.getBoolean("CzyJestBlad") != false) { - // TODO error - return@webApiGet - } - - IdziennikApiMessagesSent(data, null) { - val message = data.messageIgnoreList.firstOrNull { it.type == Message.TYPE_SENT && it.subject == subject } - val metadata = data.metadataList.firstOrNull { it.thingType == Metadata.TYPE_MESSAGE && it.thingId == message?.id } - val event = MessageSentEvent(data.profileId, message, metadata?.addedDate) - - EventBus.getDefault().postSticky(event) - onSuccess() - } - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebSwitchRegister.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebSwitchRegister.kt deleted file mode 100644 index f225f177..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebSwitchRegister.kt +++ /dev/null @@ -1,36 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web - -import com.google.gson.JsonObject -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_WEB_HOME -import pl.szczodrzynski.edziennik.data.api.Regexes -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikWeb -import pl.szczodrzynski.edziennik.get -import pl.szczodrzynski.edziennik.getString - -class IdziennikWebSwitchRegister(override val data: DataIdziennik, - val registerId: Int, - val onSuccess: () -> Unit -) : IdziennikWeb(data, null) { - companion object { - private const val TAG = "IdziennikWebSwitchRegister" - } - - init { - val hiddenFields = data.loginStore.getLoginData("hiddenFields", JsonObject()) - // TODO error checking - - webGet(TAG, IDZIENNIK_WEB_HOME, mapOf( - "__VIEWSTATE" to hiddenFields.getString("__VIEWSTATE", ""), - "__VIEWSTATEGENERATOR" to hiddenFields.getString("__VIEWSTATEGENERATOR", ""), - "__EVENTVALIDATION" to hiddenFields.getString("__EVENTVALIDATION", ""), - "ctl00\$dxComboUczniowie" to registerId - )) { text -> - Regexes.IDZIENNIK_WEB_SELECTED_REGISTER.find(text)?.let { - val registerId = it[1].toIntOrNull() ?: return@let - data.webSelectedRegister = registerId - } - onSuccess() - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebTimetable.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebTimetable.kt deleted file mode 100644 index 066346cd..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/data/web/IdziennikWebTimetable.kt +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-11-22 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.web - -import androidx.core.util.set -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_WEB_TIMETABLE -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.ENDPOINT_IDZIENNIK_WEB_TIMETABLE -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikWeb -import pl.szczodrzynski.edziennik.data.api.models.ApiError -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.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 IdziennikWebTimetable(override val data: DataIdziennik, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : IdziennikWeb(data, lastSync) { - companion object { - private const val TAG = "IdziennikWebTimetable" - } - - 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) - - webApiGet(TAG, IDZIENNIK_WEB_TIMETABLE, mapOf( - "idPozDziennika" to data.registerId, - "pidRokSzkolny" to data.schoolYearId, - "data" to "${weekStart.stringY_m_d}T10:00:00.000Z" - )) { result -> - val json = result.getJsonObject("d") ?: run { - data.error(ApiError(TAG, ERROR_IDZIENNIK_WEB_REQUEST_NO_DATA) - .withApiResponse(result)) - return@webApiGet - } - - json.getJsonArray("GodzinyLekcyjne")?.asJsonObjectList()?.forEachIndexed { index, range -> - val lessonRange = LessonRange( - profileId, - index + 1, - range.getString("Poczatek")?.let { Time.fromH_m(it) } - ?: return@forEachIndexed, - range.getString("Koniec")?.let { Time.fromH_m(it) } ?: return@forEachIndexed - ) - data.lessonRanges[lessonRange.lessonNumber] = lessonRange - } - - val dates = mutableSetOf() - val lessons = mutableListOf() - - json.getJsonArray("Przedmioty")?.asJsonObjectList()?.forEach { lesson -> - val subject = data.getSubject( - lesson.getString("Nazwa") ?: return@forEach, - lesson.getLong("Id"), - lesson.getString("Skrot") ?: "" - ) - val teacher = data.getTeacherByFDotLast(lesson.getString("Nauczyciel") - ?: return@forEach) - - val newSubjectName = lesson.getString("PrzedmiotZastepujacy") - val newSubject = when (newSubjectName.isNullOrBlank()) { - true -> null - else -> data.getSubject(newSubjectName, null, newSubjectName) - } - - val newTeacherName = lesson.getString("NauZastepujacy") - val newTeacher = when (newTeacherName.isNullOrBlank()) { - true -> null - else -> data.getTeacherByFDotLast(newTeacherName) - } - - val weekDay = lesson.getInt("DzienTygodnia")?.minus(1) ?: return@forEach - val lessonRange = data.lessonRanges[lesson.getInt("Godzina")?.plus(1) - ?: return@forEach] - val lessonDate = weekStart.clone().stepForward(0, 0, weekDay) - val classroom = lesson.getString("NazwaSali") - - val type = lesson.getInt("TypZastepstwa") ?: -1 - - val lessonObject = Lesson(profileId, -1) - - when (type) { - 1, 2, 3, 4, 5 -> { - lessonObject.apply { - this.type = Lesson.TYPE_CHANGE - - this.date = lessonDate - this.lessonNumber = lessonRange.lessonNumber - this.startTime = lessonRange.startTime - this.endTime = lessonRange.endTime - this.subjectId = newSubject?.id - this.teacherId = newTeacher?.id - this.teamId = data.teamClass?.id - this.classroom = classroom - - this.oldDate = lessonDate - this.oldLessonNumber = lessonRange.lessonNumber - this.oldStartTime = lessonRange.startTime - this.oldEndTime = lessonRange.endTime - this.oldSubjectId = subject.id - this.oldTeacherId = teacher.id - this.oldTeamId = data.teamClass?.id - this.oldClassroom = classroom - } - } - 0 -> { - lessonObject.apply { - this.type = Lesson.TYPE_CANCELLED - - this.oldDate = lessonDate - this.oldLessonNumber = lessonRange.lessonNumber - this.oldStartTime = lessonRange.startTime - this.oldEndTime = lessonRange.endTime - this.oldSubjectId = subject.id - this.oldTeacherId = teacher.id - this.oldTeamId = data.teamClass?.id - this.oldClassroom = classroom - } - } - else -> { - lessonObject.apply { - this.type = Lesson.TYPE_NORMAL - - this.date = lessonDate - this.lessonNumber = lessonRange.lessonNumber - this.startTime = lessonRange.startTime - this.endTime = lessonRange.endTime - this.subjectId = subject.id - this.teacherId = teacher.id - this.teamId = data.teamClass?.id - this.classroom = classroom - } - } - } - - lessonObject.id = lessonObject.buildId() - - dates.add(lessonDate.value) - lessons.add(lessonObject) - - val seen = profile.empty || lessonDate < Date.getToday() - - if (lessonObject.type != Lesson.TYPE_NORMAL && lessonDate >= Date.getToday()) { - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_LESSON_CHANGE, - lessonObject.id, - seen, - seen, - System.currentTimeMillis() - )) - } - } - - val date: Date = weekStart.clone() - while (date <= weekEnd) { - if (!dates.contains(date.value)) { - lessons.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 ${weekStart.stringY_m_d} and ${weekEnd.stringY_m_d} - timetable downloaded for $getDate") - - data.lessonList.addAll(lessons) - data.toRemove.add(DataRemoveModel.Timetable.between(weekStart, weekEnd)) - - data.setSyncNext(ENDPOINT_IDZIENNIK_WEB_TIMETABLE, SYNC_ALWAYS) - onSuccess(ENDPOINT_IDZIENNIK_WEB_TIMETABLE) - } - }} -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/firstlogin/IdziennikFirstLogin.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/firstlogin/IdziennikFirstLogin.kt deleted file mode 100644 index 892c12c8..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/firstlogin/IdziennikFirstLogin.kt +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-27. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.firstlogin - -import org.greenrobot.eventbus.EventBus -import pl.szczodrzynski.edziennik.data.api.ERROR_LOGIN_IDZIENNIK_FIRST_NO_SCHOOL_YEAR -import pl.szczodrzynski.edziennik.data.api.IDZIENNIK_WEB_SETTINGS -import pl.szczodrzynski.edziennik.data.api.LOGIN_TYPE_IDZIENNIK -import pl.szczodrzynski.edziennik.data.api.Regexes -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.data.IdziennikWeb -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.login.IdziennikLoginWeb -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.fixName -import pl.szczodrzynski.edziennik.get -import pl.szczodrzynski.edziennik.set -import pl.szczodrzynski.edziennik.swapFirstLastName - -class IdziennikFirstLogin(val data: DataIdziennik, val onSuccess: () -> Unit) { - companion object { - private const val TAG = "IdziennikFirstLogin" - } - - private val web = IdziennikWeb(data, null) - private val profileList = mutableListOf() - - init { - val loginStoreId = data.loginStore.id - val loginStoreType = LOGIN_TYPE_IDZIENNIK - var firstProfileId = loginStoreId - - IdziennikLoginWeb(data) { - web.webGet(TAG, IDZIENNIK_WEB_SETTINGS) { text -> - //val accounts = json.getJsonArray("accounts") - - val isParent = Regexes.IDZIENNIK_LOGIN_FIRST_IS_PARENT.find(text)?.get(1) != "0" - val accountNameLong = if (isParent) - Regexes.IDZIENNIK_LOGIN_FIRST_ACCOUNT_NAME.find(text)?.get(1)?.swapFirstLastName()?.fixName() - else null - - var schoolYearStart: Int? = null - var schoolYearEnd: Int? = null - var schoolYearName: String? = null - val schoolYearId = Regexes.IDZIENNIK_LOGIN_FIRST_SCHOOL_YEAR.find(text)?.let { - schoolYearName = it[2]+"/"+it[3] - schoolYearStart = it[2].toIntOrNull() - schoolYearEnd = it[3].toIntOrNull() - it[1].toIntOrNull() - } ?: run { - data.error(ApiError(TAG, ERROR_LOGIN_IDZIENNIK_FIRST_NO_SCHOOL_YEAR) - .withApiResponse(text)) - return@webGet - } - - Regexes.IDZIENNIK_LOGIN_FIRST_STUDENT.findAll(text) - .toMutableList() - .reversed() - .forEach { match -> - val registerId = match[1].toIntOrNull() ?: return@forEach - val studentId = match[2] - val firstName = match[3] - val lastName = match[4] - val className = match[5] + " " + match[6] - - val studentNameLong = "$firstName $lastName".fixName() - val studentNameShort = "$firstName ${lastName[0]}.".fixName() - val accountName = if (accountNameLong == studentNameLong) null else accountNameLong - - val profile = Profile( - firstProfileId++, - loginStoreId, - loginStoreType, - studentNameLong, - data.webUsername, - studentNameLong, - studentNameShort, - accountName - ).apply { - schoolYearStart?.let { studentSchoolYearStart = it } - studentClassName = className - studentData["studentId"] = studentId - studentData["registerId"] = registerId - studentData["schoolYearId"] = schoolYearId - } - profileList.add(profile) - } - - EventBus.getDefault().post(FirstLoginFinishedEvent(profileList, data.loginStore)) - onSuccess() - } - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/login/IdziennikLoginApi.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/login/IdziennikLoginApi.kt deleted file mode 100644 index 2afe481d..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/login/IdziennikLoginApi.kt +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-27. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.login - -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik - -class IdziennikLoginApi(val data: DataIdziennik, val onSuccess: () -> Unit) { - companion object { - private const val TAG = "IdziennikLoginApi" - } - - init { run { - if (data.isApiLoginValid()) { - onSuccess() - } - else { - onSuccess() - } - }} -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/login/IdziennikLoginWeb.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/login/IdziennikLoginWeb.kt deleted file mode 100644 index e15f9410..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/login/IdziennikLoginWeb.kt +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-26. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.login - -import im.wangchao.mhttp.Request -import im.wangchao.mhttp.Response -import im.wangchao.mhttp.callback.TextCallbackHandler -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.* -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.data.api.models.ApiError -import pl.szczodrzynski.edziennik.data.db.entity.LuckyNumber -import pl.szczodrzynski.edziennik.data.db.entity.Metadata -import pl.szczodrzynski.edziennik.utils.Utils -import pl.szczodrzynski.edziennik.utils.models.Date - -class IdziennikLoginWeb(val data: DataIdziennik, val onSuccess: () -> Unit) { - companion object { - private const val TAG = "IdziennikLoginWeb" - } - - init { run { - if (data.isWebLoginValid()) { - data.app.cookieJar.set("iuczniowie.progman.pl", "ASP.NET_SessionId_iDziennik", data.webSessionId) - data.app.cookieJar.set("iuczniowie.progman.pl", ".ASPXAUTH", data.webAuth) - onSuccess() - } - else { - data.app.cookieJar.clear("iuczniowie.progman.pl") - if (data.webSchoolName != null && data.webUsername != null && data.webPassword != null) { - loginWithCredentials() - } - else { - data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) - } - } - }} - - private fun loginWithCredentials() { - Utils.d(TAG, "Request: Idziennik/Login/Web - $IDZIENNIK_WEB_URL/$IDZIENNIK_WEB_LOGIN") - - val loginCallback = object : TextCallbackHandler() { - override fun onSuccess(text: String?, response: Response?) { - if (text.isNullOrEmpty()) { - data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) - .withResponse(response)) - return - } - - // login succeeded: there is a start page - if (text.contains("czyWyswietlicDostepMobilny")) { - val cookies = data.app.cookieJar.getAll("iuczniowie.progman.pl") - run { - data.webSessionId = cookies["ASP.NET_SessionId_iDziennik"] ?: return@run ERROR_LOGIN_IDZIENNIK_WEB_NO_SESSION - data.webAuth = cookies[".ASPXAUTH"] ?: return@run ERROR_LOGIN_IDZIENNIK_WEB_NO_AUTH - data.apiBearer = cookies["Bearer"]?: return@run ERROR_LOGIN_IDZIENNIK_WEB_NO_BEARER - data.loginExpiryTime = response.getUnixDate() + 30 * MINUTE /* after about 40 minutes the login didn't work already */ - data.apiExpiryTime = response.getUnixDate() + 12 * HOUR /* actually it expires after 24 hours but I'm not sure when does the token refresh. */ - - val hiddenFields = JsonObject() - Regexes.IDZIENNIK_LOGIN_HIDDEN_FIELDS.findAll(text).forEach { - hiddenFields[it[1]] = it[2] - } - data.loginStore.putLoginData("hiddenFields", hiddenFields) - - Regexes.IDZIENNIK_WEB_SELECTED_REGISTER.find(text)?.let { - val registerId = it[1].toIntOrNull() ?: return@let - data.webSelectedRegister = registerId - } - - data.profile?.let { profile -> - Regexes.IDZIENNIK_WEB_LUCKY_NUMBER.find(text)?.also { - val number = it[1].toIntOrNull() ?: return@also - val luckyNumberObject = LuckyNumber( - data.profileId, - Date.getToday(), - number - ) - - data.luckyNumberList.add(luckyNumberObject) - data.metadataList.add( - Metadata( - profile.id, - Metadata.TYPE_LUCKY_NUMBER, - luckyNumberObject.date.value.toLong(), - true, - profile.empty, - System.currentTimeMillis() - )) - } - } - - return@run null - }?.let { errorCode -> - data.error(ApiError(TAG, errorCode) - .withApiResponse(text) - .withResponse(response)) - return - } - - onSuccess() - return - } - - val errorText = Regexes.IDZIENNIK_LOGIN_ERROR.find(text)?.get(1) - when { - errorText?.contains("nieprawidłową nazwę szkoły") == true -> ERROR_LOGIN_IDZIENNIK_WEB_INVALID_SCHOOL_NAME - errorText?.contains("nieprawidłowy login lub hasło") == true -> ERROR_LOGIN_IDZIENNIK_WEB_INVALID_LOGIN - text.contains("Identyfikator zgłoszenia") -> ERROR_LOGIN_IDZIENNIK_WEB_SERVER_ERROR - text.contains("Hasło dostępu do systemu wygasło") -> ERROR_LOGIN_IDZIENNIK_WEB_PASSWORD_CHANGE_NEEDED - text.contains("Trwają prace konserwacyjne") -> ERROR_LOGIN_IDZIENNIK_WEB_MAINTENANCE - else -> ERROR_LOGIN_IDZIENNIK_WEB_OTHER - }.let { errorCode -> - data.error(ApiError(TAG, errorCode) - .withApiResponse(text) - .withResponse(response)) - return - } - } - - override fun onFailure(response: Response?, throwable: Throwable?) { - data.error(ApiError(TAG, ERROR_REQUEST_FAILURE) - .withResponse(response) - .withThrowable(throwable)) - } - } - - val getCallback = object : TextCallbackHandler() { - override fun onSuccess(text: String?, response: Response?) { - Request.builder() - .url("$IDZIENNIK_WEB_URL/$IDZIENNIK_WEB_LOGIN") - .userAgent(IDZIENNIK_USER_AGENT) - .addHeader("Origin", "https://iuczniowie.progman.pl") - .addHeader("Referer", "$IDZIENNIK_WEB_URL/$IDZIENNIK_WEB_LOGIN") - .apply { - Regexes.IDZIENNIK_LOGIN_HIDDEN_FIELDS.findAll(text ?: return@apply).forEach { - addParameter(it[1], it[2]) - } - } - .addParameter("ctl00\$ContentPlaceHolder\$nazwaPrzegladarki", IDZIENNIK_USER_AGENT) - .addParameter("ctl00\$ContentPlaceHolder\$NazwaSzkoly", data.webSchoolName) - .addParameter("ctl00\$ContentPlaceHolder\$UserName", data.webUsername) - .addParameter("ctl00\$ContentPlaceHolder\$Password", data.webPassword) - .addParameter("ctl00\$ContentPlaceHolder\$captcha", "") - .addParameter("ctl00\$ContentPlaceHolder\$Logowanie", "Zaloguj") - .post() - .allowErrorCode(502) - .callback(loginCallback) - .build() - .enqueue() - } - - override fun onFailure(response: Response?, throwable: Throwable?) { - data.error(ApiError(TAG, ERROR_REQUEST_FAILURE) - .withResponse(response) - .withThrowable(throwable)) - } - } - - Request.builder() - .url("$IDZIENNIK_WEB_URL/$IDZIENNIK_WEB_LOGIN") - .userAgent(IDZIENNIK_USER_AGENT) - .get() - .allowErrorCode(502) - .callback(getCallback) - .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 index 80a85a9f..5d82191d 100644 --- 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 @@ -5,7 +5,6 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.librus import pl.szczodrzynski.edziennik.App -import pl.szczodrzynski.edziennik.currentTimeUnix 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 @@ -13,7 +12,8 @@ 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.isNotNullNorEmpty +import pl.szczodrzynski.edziennik.ext.currentTimeUnix +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty class DataLibrus(app: App, profile: Profile?, loginStore: LoginStore) : Data(app, profile, loginStore) { @@ -120,7 +120,7 @@ class DataLibrus(app: App, profile: Profile?, loginStore: LoginStore) : Data(app private var mApiLogin: String? = null var apiLogin: String? get() { mApiLogin = mApiLogin ?: profile?.getStudentData("accountLogin", null); return mApiLogin } - set(value) { profile?.putStudentData("accountLogin", value) ?: return; mApiLogin = value } + set(value) { profile?.putStudentData("accountLogin", value); mApiLogin = value } /** * A Synergia password. * Used: for login (API Login Method) in Synergia mode. @@ -129,7 +129,7 @@ class DataLibrus(app: App, profile: Profile?, loginStore: LoginStore) : Data(app private var mApiPassword: String? = null var apiPassword: String? get() { mApiPassword = mApiPassword ?: profile?.getStudentData("accountPassword", null); return mApiPassword } - set(value) { profile?.putStudentData("accountPassword", value) ?: return; mApiPassword = value } + set(value) { profile?.putStudentData("accountPassword", value); mApiPassword = value } /** * A JST login Code. @@ -138,8 +138,7 @@ class DataLibrus(app: App, profile: Profile?, loginStore: LoginStore) : Data(app private var mApiCode: String? = null var apiCode: String? get() { mApiCode = mApiCode ?: loginStore.getLoginData("accountCode", null); return mApiCode } - set(value) { - loginStore.putLoginData("accountCode", value); mApiCode = value } + set(value) { profile?.putStudentData("accountCode", value); mApiCode = value } /** * A JST login PIN. * Used only during first login in JST mode. @@ -147,8 +146,7 @@ class DataLibrus(app: App, profile: Profile?, loginStore: LoginStore) : Data(app private var mApiPin: String? = null var apiPin: String? get() { mApiPin = mApiPin ?: loginStore.getLoginData("accountPin", null); return mApiPin } - set(value) { - loginStore.putLoginData("accountPin", value); mApiPin = value } + set(value) { profile?.putStudentData("accountPin", value); mApiPin = value } /** * A Synergia API access token. @@ -277,4 +275,10 @@ class DataLibrus(app: App, profile: Profile?, loginStore: LoginStore) : Data(app 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 index 0a1ed593..0830752f 100644 --- 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 @@ -13,9 +13,10 @@ import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages.Librus 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.LibrusSynergiaMarkAllAnnouncementsAsRead +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.events.UserActionRequiredEvent import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikCallback import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikInterface import pl.szczodrzynski.edziennik.data.api.models.ApiError @@ -24,6 +25,7 @@ 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 @@ -88,9 +90,8 @@ class Librus(val app: App, val profile: Profile?, val loginStore: LoginStore, va override fun getMessage(message: MessageFull) { login(LOGIN_METHOD_LIBRUS_MESSAGES) { - LibrusMessagesGetMessage(data, message) { - completed() - } + if (data.messagesLoginSuccessful) LibrusMessagesGetMessage(data, message) { completed() } + else LibrusSynergiaGetMessage(data, message) { completed() } } } @@ -118,11 +119,22 @@ class Librus(val app: App, val profile: Profile?, val loginStore: LoginStore, va } } - override fun getAttachment(message: Message, attachmentId: Long, attachmentName: String) { - login(LOGIN_METHOD_LIBRUS_MESSAGES) { - LibrusMessagesGetAttachment(data, message, attachmentId, attachmentName) { - 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() } } @@ -134,6 +146,14 @@ class Librus(val app: App, val profile: Profile?, val loginStore: LoginStore, va } } + 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") @@ -143,6 +163,7 @@ class Librus(val app: App, val profile: Profile?, val loginStore: LoginStore, va private fun wrapCallback(callback: EdziennikCallback): EdziennikCallback { return object : EdziennikCallback { override fun onCompleted() { callback.onCompleted() } + override fun onRequiresUserAction(event: UserActionRequiredEvent) { callback.onRequiresUserAction(event) } override fun onProgress(step: Float) { callback.onProgress(step) } override fun onStartProgress(stringRes: Int) { callback.onStartProgress(stringRes) } override fun onError(apiError: 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 index 98caab4e..c14a00df 100644 --- 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 @@ -50,6 +50,8 @@ 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 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 index d06cc219..2b736a0f 100644 --- 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 @@ -11,7 +11,7 @@ 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.getString +import pl.szczodrzynski.edziennik.ext.getString import pl.szczodrzynski.edziennik.utils.Utils.d import java.net.HttpURLConnection.* 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 index bf1fdab4..db72ddcc 100644 --- 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 @@ -8,6 +8,7 @@ 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 @@ -181,10 +182,6 @@ class LibrusData(val data: DataLibrus, val onSuccess: () -> Unit) { data.startProgress(R.string.edziennik_progress_endpoint_pt_meetings) LibrusApiPtMeetings(data, lastSync, onSuccess) } - ENDPOINT_LIBRUS_API_TEACHER_FREE_DAY_TYPES -> { - data.startProgress(R.string.edziennik_progress_endpoint_teacher_free_day_types) - LibrusApiTeacherFreeDayTypes(data, lastSync, onSuccess) - } ENDPOINT_LIBRUS_API_TEACHER_FREE_DAYS -> { data.startProgress(R.string.edziennik_progress_endpoint_teacher_free_days) LibrusApiTeacherFreeDays(data, lastSync, onSuccess) @@ -201,17 +198,27 @@ class LibrusData(val data: DataLibrus, val onSuccess: () -> Unit) { 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) - LibrusMessagesGetList(data, type = Message.TYPE_RECEIVED, lastSync = lastSync, onSuccess = onSuccess) + 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) - LibrusMessagesGetList(data, type = Message.TYPE_SENT, lastSync = lastSync, onSuccess = onSuccess) + 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 index bccaa1f9..dc8d8c47 100644 --- 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 @@ -252,10 +252,11 @@ open class LibrusMessages(open val data: DataLibrus, open val lastSync: Long?) { .enqueue() } - fun sandboxGetFile(tag: String, action: String, targetFile: File, onSuccess: (file: File) -> Unit, + 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 - $LIBRUS_SANDBOX_URL$action") + d(tag, "Request: Librus/Messages - $url") val callback = object : FileCallbackHandler(targetFile) { override fun onSuccess(file: File?, response: Response?) { @@ -291,9 +292,14 @@ open class LibrusMessages(open val data: DataLibrus, open val lastSync: Long?) { } Request.builder() - .url("$LIBRUS_SANDBOX_URL$action") + .url(url) .userAgent(SYNERGIA_USER_AGENT) - .post() + .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 index 4a5e0af6..d1d34226 100644 --- 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 @@ -7,7 +7,7 @@ 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.getString +import pl.szczodrzynski.edziennik.ext.getString import pl.szczodrzynski.edziennik.utils.Utils.d import java.net.HttpURLConnection 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 index e201ca8f..72faf801 100644 --- 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 @@ -35,7 +35,7 @@ open class LibrusSynergia(open val data: DataLibrus, open val lastSync: Long?) { return } - if (!text.contains("jesteś zalogowany")) { + 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 @@ -48,7 +48,6 @@ open class LibrusSynergia(open val data: DataLibrus, open val lastSync: Long?) { } } - try { onSuccess(text) } catch (e: Exception) { @@ -90,4 +89,44 @@ open class LibrusSynergia(open val data: DataLibrus, open val lastSync: Long?) { .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 index d40c1a9a..23cfceb4 100644 --- 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 @@ -37,8 +37,7 @@ class LibrusApiAnnouncementMarkAsRead(override val data: DataLibrus, Metadata.TYPE_ANNOUNCEMENT, announcement.id, announcement.seen, - announcement.notified, - announcement.addedDate + 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 index 8256b859..fcf68cad 100644 --- 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 @@ -11,6 +11,7 @@ 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, @@ -38,15 +39,17 @@ class LibrusApiAnnouncements(override val data: DataLibrus, val read = announcement.getBoolean("WasRead") ?: false val announcementObject = Announcement( - profileId, - id, - subject, - text, - startDate, - endDate, - teacherId, - longId - ) + 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( @@ -54,8 +57,7 @@ class LibrusApiAnnouncements(override val data: DataLibrus, Metadata.TYPE_ANNOUNCEMENT, id, read, - profile.empty || read, - addedDate + profile.empty || read )) } 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 index d7cbc00c..417a1de0 100644 --- 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 @@ -11,6 +11,7 @@ import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_ 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?, @@ -26,25 +27,39 @@ class LibrusApiAttendanceTypes(override val data: DataLibrus, attendanceTypes?.forEach { attendanceType -> val id = attendanceType.getLong("Id") ?: return@forEach - val name = attendanceType.getString("Name") ?: "" - val color = attendanceType.getString("ColorRGB")?.let { Color.parseColor("#$it") } ?: -1 - val standardId = when (attendanceType.getBoolean("Standard") ?: false) { - true -> id - false -> attendanceType.getJsonObject("StandardType")?.getLong("Id") ?: id - } - val type = when (standardId) { + 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 -> Attendance.TYPE_PRESENT + /*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, name, type, color)) + data.attendanceTypes.put(id, AttendanceType( + profileId, + id, + baseType, + typeName, + typeShort, + typeSymbol, + typeColor + )) } - data.setSyncNext(ENDPOINT_LIBRUS_API_ATTENDANCE_TYPES, 4*DAY) + 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 index 3727788d..314a0716 100644 --- 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 @@ -12,8 +12,8 @@ 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 -import pl.szczodrzynski.edziennik.utils.models.Time class LibrusApiAttendances(override val data: DataLibrus, override val lastSync: Long?, @@ -42,9 +42,9 @@ class LibrusApiAttendances(override val data: DataLibrus, val lessonDate = Date.fromY_m_d(attendance.getString("Date")) val teacherId = attendance.getJsonObject("AddedBy")?.getLong("Id") val semester = attendance.getInt("Semester") ?: return@forEach - val type = attendance.getJsonObject("Type")?.getLong("Id") ?: return@forEach - val typeObject = data.attendanceTypes[type] ?: null - val topic = typeObject?.name ?: "" + + val typeId = attendance.getJsonObject("Type")?.getLong("Id") ?: return@forEach + val type = data.attendanceTypes[typeId] ?: null val startTime = data.lessonRanges.get(lessonNo)?.startTime @@ -52,29 +52,34 @@ class LibrusApiAttendances(override val data: DataLibrus, data.librusLessons.singleOrNull { it.lessonId == lessonId } else null - val attendanceObject = Attendance( - profileId, - id, - teacherId ?: lesson?.teacherId ?: -1, - lesson?.subjectId ?: -1, - semester, - topic, - lessonDate, - startTime ?: Time(0, 0, 0), - typeObject?.type ?: Attendance.TYPE_CUSTOM - ) - 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(typeObject?.type != Attendance.TYPE_PRESENT) { + if(type?.baseType != Attendance.TYPE_PRESENT) { data.metadataList.add(Metadata( profileId, Metadata.TYPE_ATTENDANCE, id, - profile?.empty ?: false, - profile?.empty ?: false, - addedDate + 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 )) } } 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 index 650dfbb5..24992be1 100644 --- 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 @@ -10,6 +10,7 @@ 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?, 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 index eedb1d1d..4f44c0f0 100644 --- 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 @@ -10,6 +10,7 @@ import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_ 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?, 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 index 5a374ec9..7a528407 100644 --- 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 @@ -14,6 +14,7 @@ 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 @@ -55,7 +56,8 @@ class LibrusApiBehaviourGrades(override val data: DataLibrus, comment = null, semester = 1, teacherId = -1, - subjectId = 1 + subjectId = 1, + addedDate = profile.getSemesterStart(1).inMillis ) data.gradeList.add(semester1StartGradeObject) @@ -64,8 +66,7 @@ class LibrusApiBehaviourGrades(override val data: DataLibrus, Metadata.TYPE_GRADE, semester1StartGradeObject.id, true, - true, - profile.getSemesterStart(1).inMillis + true )) } @@ -83,7 +84,8 @@ class LibrusApiBehaviourGrades(override val data: DataLibrus, comment = null, semester = 2, teacherId = -1, - subjectId = 1 + subjectId = 1, + addedDate = profile.getSemesterStart(2).inMillis ) data.gradeList.add(semester2StartGradeObject) @@ -92,8 +94,7 @@ class LibrusApiBehaviourGrades(override val data: DataLibrus, Metadata.TYPE_GRADE, semester2StartGradeObject.id, true, - true, - profile.getSemesterStart(2).inMillis + true )) } @@ -155,7 +156,8 @@ class LibrusApiBehaviourGrades(override val data: DataLibrus, comment = if (text != null) description.join(" - ") else null, semester = semester, teacherId = teacherId, - subjectId = 1 + subjectId = 1, + addedDate = addedDate ).apply { valueMax = valueTo } @@ -166,8 +168,7 @@ class LibrusApiBehaviourGrades(override val data: DataLibrus, Metadata.TYPE_GRADE, id, profile.empty, - profile.empty, - addedDate + profile.empty )) } 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 index 171e80e1..43baf873 100644 --- 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 @@ -4,14 +4,14 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api -import pl.szczodrzynski.edziennik.DAY 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.getJsonObject -import pl.szczodrzynski.edziennik.getLong -import pl.szczodrzynski.edziennik.getString +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, 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 index 80a11105..6fbebca5 100644 --- 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 @@ -9,6 +9,7 @@ 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, @@ -25,8 +26,8 @@ class LibrusApiClassrooms(override val data: DataLibrus, classrooms?.forEach { classroom -> val id = classroom.getLong("Id") ?: return@forEach - val name = classroom.getString("Name")?.toLowerCase(Locale.getDefault()) ?: "" - val symbol = classroom.getString("Symbol")?.toLowerCase(Locale.getDefault()) ?: "" + 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(" ") @@ -40,7 +41,7 @@ class LibrusApiClassrooms(override val data: DataLibrus, data.classrooms.put(id, Classroom(profileId, id, friendlyName)) } - data.setSyncNext(ENDPOINT_LIBRUS_API_CLASSROOMS, 4*DAY) + 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 index 94ce6972..c48d34f8 100644 --- 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 @@ -10,6 +10,7 @@ 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?, 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 index 42e318e0..9b214d04 100644 --- 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 @@ -15,6 +15,7 @@ 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, @@ -65,7 +66,8 @@ class LibrusApiDescriptiveGrades(override val data: DataLibrus, comment = null, semester = semester, teacherId = teacherId, - subjectId = subjectId + subjectId = subjectId, + addedDate = addedDate ) data.gradeList.add(gradeObject) @@ -74,8 +76,7 @@ class LibrusApiDescriptiveGrades(override val data: DataLibrus, Metadata.TYPE_GRADE, id, profile.empty, - profile.empty, - addedDate + profile.empty )) } 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 index 331b8249..c2129ba6 100644 --- 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 @@ -9,6 +9,7 @@ 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?, @@ -30,7 +31,7 @@ class LibrusApiEventTypes(override val data: DataLibrus, data.eventTypes.put(id, EventType(profileId, id, name, color)) } - data.setSyncNext(ENDPOINT_LIBRUS_API_EVENT_TYPES, 4*DAY) + 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 index a04c2863..82a0e267 100644 --- 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 @@ -13,6 +13,7 @@ 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 @@ -35,7 +36,7 @@ class LibrusApiEvents(override val data: DataLibrus, events?.forEach { event -> val id = event.getLong("Id") ?: return@forEach val eventDate = Date.fromY_m_d(event.getString("Date")) - val topic = event.getString("Content") ?: "" + 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 @@ -46,18 +47,24 @@ class LibrusApiEvents(override val data: DataLibrus, 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, - id, - eventDate, - startTime, - topic, - -1, - type, - false, - teacherId, - subjectId, - teamId + 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) @@ -67,8 +74,7 @@ class LibrusApiEvents(override val data: DataLibrus, Metadata.TYPE_EVENT, id, profile?.empty ?: false, - profile?.empty ?: false, - addedDate + profile?.empty ?: false )) } 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 index 518e643f..c6c4fecc 100644 --- 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 @@ -11,6 +11,7 @@ import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_ 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?, 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 index 971ac35b..96225b67 100644 --- 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 @@ -10,6 +10,7 @@ import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_ 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?, 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 index 7ff42fde..58621a0e 100644 --- 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 @@ -16,6 +16,7 @@ import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_YEAR_PROPO 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 @@ -79,7 +80,8 @@ class LibrusApiGrades(override val data: DataLibrus, comment = null, semester = semester, teacherId = teacherId, - subjectId = subjectId + subjectId = subjectId, + addedDate = addedDate ) grade.getJsonObject("Improvement")?.also { @@ -98,8 +100,7 @@ class LibrusApiGrades(override val data: DataLibrus, Metadata.TYPE_GRADE, id, profile.empty, - profile.empty, - addedDate + profile.empty )) } 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 index 16d66c6f..f304aaad 100644 --- 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 @@ -12,6 +12,7 @@ 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, @@ -34,17 +35,17 @@ class LibrusApiHomework(override val data: DataLibrus, val addedDate = Date.fromY_m_d(homework.getString("Date")) val eventObject = Event( - profileId, - id, - eventDate, - null, - topic, - -1, - -1, - false, - teacherId, - -1, - -1 + 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) @@ -53,8 +54,7 @@ class LibrusApiHomework(override val data: DataLibrus, Metadata.TYPE_HOMEWORK, id, profile?.empty ?: false, - profile?.empty ?: false, - addedDate.inMillis + profile?.empty ?: false )) } 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 index e32790c9..66075008 100644 --- 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 @@ -9,6 +9,7 @@ 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?, @@ -39,7 +40,7 @@ class LibrusApiLessons(override val data: DataLibrus, data.librusLessons.put(id, librusLesson) } - data.setSyncNext(ENDPOINT_LIBRUS_API_LESSONS, 4*DAY) + 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 index 5a52cd69..6ebe9e63 100644 --- 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 @@ -4,12 +4,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_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 @@ -22,7 +22,7 @@ class LibrusApiLuckyNumber(override val data: DataLibrus, } init { - var nextSync = System.currentTimeMillis() + 2*DAY*1000 + var nextSync = System.currentTimeMillis() + 2* DAY *1000 apiGet(TAG, "LuckyNumbers") { json -> if (json.isJsonNull) { @@ -33,15 +33,15 @@ class LibrusApiLuckyNumber(override val data: DataLibrus, val luckyNumberDate = Date.fromY_m_d(luckyNumberEl.getString("LuckyNumberDay")) ?: Date.getToday() val luckyNumber = luckyNumberEl.getInt("LuckyNumber") ?: -1 val luckyNumberObject = LuckyNumber( - profileId, - luckyNumberDate, - 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 + nextSync = System.currentTimeMillis() + 6* HOUR *1000 data.luckyNumberList.add(luckyNumberObject) data.metadataList.add( @@ -50,8 +50,7 @@ class LibrusApiLuckyNumber(override val data: DataLibrus, Metadata.TYPE_LUCKY_NUMBER, luckyNumberObject.date.value.toLong(), true, - profile?.empty ?: false, - System.currentTimeMillis() + profile?.empty ?: false )) } } 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 index 9d5ce1d4..ea46971f 100644 --- 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 @@ -4,10 +4,10 @@ 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_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?, @@ -34,7 +34,7 @@ class LibrusApiMe(override val data: DataLibrus, data.profile?.studentNameLong = buildFullName(user?.getString("FirstName"), user?.getString("LastName")) - data.setSyncNext(ENDPOINT_LIBRUS_API_ME, 2*DAY) + 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 index 55e753ee..7e90fbb2 100644 --- 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 @@ -9,6 +9,7 @@ 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?, @@ -29,7 +30,7 @@ class LibrusApiNoticeTypes(override val data: DataLibrus, data.noticeTypes.put(id, NoticeType(profileId, id, name)) } - data.setSyncNext(ENDPOINT_LIBRUS_API_NOTICE_TYPES, 4*DAY) + 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 index e05cbfd7..ea61428e 100644 --- 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 @@ -12,6 +12,7 @@ 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, @@ -46,12 +47,15 @@ class LibrusApiNotices(override val data: DataLibrus, val semester = profile?.dateToSemester(addedDate) ?: 1 val noticeObject = Notice( - profileId, - id, - categoryText + "\n" + text, - semester, - type, - teacherId + profileId = profileId, + id = id, + type = type, + semester = semester, + text = text, + category = categoryText, + points = null, + teacherId = teacherId, + addedDate = addedDate.inMillis ) data.noticeList.add(noticeObject) @@ -61,8 +65,7 @@ class LibrusApiNotices(override val data: DataLibrus, Metadata.TYPE_NOTICE, id, profile?.empty ?: false, - profile?.empty ?: false, - addedDate.inMillis + profile?.empty ?: false )) } 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 index bba6ead9..775f0897 100644 --- 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 @@ -10,6 +10,7 @@ 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?, 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 index fae45318..8a7ad29f 100644 --- 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 @@ -14,6 +14,7 @@ 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, @@ -56,7 +57,8 @@ class LibrusApiPointGrades(override val data: DataLibrus, comment = null, semester = semester, teacherId = teacherId, - subjectId = subjectId + subjectId = subjectId, + addedDate = addedDate ).apply { valueMax = category?.valueTo ?: 0f } @@ -67,8 +69,7 @@ class LibrusApiPointGrades(override val data: DataLibrus, Metadata.TYPE_GRADE, id, profile.empty, - profile.empty, - addedDate + profile.empty )) } 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 index 3a58d8e1..170c6135 100644 --- 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 @@ -11,6 +11,7 @@ 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 @@ -39,17 +40,16 @@ class LibrusApiPtMeetings(override val data: DataLibrus, } val eventObject = Event( - profileId, - id, - eventDate, - startTime, - topic, - -1, - Event.TYPE_PT_MEETING, - false, - teacherId, - -1, - data.teamClass?.id ?: -1 + 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) @@ -59,14 +59,13 @@ class LibrusApiPtMeetings(override val data: DataLibrus, Metadata.TYPE_EVENT, id, profile?.empty ?: false, - profile?.empty ?: false, - System.currentTimeMillis() + profile?.empty ?: false )) } data.toRemove.add(DataRemoveModel.Events.futureWithType(Event.TYPE_PT_MEETING)) - data.setSyncNext(ENDPOINT_LIBRUS_API_PT_MEETINGS, 12*HOUR) + 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 index 9073d03f..5dac1841 100644 --- 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 @@ -4,13 +4,13 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.api -import pl.szczodrzynski.edziennik.JsonObject 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.getInt -import pl.szczodrzynski.edziennik.getJsonObject +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?, 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 index d405f9bf..e42ab949 100644 --- 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 @@ -9,6 +9,7 @@ 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.* @@ -29,7 +30,7 @@ class LibrusApiSchools(override val data: DataLibrus, // 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")?.toLowerCase(Locale.getDefault()) + val schoolTown = school?.getString("Town")?.lowercase() data.schoolName = schoolId.toString() + schoolNameShort + "_" + schoolTown school?.getJsonArray("LessonsRange")?.let { ranges -> 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 index cfd9bd31..17e30559 100644 --- 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 @@ -9,6 +9,7 @@ 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?, @@ -32,7 +33,7 @@ class LibrusApiSubjects(override val data: DataLibrus, data.subjectList.put(1, Subject(profileId, 1, "Zachowanie", "zach")) - data.setSyncNext(ENDPOINT_LIBRUS_API_SUBJECTS, 4*DAY) + 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/LibrusApiTeacherFreeDayTypes.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTeacherFreeDayTypes.kt deleted file mode 100644 index e09504bf..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTeacherFreeDayTypes.kt +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-10-19 - */ - -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_TEACHER_FREE_DAY_TYPES -import pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.LibrusApi -import pl.szczodrzynski.edziennik.data.db.entity.TeacherAbsenceType - -class LibrusApiTeacherFreeDayTypes(override val data: DataLibrus, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : LibrusApi(data, lastSync) { - companion object { - const val TAG = "LibrusApiTeacherFreeDayTypes" - } - - init { - apiGet(TAG, "TeacherFreeDays/Types") { json -> - val teacherAbsenceTypes = json.getJsonArray("Types")?.asJsonObjectList() - - teacherAbsenceTypes?.forEach { teacherAbsenceType -> - val id = teacherAbsenceType.getLong("Id") ?: return@forEach - val name = teacherAbsenceType.getString("Name") ?: return@forEach - - val teacherAbsenceTypeObject = TeacherAbsenceType( - profileId, - id, - name - ) - - data.teacherAbsenceTypes.put(id, teacherAbsenceTypeObject) - } - - data.setSyncNext(ENDPOINT_LIBRUS_API_TEACHER_FREE_DAY_TYPES, 7 * DAY) - onSuccess(ENDPOINT_LIBRUS_API_TEACHER_FREE_DAY_TYPES) - } - } -} 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 index 04c44efb..09ed5416 100644 --- 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 @@ -12,6 +12,7 @@ import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_API_ 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 @@ -35,23 +36,21 @@ class LibrusApiTeacherFreeDays(override val data: DataLibrus, val id = teacherAbsence.getLong("Id") ?: return@forEach val teacherId = teacherAbsence.getJsonObject("Teacher")?.getLong("Id") ?: return@forEach - val type = teacherAbsence.getJsonObject("Type").getLong("Id") ?: return@forEach - val name = data.teacherAbsenceTypes.singleOrNull { it.id == type }?.name 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, - id, - teacherId, - type, - name, - dateFrom, - dateTo, - timeFrom, - timeTo + profileId = profileId, + id = id, + type = -1L, + name = null, + dateFrom = dateFrom, + dateTo = dateTo, + timeFrom = timeFrom, + timeTo = timeTo, + teacherId = teacherId ) data.teacherAbsenceList.add(teacherAbsenceObject) @@ -59,13 +58,12 @@ class LibrusApiTeacherFreeDays(override val data: DataLibrus, profileId, Metadata.TYPE_TEACHER_ABSENCE, id, - profile?.empty ?: false, - profile?.empty ?: false, - System.currentTimeMillis() + true, + profile?.empty ?: false )) } - data.setSyncNext(ENDPOINT_LIBRUS_API_TEACHER_FREE_DAYS, 6*HOUR, DRAWER_ITEM_AGENDA) + 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/LibrusApiTextGradeCategories.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/librus/data/api/LibrusApiTextGradeCategories.kt index 45b6b069..441e3b60 100644 --- 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 @@ -10,6 +10,7 @@ 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?, 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 index cf020425..bb19f11f 100644 --- 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 @@ -14,6 +14,7 @@ import pl.szczodrzynski.edziennik.data.db.entity.Grade.Companion.TYPE_DESCRIPTIV 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, @@ -60,7 +61,8 @@ class LibrusApiTextGrades(override val data: DataLibrus, comment = grade.getString("Phrase") /* whatever it is */, semester = semester, teacherId = teacherId, - subjectId = subjectId + subjectId = subjectId, + addedDate = addedDate ) data.gradeList.add(gradeObject) @@ -69,8 +71,7 @@ class LibrusApiTextGrades(override val data: DataLibrus, Metadata.TYPE_GRADE, id, profile.empty, - profile.empty, - addedDate + profile.empty )) } 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 index 7c1eec61..b224a381 100644 --- 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 @@ -14,6 +14,7 @@ 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 @@ -198,8 +199,7 @@ class LibrusApiTimetables(override val data: DataLibrus, Metadata.TYPE_LESSON_CHANGE, lessonObject.id, seen, - seen, - System.currentTimeMillis() + 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 index 791283ed..03fcf4a5 100644 --- 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 @@ -8,6 +8,7 @@ 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?, 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 index 0ac9a5ea..fb82849f 100644 --- 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 @@ -9,6 +9,7 @@ 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?, @@ -37,7 +38,7 @@ class LibrusApiUsers(override val data: DataLibrus, data.teacherList.put(id, teacher) } - data.setSyncNext(ENDPOINT_LIBRUS_API_USERS, 4*DAY) + 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 index 9937f808..2d6a7958 100644 --- 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 @@ -9,6 +9,7 @@ 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?, @@ -31,7 +32,7 @@ class LibrusApiVirtualClasses(override val data: DataLibrus, data.teamList.put(id, Team(profileId, id, name, 2, code, teacherId)) } - data.setSyncNext(ENDPOINT_LIBRUS_API_VIRTUAL_CLASSES, 4*DAY) + 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 index f7234891..b54e704b 100644 --- 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 @@ -4,22 +4,12 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages -import kotlinx.coroutines.* -import org.greenrobot.eventbus.EventBus -import pl.szczodrzynski.edziennik.data.api.ERROR_FILE_DOWNLOAD -import pl.szczodrzynski.edziennik.data.api.EXCEPTION_LIBRUS_MESSAGES_REQUEST -import pl.szczodrzynski.edziennik.data.api.Regexes +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.api.events.AttachmentGetEvent -import pl.szczodrzynski.edziennik.data.api.events.AttachmentGetEvent.Companion.TYPE_FINISHED -import pl.szczodrzynski.edziennik.data.api.events.AttachmentGetEvent.Companion.TYPE_PROGRESS -import pl.szczodrzynski.edziennik.data.api.models.ApiError import pl.szczodrzynski.edziennik.data.db.entity.Message -import pl.szczodrzynski.edziennik.get -import pl.szczodrzynski.edziennik.getString -import pl.szczodrzynski.edziennik.utils.Utils -import java.io.File import kotlin.coroutines.CoroutineContext class LibrusMessagesGetAttachment(override val data: DataLibrus, @@ -37,8 +27,6 @@ class LibrusMessagesGetAttachment(override val data: DataLibrus, override val coroutineContext: CoroutineContext get() = job + Dispatchers.Default - private var getAttachmentCheckKeyTries = 0 - init { messagesGet(TAG, "GetFileDownloadLink", parameters = mapOf( "fileId" to attachmentId, @@ -46,81 +34,8 @@ class LibrusMessagesGetAttachment(override val data: DataLibrus, "archive" to 0 )) { doc -> val downloadLink = doc.select("response GetFileDownloadLink downloadLink").text() - val keyMatcher = Regexes.LIBRUS_ATTACHMENT_KEY.find(downloadLink) - if (keyMatcher != null) { - getAttachmentCheckKeyTries = 0 - - val attachmentKey = keyMatcher[1] - getAttachmentCheckKey(attachmentKey) { - downloadAttachment(attachmentKey) - } - } else { - data.error(ApiError(TAG, ERROR_FILE_DOWNLOAD) - .withApiResponse(doc.toString())) - } - } - } - - 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(attachmentKey: String) { - val targetFile = File(Utils.getStorageDir(), attachmentName) - - sandboxGetFile(TAG, "CSDownload&singleUseKey=$attachmentKey", targetFile, { file -> - - val event = AttachmentGetEvent( - profileId, - message.id, - attachmentId, - TYPE_FINISHED, - file.absolutePath - ) - - val attachmentDataFile = File(Utils.getStorageDir(), ".${profileId}_${event.messageId}_${event.attachmentId}") - Utils.writeStringToFile(attachmentDataFile, event.fileName) - - EventBus.getDefault().post(event) - - onSuccess() - - }) { written, _ -> - val event = AttachmentGetEvent( - profileId, - message.id, - attachmentId, - TYPE_PROGRESS, - bytesWritten = written - ) - - EventBus.getDefault().post(event) + 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 index f4aa2b3a..7d0cfeef 100644 --- 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 @@ -4,7 +4,6 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages -import pl.szczodrzynski.edziennik.DAY 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 @@ -12,9 +11,10 @@ import pl.szczodrzynski.edziennik.data.api.edziennik.librus.ENDPOINT_LIBRUS_MESS 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.TYPE_RECEIVED -import pl.szczodrzynski.edziennik.fixName -import pl.szczodrzynski.edziennik.singleOrNull +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 @@ -78,7 +78,7 @@ class LibrusMessagesGetList(override val data: DataLibrus, val senderId = when (type) { TYPE_RECEIVED -> recipientId - else -> -1 + else -> null } val receiverId = when (type) { @@ -92,13 +92,13 @@ class LibrusMessagesGetList(override val data: DataLibrus, } val messageObject = Message( - profileId, - id, - subject, - null, - type, - senderId, - -1 + profileId = profileId, + id = id, + type = type, + subject = subject, + body = null, + senderId = senderId, + addedDate = sentDate ) val messageRecipientObject = MessageRecipient( @@ -109,15 +109,19 @@ class LibrusMessagesGetList(override val data: DataLibrus, id ) - data.messageIgnoreList.add(messageObject) + 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, - sentDate + notified )) } 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 index 824fdc5e..8e6435c6 100644 --- 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 @@ -9,16 +9,16 @@ 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.TYPE_RECEIVED -import pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_SENT +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.fixName -import pl.szczodrzynski.edziennik.isNotNullNorEmpty -import pl.szczodrzynski.edziennik.notEmptyOrNull -import pl.szczodrzynski.edziennik.singleOrNull +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 @@ -35,7 +35,7 @@ class LibrusMessagesGetMessage(override val data: DataLibrus, "messageId" to messageObject.id, "archive" to 0 )) { doc -> - val message = doc.select("response GetMessage data").first() + val message = doc.select("response GetMessage data").first() ?: return@messagesGet val body = Base64.decode(message.select("Message").text(), Base64.DEFAULT) .toString(Charset.defaultCharset()) @@ -102,14 +102,13 @@ class LibrusMessagesGetMessage(override val data: DataLibrus, } val messageRecipientObject = MessageRecipientFull( - profileId, - -1, - -1, - readDate, - messageObject.id + profileId = profileId, + id = -1, + messageId = messageObject.id, + readDate = readDate ) - messageRecipientObject.fullName = profile.accountName ?: profile.studentNameLong ?: "" + messageRecipientObject.fullName = profile.accountName ?: profile.studentNameLong messageRecipientList.add(messageRecipientObject) } @@ -132,11 +131,10 @@ class LibrusMessagesGetMessage(override val data: DataLibrus, } val messageRecipientObject = MessageRecipientFull( - profileId, - receiverId, - -1, - readDate, - messageObject.id + profileId = profileId, + id = receiverId, + messageId = messageObject.id, + readDate = readDate ) messageRecipientObject.fullName = "$receiverFirstName $receiverLastName" @@ -152,14 +150,15 @@ class LibrusMessagesGetMessage(override val data: DataLibrus, Metadata.TYPE_MESSAGE, messageObject.id, true, - true, - messageObject.addedDate + true )) } messageObject.recipients = messageRecipientList data.messageRecipientList.addAll(messageRecipientList) + data.messageList.add(messageObject) + data.messageListReplace = true EventBus.getDefault().postSticky(MessageGetEvent(messageObject)) 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 index 053258d8..b6881f17 100644 --- 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 @@ -14,6 +14,7 @@ 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 @@ -28,9 +29,9 @@ class LibrusMessagesGetRecipientList(override val data: DataLibrus, 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 + 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 } @@ -55,7 +56,7 @@ class LibrusMessagesGetRecipientList(override val data: DataLibrus, if (dataEl is JsonObject) { val listEl = dataEl.get("ArrayItem") if (listEl is JsonArray) { - listEl.asJsonObjectList()?.forEach { item -> + listEl.asJsonObjectList().forEach { item -> processElement(item, type.first, type.second) } } @@ -71,7 +72,7 @@ class LibrusMessagesGetRecipientList(override val data: DataLibrus, 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 -> + listEl.asJsonObjectList().let { list -> val label = element.getString("label") ?: "" list.forEach { item -> processElement(item, typeId, typeName, label) 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 index 02215dea..02248e99 100644 --- 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 @@ -5,16 +5,15 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.messages import org.greenrobot.eventbus.EventBus -import pl.szczodrzynski.edziennik.base64Encode 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.Metadata import pl.szczodrzynski.edziennik.data.db.entity.Teacher -import pl.szczodrzynski.edziennik.getJsonObject -import pl.szczodrzynski.edziennik.getLong -import pl.szczodrzynski.edziennik.getString +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, @@ -42,15 +41,15 @@ class LibrusMessagesSendMessage(override val data: DataLibrus, val id = response.getLong("data") if (response.getString("status") != "ok" || id == null) { - val message = response.getString("message") + // val message = response.getString("message") // TODO error return@messagesGetJson } LibrusMessagesGetList(data, type = Message.TYPE_SENT, lastSync = null) { - val message = data.messageIgnoreList.firstOrNull { it.type == Message.TYPE_SENT && it.id == id } - val metadata = data.metadataList.firstOrNull { it.thingType == Metadata.TYPE_MESSAGE && it.thingId == message?.id } - val event = MessageSentEvent(data.profileId, message, metadata?.addedDate) + 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/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 index 87cd88cf..ddf6635c 100644 --- 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 @@ -5,7 +5,6 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.synergia import org.jsoup.Jsoup -import pl.szczodrzynski.edziennik.HOUR 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 @@ -14,8 +13,9 @@ 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.get -import pl.szczodrzynski.edziennik.singleOrNull +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, @@ -42,9 +42,7 @@ class LibrusSynergiaHomework(override val data: DataLibrus, doc.select("table.myHomeworkTable > tbody").firstOrNull()?.also { homeworkTable -> val homeworkElements = homeworkTable.children() - val graphElements = doc.select("table[border].center td[align=left] tbody").first().children() - - homeworkElements.forEachIndexed { i, el -> + homeworkElements.forEach { el -> val elements = el.children() val subjectName = elements[0].text().trim() @@ -58,49 +56,30 @@ class LibrusSynergiaHomework(override val data: DataLibrus, 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@forEachIndexed + )?.get(1)?.toLong() ?: return@forEach - val lessons = data.db.timetableDao().getForDateNow(profileId, eventDate) + val lessons = data.db.timetableDao().getAllForDateNow(profileId, eventDate) val startTime = lessons.firstOrNull { it.subjectId == subjectId }?.startTime - /*val moreInfo = graphElements[2 * i + 1].select("td[title]") - .attr("title").trim()*/ - - var description = "" - - graphElements.forEach { graphEl -> - graphEl.select("td[title]")?.also { - val title = it.attr("title") - val r = "Temat: (.*?)Data udostępnienia: (.*?)Termin wykonania: (.*?)Treść: (.*)" - .toRegex(RegexOption.DOT_MATCHES_ALL).find(title) ?: return@forEach - val gTopic = r[1].trim() - val gAddedDate = Date.fromY_m_d(r[2].trim()) - val gEventDate = Date.fromY_m_d(r[3].trim()) - if (gTopic == topic && gAddedDate == addedDate && gEventDate == eventDate) { - description = r[4].replace("".toRegex(), "\n").trim() - return@forEach - } - } - } - val seen = when (profile.empty) { true -> true else -> eventDate < Date.getToday() } val eventObject = Event( - profileId, - id, - eventDate, - startTime, - "$topic\n$description", - -1, - Event.TYPE_HOMEWORK, - false, - teacherId, - subjectId, - data.teamClass?.id ?: -1 + 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( @@ -108,8 +87,7 @@ class LibrusSynergiaHomework(override val data: DataLibrus, Metadata.TYPE_HOMEWORK, id, seen, - seen, - addedDate.inMillis + seen )) } } 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 index 66e11785..74458fb5 100644 --- 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 @@ -5,10 +5,10 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.librus.data.synergia import org.jsoup.Jsoup -import pl.szczodrzynski.edziennik.MONTH 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?, 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 index f693c41a..43e5bda9 100644 --- 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 @@ -11,6 +11,7 @@ import pl.szczodrzynski.edziennik.data.api.edziennik.librus.login.LibrusLoginPor 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 { @@ -33,7 +34,7 @@ class LibrusFirstLogin(val data: DataLibrus, val onSuccess: () -> Unit) { val accounts = json.getJsonArray("accounts") if (accounts == null || accounts.size() < 1) { - EventBus.getDefault().post(FirstLoginFinishedEvent(listOf(), data.loginStore)) + EventBus.getDefault().postSticky(FirstLoginFinishedEvent(listOf(), data.loginStore)) onSuccess() return@portalGet } @@ -81,7 +82,7 @@ class LibrusFirstLogin(val data: DataLibrus, val onSuccess: () -> Unit) { profileList.add(profile) } - EventBus.getDefault().post(FirstLoginFinishedEvent(profileList, data.loginStore)) + EventBus.getDefault().postSticky(FirstLoginFinishedEvent(profileList, data.loginStore)) onSuccess() } } @@ -116,14 +117,15 @@ class LibrusFirstLogin(val data: DataLibrus, val onSuccess: () -> Unit) { ).apply { studentData["isPremium"] = account?.getBoolean("IsPremium") == true || account?.getBoolean("IsPremiumDemo") == true studentData["accountId"] = account.getInt("Id") ?: 0 - studentData["accountLogin"] = login + 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().post(FirstLoginFinishedEvent(profileList, data.loginStore)) + EventBus.getDefault().postSticky(FirstLoginFinishedEvent(profileList, data.loginStore)) onSuccess() } } 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 index fe155abe..58f7181d 100644 --- 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 @@ -12,12 +12,13 @@ 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.getInt -import pl.szczodrzynski.edziennik.getString -import pl.szczodrzynski.edziennik.getUnixDate +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" @@ -62,7 +63,7 @@ class LibrusLoginApi { } private fun copyFromLoginStore() { - data.loginStore.data?.apply { + data.loginStore.data.apply { if (has("accountLogin")) { data.apiLogin = getString("accountLogin") remove("accountLogin") 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 index ba8bcf76..2a61f641 100644 --- 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 @@ -10,8 +10,9 @@ 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.getUnixDate +import pl.szczodrzynski.edziennik.ext.getUnixDate import pl.szczodrzynski.edziennik.utils.Utils.d import java.io.StringWriter import javax.xml.parsers.DocumentBuilderFactory @@ -35,17 +36,39 @@ class LibrusLoginMessages(val data: DataLibrus, val onSuccess: () -> Unit) { 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) + 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) } } 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 index 166a4ae5..ab21c692 100644 --- 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 @@ -10,7 +10,9 @@ 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.events.UserActionRequiredEvent 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.* @@ -66,7 +68,7 @@ class LibrusLoginPortal(val data: DataLibrus, val onSuccess: () -> Unit) { override fun onSuccess(text: String, response: Response) { val location = response.headers().get("Location") if (location != null) { - val authMatcher = Pattern.compile("http://localhost/bar\\?code=([A-z0-9]+?)$", Pattern.DOTALL or Pattern.MULTILINE).matcher(location) + 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) @@ -83,7 +85,7 @@ class LibrusLoginPortal(val data: DataLibrus, val onSuccess: () -> Unit) { } else { val csrfMatcher = Pattern.compile("name=\"csrf-token\" content=\"([A-z0-9=+/\\-_]+?)\"", Pattern.DOTALL).matcher(text) if (csrfMatcher.find()) { - login(csrfMatcher.group(1)) + login(csrfMatcher.group(1) ?: "") } else { data.error(ApiError(TAG, ERROR_LOGIN_LIBRUS_PORTAL_CSRF_MISSING) .withResponse(response) @@ -127,7 +129,7 @@ class LibrusLoginPortal(val data: DataLibrus, val onSuccess: () -> Unit) { .callback(object : JsonCallbackHandler() { override fun onSuccess(json: JsonObject?, response: Response) { val location = response.headers()?.get("Location") - if (location == "http://localhost/bar?command=close") { + if (location == "$LIBRUS_REDIRECT_URL?command=close") { data.error(ApiError(TAG, ERROR_LIBRUS_PORTAL_MAINTENANCE) .withApiResponse(json) .withResponse(response)) @@ -146,12 +148,25 @@ class LibrusLoginPortal(val data: DataLibrus, val onSuccess: () -> Unit) { } val error = if (response.code() == 200) null else json.getJsonArray("errors")?.getString(0) + ?: json.getJsonObject("errors")?.entrySet()?.firstOrNull()?.value?.asString + + if (error?.contains("robotem") == true || json.getBoolean("captchaRequired") == true) { + data.requireUserAction( + type = UserActionRequiredEvent.Type.RECAPTCHA, + params = Bundle( + "siteKey" to LIBRUS_PORTAL_RECAPTCHA_KEY, + "referer" to LIBRUS_PORTAL_RECAPTCHA_REFERER, + ), + errorText = R.string.notification_user_action_required_captcha_librus, + ) + return + } + 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) @@ -160,12 +175,6 @@ class LibrusLoginPortal(val data: DataLibrus, val onSuccess: () -> Unit) { 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)) } 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 index 4a292cfe..a95af893 100644 --- 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 @@ -12,8 +12,8 @@ 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.getString -import pl.szczodrzynski.edziennik.getUnixDate +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.ext.getUnixDate import pl.szczodrzynski.edziennik.utils.Utils.d import java.net.HttpURLConnection 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 index 5072e5a2..807bb131 100644 --- 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 @@ -7,6 +7,7 @@ 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) { 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 index ddfb0113..cee3cda5 100644 --- 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 @@ -6,12 +6,14 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik import android.util.LongSparseArray import pl.szczodrzynski.edziennik.App -import pl.szczodrzynski.edziennik.currentTimeUnix 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.isNotNullNorEmpty +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 @@ -35,6 +37,31 @@ class DataMobidziennik(app: App, profile: Profile?, loginStore: LoginStore) : Da 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() 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 index 5e08f6c4..0144ad5d 100644 --- 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 @@ -8,20 +8,18 @@ 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.MobidziennikWebGetAttachment -import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.web.MobidziennikWebGetMessage -import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.web.MobidziennikWebGetRecipientList -import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.web.MobidziennikWebSendMessage +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.events.UserActionRequiredEvent 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 @@ -105,9 +103,9 @@ class Mobidziennik(val app: App, val profile: Profile?, val loginStore: LoginSto override fun markAllAnnouncementsAsRead() {} override fun getAnnouncement(announcement: AnnouncementFull) {} - override fun getAttachment(message: Message, attachmentId: Long, attachmentName: String) { + override fun getAttachment(owner: Any, attachmentId: Long, attachmentName: String) { login(LOGIN_METHOD_MOBIDZIENNIK_WEB) { - MobidziennikWebGetAttachment(data, message, attachmentId, attachmentName) { + MobidziennikWebGetAttachment(data, owner, attachmentId, attachmentName) { completed() } } @@ -121,6 +119,21 @@ class Mobidziennik(val app: App, val profile: Profile?, val loginStore: LoginSto } } + 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") @@ -130,6 +143,7 @@ class Mobidziennik(val app: App, val profile: Profile?, val loginStore: LoginSto private fun wrapCallback(callback: EdziennikCallback): EdziennikCallback { return object : EdziennikCallback { override fun onCompleted() { callback.onCompleted() } + override fun onRequiresUserAction(event: UserActionRequiredEvent) { callback.onRequiresUserAction(event) } override fun onProgress(step: Float) { callback.onProgress(step) } override fun onStartProgress(stringRes: Int) { callback.onStartProgress(stringRes) } override fun onError(apiError: 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 index d056fc4b..7b39e455 100644 --- 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 @@ -17,6 +17,8 @@ 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( @@ -37,6 +39,12 @@ val MobidziennikFeatures = listOf( + /** + * 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. */ 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 index 09e1e9fb..b82f6355 100644 --- 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 @@ -84,6 +84,10 @@ class MobidziennikData(val data: DataMobidziennik, val onSuccess: () -> Unit) { 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/api/MobidziennikApiAttendance.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiAttendance.kt index be68de4d..473b3691 100644 --- 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 @@ -6,7 +6,10 @@ 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.* +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) { @@ -23,7 +26,7 @@ class MobidziennikApiAttendance(val data: DataMobidziennik, rows: List) val id = cols[0].toLong() val lessonId = cols[1].toLong() data.mobiLessons.singleOrNull { it.id == lessonId }?.let { lesson -> - val type = when (cols[4]) { + val baseType = when (cols[4]) { "2" -> TYPE_ABSENT "5" -> TYPE_ABSENT_EXCUSED "4" -> TYPE_RELEASED @@ -31,16 +34,37 @@ class MobidziennikApiAttendance(val data: DataMobidziennik, rows: List) } 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( - data.profileId, - id, - lesson.teacherId, - lesson.subjectId, - semester, - lesson.topic, - lesson.date, - lesson.startTime, - type) + 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( @@ -48,9 +72,8 @@ class MobidziennikApiAttendance(val data: DataMobidziennik, rows: List) data.profileId, Metadata.TYPE_ATTENDANCE, id, - data.profile?.empty ?: false, - data.profile?.empty ?: false, - System.currentTimeMillis() + 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/MobidziennikApiEvents.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiEvents.kt index f5cb912b..7a72d3de 100644 --- 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 @@ -30,7 +30,7 @@ class MobidziennikApiEvents(val data: DataMobidziennik, rows: List) { val teacherId = cols[1].toLong() val subjectId = cols[3].toLong() var type = Event.TYPE_DEFAULT - var topic = cols[5] + var topic = cols[5].trim() Regexes.MOBIDZIENNIK_EVENT_TYPE.find(topic)?.let { val typeText = it.groupValues[1] when (typeText) { @@ -51,17 +51,18 @@ class MobidziennikApiEvents(val data: DataMobidziennik, rows: List) { val eventObject = Event( - data.profileId, - id, - eventDate, - startTime, - topic, - -1, - type, - false, - teacherId, - subjectId, - teamId) + 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( @@ -70,12 +71,13 @@ class MobidziennikApiEvents(val data: DataMobidziennik, rows: List) { Metadata.TYPE_EVENT, id, data.profile?.empty ?: false, - data.profile?.empty ?: false, - addedDate + data.profile?.empty ?: false )) } } - data.toRemove.add(DataRemoveModel.Events.futureExceptType(Event.TYPE_HOMEWORK)) + 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/MobidziennikApiGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiGrades.kt index 609c895c..c3c1b449 100644 --- 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 @@ -79,7 +79,9 @@ class MobidziennikApiGrades(val data: DataMobidziennik, rows: List) { comment = null, semester = semester, teacherId = teacherId, - subjectId = subjectId) + subjectId = subjectId, + addedDate = addedDate + ) if (data.profile?.empty == true) { addedDate = data.profile.dateSemester1Start.inMillis @@ -92,8 +94,7 @@ class MobidziennikApiGrades(val data: DataMobidziennik, rows: List) { Metadata.TYPE_GRADE, id, data.profile?.empty ?: false, - data.profile?.empty ?: false, - addedDate + data.profile?.empty ?: false )) addedDate++ } 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 index 4c5b4e03..a79eaded 100644 --- 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 @@ -9,6 +9,7 @@ import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidzienn 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 @@ -25,22 +26,22 @@ class MobidziennikApiHomework(val data: DataMobidziennik, rows: List) { val id = cols[0].toLong() val teacherId = cols[7].toLong() val subjectId = cols[6].toLong() - val topic = cols[1] + 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( - data.profileId, - id, - eventDate, - startTime, - topic, - -1, - Event.TYPE_HOMEWORK, - false, - teacherId, - subjectId, - teamId) + 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( @@ -49,8 +50,7 @@ class MobidziennikApiHomework(val data: DataMobidziennik, rows: List) { Metadata.TYPE_HOMEWORK, id, data.profile?.empty ?: false, - data.profile?.empty ?: false, - System.currentTimeMillis() + data.profile?.empty ?: false )) } } 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 index f1d9aed2..66bfe1fd 100644 --- 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 @@ -33,12 +33,16 @@ class MobidziennikApiNotices(val data: DataMobidziennik, rows: List) { val addedDate = Date.fromYmd(cols[7]).inMillis val noticeObject = Notice( - data.profileId, - id, - text, - semester, - type, - teacherId) + 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( @@ -47,8 +51,7 @@ class MobidziennikApiNotices(val data: DataMobidziennik, rows: List) { Metadata.TYPE_NOTICE, id, data.profile?.empty ?: false, - data.profile?.empty ?: false, - addedDate + data.profile?.empty ?: false )) } }} 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 index 8fd5677b..dbd1c03d 100644 --- 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 @@ -6,8 +6,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.db.entity.Team -import pl.szczodrzynski.edziennik.getById -import pl.szczodrzynski.edziennik.values +import pl.szczodrzynski.edziennik.ext.getById +import pl.szczodrzynski.edziennik.ext.values class MobidziennikApiTeams(val data: DataMobidziennik, tableTeams: List?, tableRelations: List?) { init { @@ -35,7 +35,6 @@ class MobidziennikApiTeams(val data: DataMobidziennik, tableTeams: List? } if (tableRelations != null) { val allTeams = data.teamList.values() - data.teamList.clear() for (row in tableRelations) { if (row.isEmpty()) @@ -44,7 +43,7 @@ class MobidziennikApiTeams(val data: DataMobidziennik, tableTeams: List? val studentId = cols[1].toInt() val teamId = cols[2].toLong() - val studentNumber = cols[4].toInt() + val studentNumber = cols[4].toIntOrNull() ?: -1 if (studentId != data.studentId) continue 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 index 6a7ce02d..8e490832 100644 --- 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 @@ -8,12 +8,12 @@ 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.data.db.entity.Lesson -import pl.szczodrzynski.edziennik.fixName -import pl.szczodrzynski.edziennik.keys -import pl.szczodrzynski.edziennik.singleOrNull +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 @@ -24,7 +24,7 @@ class MobidziennikApiTimetable(val data: DataMobidziennik, rows: List) { val dataStart = Date.getToday() val dataEnd = dataStart.clone().stepForward(0, 0, 7 + (6 - dataStart.weekDay)) - data.toRemove.add(DataRemoveModel.Timetable.between(dataStart.clone(), dataEnd)) + data.toRemove.add(DataRemoveModel.Timetable.between(dataStart.clone(), dataEnd, isExtra = false)) val dataDays = mutableListOf() while (dataStart <= dataEnd) { @@ -44,7 +44,7 @@ class MobidziennikApiTimetable(val data: DataMobidziennik, rows: List) { dataDays.remove(date.value) - val subjectId = data.subjectList.singleOrNull { it.longName == lesson[5] }?.id ?: -1 + val subjectId = data.subjectList.singleOrNull { it.longName == lesson[5].trim() }?.id ?: -1 val teacherId = data.teacherList.singleOrNull { it.fullNameLastFirst == (lesson[7]+" "+lesson[6]).fixName() }?.id ?: -1 val teamId = data.teamList.singleOrNull { it.name == lesson[8]+lesson[9] }?.id ?: -1 val classroom = lesson[11] @@ -97,8 +97,7 @@ class MobidziennikApiTimetable(val data: DataMobidziennik, rows: List) { Metadata.TYPE_LESSON_CHANGE, it.id, seen, - seen, - System.currentTimeMillis() + seen )) } data.lessonList += it diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiUsers.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiUsers.kt index b95a55fe..943983d4 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiUsers.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api/MobidziennikApiUsers.kt @@ -6,7 +6,7 @@ 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.Teacher -import pl.szczodrzynski.edziennik.fixName +import pl.szczodrzynski.edziennik.ext.fixName class MobidziennikApiUsers(val data: DataMobidziennik, rows: List) { init { diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api2/MobidziennikApi2Main.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api2/MobidziennikApi2Main.kt index 70d32b18..9c231849 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api2/MobidziennikApi2Main.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/api2/MobidziennikApi2Main.kt @@ -14,8 +14,8 @@ import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.ENDPOINT_MOBID import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.login.MobidziennikLoginApi2 import pl.szczodrzynski.edziennik.data.api.models.ApiError import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS -import pl.szczodrzynski.edziennik.getJsonObject -import pl.szczodrzynski.edziennik.getString +import pl.szczodrzynski.edziennik.ext.getJsonObject +import pl.szczodrzynski.edziennik.ext.getString import pl.szczodrzynski.edziennik.utils.Utils class MobidziennikApi2Main(val data: DataMobidziennik, diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikLuckyNumberExtractor.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikLuckyNumberExtractor.kt index 5e1445ec..ece23d7f 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikLuckyNumberExtractor.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikLuckyNumberExtractor.kt @@ -17,9 +17,9 @@ class MobidziennikLuckyNumberExtractor(val data: DataMobidziennik, text: String) val luckyNumber = it.groupValues[1].toInt() val luckyNumberObject = LuckyNumber( - data.profileId, - Date.getToday(), - luckyNumber + profileId = data.profileId, + date = Date.getToday(), + number = luckyNumber ) data.luckyNumberList.add(luckyNumberObject) @@ -29,8 +29,7 @@ class MobidziennikLuckyNumberExtractor(val data: DataMobidziennik, text: String) Metadata.TYPE_LUCKY_NUMBER, luckyNumberObject.date.value.toLong(), true, - data.profile?.empty ?: false, - System.currentTimeMillis() + data.profile?.empty ?: false )) } catch (_: Exception){} } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebAccountEmail.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebAccountEmail.kt index ef4c2847..9dc3878c 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebAccountEmail.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebAccountEmail.kt @@ -4,12 +4,12 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.web -import pl.szczodrzynski.edziennik.DAY import pl.szczodrzynski.edziennik.data.api.Regexes import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.ENDPOINT_MOBIDZIENNIK_WEB_ACCOUNT_EMAIL import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.MobidziennikWeb -import pl.szczodrzynski.edziennik.get +import pl.szczodrzynski.edziennik.ext.DAY +import pl.szczodrzynski.edziennik.ext.get class MobidziennikWebAccountEmail(override val data: DataMobidziennik, override val lastSync: Long?, @@ -26,7 +26,7 @@ class MobidziennikWebAccountEmail(override val data: DataMobidziennik, val email = Regexes.MOBIDZIENNIK_ACCOUNT_EMAIL.find(text)?.let { it[1] } data.loginEmail = email - data.setSyncNext(ENDPOINT_MOBIDZIENNIK_WEB_ACCOUNT_EMAIL, if (email == null) 3*DAY else 7*DAY) + data.setSyncNext(ENDPOINT_MOBIDZIENNIK_WEB_ACCOUNT_EMAIL, if (email == null) 3* DAY else 7* DAY) onSuccess(ENDPOINT_MOBIDZIENNIK_WEB_ACCOUNT_EMAIL) } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebAttendance.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebAttendance.kt index c56c56d9..9160e4d6 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebAttendance.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebAttendance.kt @@ -11,12 +11,18 @@ import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.ENDPOINT_MOBID import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.MobidziennikWeb import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel import pl.szczodrzynski.edziennik.data.db.entity.Attendance -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_BELATED +import pl.szczodrzynski.edziennik.data.db.entity.Attendance.Companion.TYPE_PRESENT +import pl.szczodrzynski.edziennik.data.db.entity.Attendance.Companion.TYPE_PRESENT_CUSTOM +import pl.szczodrzynski.edziennik.data.db.entity.Attendance.Companion.TYPE_RELEASED +import pl.szczodrzynski.edziennik.data.db.entity.Attendance.Companion.TYPE_UNKNOWN import pl.szczodrzynski.edziennik.data.db.entity.Metadata import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS -import pl.szczodrzynski.edziennik.fixName -import pl.szczodrzynski.edziennik.get -import pl.szczodrzynski.edziennik.singleOrNull +import pl.szczodrzynski.edziennik.ext.fixName +import pl.szczodrzynski.edziennik.ext.get +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 @@ -42,7 +48,7 @@ class MobidziennikWebAttendance(override val data: DataMobidziennik, //syncWeeks.clear() //syncWeeks += Date.fromY_m_d("2019-12-19") - syncWeeks.minBy { it.value }?.let { + syncWeeks.minByOrNull { it.value }?.let { data.toRemove.add(DataRemoveModel.Attendance.from(it)) } @@ -71,10 +77,25 @@ class MobidziennikWebAttendance(override val data: DataMobidziennik, val start = System.currentTimeMillis() + val types = Regexes.MOBIDZIENNIK_ATTENDANCE_TYPES + .find(text) + ?.get(1) + ?.split("
    ") + ?.map { + it.trimEnd(',') + .split(" ", limit = 2) + .let { it.getOrNull(0) to it.getOrNull(1) } + } + ?.toMap() + val typeSymbols = types?.keys?.filterNotNull() ?: listOf() + Regexes.MOBIDZIENNIK_ATTENDANCE_TABLE.findAll(text).forEach { tableResult -> val table = tableResult[1] + val lessonDates = mutableListOf() val entries = mutableListOf() + val ranges = mutableListOf() + Regexes.MOBIDZIENNIK_ATTENDANCE_LESSON_COUNT.findAll(table).forEach { val date = Date.fromY_m_d(it[1]) for (i in 0 until (it[2].toIntOrNull() ?: 0)) { @@ -83,67 +104,52 @@ class MobidziennikWebAttendance(override val data: DataMobidziennik, } Regexes.MOBIDZIENNIK_ATTENDANCE_ENTRIES.findAll(table).mapTo(entries) { it[1] } + Regexes.MOBIDZIENNIK_ATTENDANCE_COLUMNS.findAll(table).forEach { columns -> + var index = 0 + Regexes.MOBIDZIENNIK_ATTENDANCE_COLUMN.findAll(columns[1]).forEach { column -> + if (column[1].contains("colspan")) { + val colspan = + Regexes.MOBIDZIENNIK_ATTENDANCE_COLUMN_SPAN.find(column[1]) + ?.get(1) + ?.toIntOrNull() ?: 0 + entries.addAll(index, List(colspan) { "" }) + ranges.addAll(List(colspan) { null }) + index += colspan + } + else { + val range = Regexes.MOBIDZIENNIK_ATTENDANCE_RANGE.find(column[2]) + ranges.add(range) + index++ + } + } + } + val dateIterator = lessonDates.iterator() val entriesIterator = entries.iterator() - Regexes.MOBIDZIENNIK_ATTENDANCE_RANGE.findAll(table).let { ranges -> - val count = ranges.count() - // verify the lesson count is the same as dates & entries - if (count != lessonDates.count() || count != entries.count()) - return@forEach - ranges.forEach { range -> - val lessonDate = dateIterator.next() - val entry = entriesIterator.next() - if (entry.isBlank()) - return@forEach - val startTime = Time.fromH_m(range[1]) - val entryIterator = entry.iterator() - range[2].split(" / ").mapNotNull { Regexes.MOBIDZIENNIK_ATTENDANCE_LESSON.find(it) }.forEachIndexed { index, lesson -> - val topic = lesson[2] - if (topic.startsWith("Lekcja odwołana: ") || !entryIterator.hasNext()) - return@forEachIndexed - val subjectName = lesson[1] - //val team = lesson[3] - val teacherName = lesson[4].fixName() - val teacherId = data.teacherList.singleOrNull { it.fullNameLastFirst == teacherName }?.id ?: -1 - val subjectId = data.subjectList.singleOrNull { it.longName == subjectName }?.id ?: -1 + val count = ranges.count() + // verify the lesson count is the same as dates & entries + if (count != lessonDates.count() || count != entries.count()) + return@forEach + ranges.onEach { range -> + val lessonDate = dateIterator.next() + val entry = entriesIterator.next() + if (range == null || entry.isBlank()) + return@onEach + val startTime = Time.fromH_m(range[1]) - val type = when (entryIterator.nextChar()) { - '.' -> TYPE_PRESENT - '|' -> TYPE_ABSENT - '+' -> TYPE_ABSENT_EXCUSED - 's' -> TYPE_BELATED - 'z' -> TYPE_RELEASED - else -> TYPE_PRESENT - } - val semester = data.profile?.dateToSemester(lessonDate) ?: 1 - - val id = lessonDate.combineWith(startTime) / 6L * 10L + (lesson[0].hashCode() and 0xFFFF) + index - - val attendanceObject = Attendance( - data.profileId, - id, - teacherId, - subjectId, - semester, - topic, - lessonDate, - startTime, - type) - - data.attendanceList.add(attendanceObject) - if (type != TYPE_PRESENT) { - data.metadataList.add( - Metadata( - data.profileId, - Metadata.TYPE_ATTENDANCE, - id, - data.profile?.empty ?: false, - data.profile?.empty ?: false, - System.currentTimeMillis() - )) - } - } + range[2].split(" / ").mapNotNull { + Regexes.MOBIDZIENNIK_ATTENDANCE_LESSON.find(it) + }.forEachIndexed { index, lesson -> + processEntry( + index, + lesson, + lessonDate, + startTime, + entry, + types, + typeSymbols + ) } } } @@ -153,4 +159,98 @@ class MobidziennikWebAttendance(override val data: DataMobidziennik, onSuccess() } } + + private fun processEntry( + index: Int, + lesson: MatchResult, + lessonDate: Date, + startTime: Time, + entry: String, + types: Map?, + typeSymbols: List + ) { + var entry = entry + + val topic = lesson[1].substringAfter(" - ", missingDelimiterValue = "").takeIf { it.isNotBlank() } + if (topic?.startsWith("Lekcja odwołana: ") == true || entry.isEmpty()) + return + val subjectName = lesson[1].substringBefore(" - ").trim() + //val team = lesson[3] + val teacherName = lesson[3].fixName() + + val teacherId = data.teacherList.singleOrNull { it.fullNameLastFirst == teacherName }?.id ?: -1 + val subjectId = data.subjectList.singleOrNull { it.longName == subjectName }?.id ?: -1 + + var typeSymbol = "" + for (symbol in typeSymbols) { + if (entry.startsWith(symbol) && symbol.length > typeSymbol.length) + typeSymbol = symbol + } + // entry = entry.removePrefix(typeSymbol) + + var isCustom = false + val baseType = when (typeSymbol) { + "." -> TYPE_PRESENT + "|" -> TYPE_ABSENT + "+" -> TYPE_ABSENT_EXCUSED + "s" -> TYPE_BELATED + "z" -> TYPE_RELEASED + else -> { + isCustom = true + when (typeSymbol) { + "e" -> TYPE_PRESENT_CUSTOM + "en" -> TYPE_ABSENT + "ep" -> TYPE_PRESENT_CUSTOM + "+ₑ" -> TYPE_ABSENT_EXCUSED + else -> TYPE_UNKNOWN + } + } + } + val typeName = types?.get(typeSymbol) ?: "" + val typeColor = when (typeSymbol) { + "e" -> 0xff673ab7 + "en" -> 0xffec407a + "ep" -> 0xff4caf50 + "+ₑ" -> 0xff795548 + else -> null + }?.toInt() + + val typeShort = if (!isCustom) + data.app.attendanceManager.getTypeShort(baseType) + else + typeSymbol + + val semester = data.profile?.dateToSemester(lessonDate) ?: 1 + + val id = lessonDate.combineWith(startTime) / 6L * 10L + (lesson[0].hashCode() and 0xFFFF) + index + + val attendanceObject = Attendance( + profileId = profileId, + id = id, + baseType = baseType, + typeName = typeName, + typeShort = typeShort, + typeSymbol = typeSymbol, + typeColor = typeColor, + date = lessonDate, + startTime = startTime, + semester = semester, + teacherId = teacherId, + subjectId = subjectId + ).also { + it.lessonTopic = topic + } + + data.attendanceList.add(attendanceObject) + if (baseType != TYPE_PRESENT) { + data.metadataList.add( + Metadata( + data.profileId, + Metadata.TYPE_ATTENDANCE, + id, + data.profile?.empty ?: false || baseType == Attendance.TYPE_PRESENT_CUSTOM || baseType == TYPE_UNKNOWN, + data.profile?.empty ?: false || baseType == Attendance.TYPE_PRESENT_CUSTOM || baseType == TYPE_UNKNOWN + )) + } + } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebCalendar.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebCalendar.kt index 9664a68b..b6a10335 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebCalendar.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebCalendar.kt @@ -12,10 +12,9 @@ import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.Mobidzien 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.getString +import pl.szczodrzynski.edziennik.ext.getString import pl.szczodrzynski.edziennik.utils.Utils.crc16 import pl.szczodrzynski.edziennik.utils.models.Date -import java.util.* class MobidziennikWebCalendar(override val data: DataMobidziennik, override val lastSync: Long?, @@ -30,7 +29,7 @@ class MobidziennikWebCalendar(override val data: DataMobidziennik, MobidziennikLuckyNumberExtractor(data, text) Regexes.MOBIDZIENNIK_CLASS_CALENDAR.find(text)?.let { - val events = JsonParser().parse(it.groupValues[1]).asJsonArray + val events = JsonParser.parseString(it.groupValues[1]).asJsonArray for (eventEl in events) { val event = eventEl.asJsonObject @@ -50,7 +49,7 @@ class MobidziennikWebCalendar(override val data: DataMobidziennik, val dateString = event.getString("start") ?: continue val eventDate = Date.fromY_m_d(dateString) - val eventType = when (event.getString("color")?.toLowerCase(Locale.getDefault())) { + val eventType = when (event.getString("color")?.lowercase()) { "#c54449" -> Event.TYPE_SHORT_QUIZ "#ab0001" -> Event.TYPE_EXAM "#008928" -> Event.TYPE_CLASS_EVENT @@ -61,27 +60,27 @@ class MobidziennikWebCalendar(override val data: DataMobidziennik, val title = event.getString("title") val comment = event.getString("comment") - var topic = title + var topic = title ?: "" if (title != comment) { topic += "\n" + comment } if (id == -1L) { - id = crc16(topic?.toByteArray()).toLong() + id = crc16(topic.toByteArray()).toLong() } val eventObject = Event( - profileId, - id, - eventDate, null, - topic, - -1, - eventType, - false, - -1, - -1, - data.teamClass?.id ?: -1 + profileId = profileId, + id = id, + date = eventDate, time = null, + topic = topic, + color = null, + type = eventType, + teacherId = -1, + subjectId = -1, + teamId = data.teamClass?.id ?: -1 ) + eventObject.isDownloaded = false data.eventList.add(eventObject) data.metadataList.add( @@ -90,8 +89,8 @@ class MobidziennikWebCalendar(override val data: DataMobidziennik, Metadata.TYPE_EVENT, eventObject.id, profile?.empty ?: false, - profile?.empty ?: false, - System.currentTimeMillis() /* no addedDate here though */ + profile?.empty ?: false + /* no addedDate here though */ )) } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGetAttachment.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGetAttachment.kt index 80803441..b8c6644f 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGetAttachment.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGetAttachment.kt @@ -8,12 +8,14 @@ import org.greenrobot.eventbus.EventBus 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.events.AttachmentGetEvent +import pl.szczodrzynski.edziennik.data.db.entity.Event import pl.szczodrzynski.edziennik.data.db.entity.Message import pl.szczodrzynski.edziennik.utils.Utils +import pl.szczodrzynski.edziennik.utils.models.Date import java.io.File class MobidziennikWebGetAttachment(override val data: DataMobidziennik, - val message: Message, + val owner: Any, val attachmentId: Long, val attachmentName: String, val onSuccess: () -> Unit @@ -25,25 +27,40 @@ class MobidziennikWebGetAttachment(override val data: DataMobidziennik, init { val targetFile = File(Utils.getStorageDir(), attachmentName) - val typeUrl = if (message.type == Message.TYPE_SENT) - "wiadwyslana" - else - "wiadodebrana" + val typeUrl = when (owner) { + is Message -> if (owner.isSent) + "dziennik/wiadwyslana/?id=" + else + "dziennik/wiadodebrana/?id=" - webGetFile(TAG, "/dziennik/$typeUrl/?id=${message.id}&zalacznik=$attachmentId", targetFile, { file -> + is Event -> if (owner.date >= Date.getToday()) + "dziennik/wyslijzadanie/?id_zadania=" + else + "dziennik/wyslijzadanie/?id_zadania=" + + else -> "" + } + + val ownerId = when (owner) { + is Message -> owner.id + is Event -> owner.id + else -> -1 + } + + webGetFile(TAG, "/$typeUrl${ownerId}&uczen=${data.studentId}&zalacznik=$attachmentId", targetFile, { file -> val event = AttachmentGetEvent( profileId, - message.id, + owner, attachmentId, AttachmentGetEvent.TYPE_FINISHED, file.absolutePath ) - val attachmentDataFile = File(Utils.getStorageDir(), ".${profileId}_${event.messageId}_${event.attachmentId}") + val attachmentDataFile = File(Utils.getStorageDir(), ".${profileId}_${event.ownerId}_${event.attachmentId}") Utils.writeStringToFile(attachmentDataFile, event.fileName) - EventBus.getDefault().post(event) + EventBus.getDefault().postSticky(event) onSuccess() @@ -51,13 +68,13 @@ class MobidziennikWebGetAttachment(override val data: DataMobidziennik, // TODO make use of bytesTotal val event = AttachmentGetEvent( profileId, - message.id, + owner, attachmentId, AttachmentGetEvent.TYPE_PROGRESS, bytesWritten = written ) - EventBus.getDefault().post(event) + EventBus.getDefault().postSticky(event) } } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGetEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGetEvent.kt new file mode 100644 index 00000000..69a2dce0 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGetEvent.kt @@ -0,0 +1,57 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-1. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.web + +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.data.api.POST +import pl.szczodrzynski.edziennik.data.api.Regexes +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.events.EventGetEvent +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.utils.models.Date + +class MobidziennikWebGetEvent( + override val data: DataMobidziennik, + val event: EventFull, + val onSuccess: () -> Unit +) : MobidziennikWeb(data, null) { + companion object { + private const val TAG = "MobidziennikWebGetEvent" + } + + init { + val params = listOf( + "typ" to "kalendarz", + "uczen" to data.studentId, + "id" to event.id, + ) + + webGet(TAG, "/dziennik/ajaxkalendarzklasowy", method = POST, parameters = params) { text -> + Regexes.MOBIDZIENNIK_EVENT_CONTENT.find(text)?.let { + val topic = it[1] + val teacherName = it[2] + val teacher = data.getTeacherByLastFirst(teacherName) + val addedDate = Date.fromY_m_d(it[3]) + val body = it[4] + .replace("\n", "") + .replace(Regexes.HTML_BR, "\n") + + event.topic = topic + event.homeworkBody = body + event.isDownloaded = true + event.teacherId = teacher.id + event.addedDate = addedDate.inMillis + } + + 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/mobidziennik/data/web/MobidziennikWebGetHomework.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGetHomework.kt new file mode 100644 index 00000000..9dbdd439 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGetHomework.kt @@ -0,0 +1,74 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-3-31. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.web + +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.data.api.Regexes +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.events.EventGetEvent +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time + +class MobidziennikWebGetHomework(override val data: DataMobidziennik, + val event: EventFull, + val onSuccess: () -> Unit +) : MobidziennikWeb(data, null) { + companion object { + private const val TAG = "MobidziennikWebGetHomework" + } + + init { + webGet(TAG, "/dziennik/wyslijzadanie/?id_zadania=${event.id}&uczen=${data.studentId}") { text -> + MobidziennikLuckyNumberExtractor(data, text) + + event.clearAttachments() + Regexes.MOBIDZIENNIK_WEB_ATTACHMENT.findAll(text).forEach { match -> + if (match[1].isNotEmpty()) + return@forEach + val attachmentId = match[2].toLong() + val attachmentName = match[3] + event.addAttachment(attachmentId, attachmentName) + } + + Regexes.MOBIDZIENNIK_WEB_HOMEWORK_ADDED_DATE.find(text)?.let { + // (Kowalski Jan), (wtorek), (2) (stycznia) (2019), godzina (12:34:56) + val month = when (it[4]) { + "stycznia" -> 1 + "lutego" -> 2 + "marca" -> 3 + "kwietnia" -> 4 + "maja" -> 5 + "czerwca" -> 6 + "lipca" -> 7 + "sierpnia" -> 8 + "września" -> 9 + "października" -> 10 + "listopada" -> 11 + "grudnia" -> 12 + else -> 1 + } + val addedDate = Date( + it[5].toInt(), + month, + it[3].toInt() + ) + val time = Time.fromH_m_s(it[6]) + event.addedDate = addedDate.combineWith(time) + } + + event.homeworkBody = "" + event.isDownloaded = true + + 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/mobidziennik/data/web/MobidziennikWebGetMessage.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGetMessage.kt index 5b462e57..3e196ec0 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGetMessage.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGetMessage.kt @@ -10,14 +10,12 @@ import pl.szczodrzynski.edziennik.data.api.Regexes 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.events.MessageGetEvent -import pl.szczodrzynski.edziennik.data.db.entity.Message -import pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_RECEIVED import pl.szczodrzynski.edziennik.data.db.entity.Metadata import pl.szczodrzynski.edziennik.data.db.full.MessageFull import pl.szczodrzynski.edziennik.data.db.full.MessageRecipientFull -import pl.szczodrzynski.edziennik.fixName -import pl.szczodrzynski.edziennik.get -import pl.szczodrzynski.edziennik.singleOrNull +import pl.szczodrzynski.edziennik.ext.fixName +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.ext.singleOrNull import pl.szczodrzynski.edziennik.utils.Utils.monthFromName import pl.szczodrzynski.edziennik.utils.models.Date import pl.szczodrzynski.edziennik.utils.models.Time @@ -31,7 +29,7 @@ class MobidziennikWebGetMessage(override val data: DataMobidziennik, } init { - val typeUrl = if (message.type == Message.TYPE_SENT) + val typeUrl = if (message.isSent) "wiadwyslana" else "wiadodebrana" @@ -42,13 +40,14 @@ class MobidziennikWebGetMessage(override val data: DataMobidziennik, val doc = Jsoup.parse(text) - val content = doc.select("#content").first() + val content = doc.select("#content").first() ?: return@webGet val body = content.select(".wiadomosc_tresc").first() + val bodyHtml = body?.html() ?: "" - if (message.type == TYPE_RECEIVED) { + if (message.isReceived) { var readDate = System.currentTimeMillis() - Regexes.MOBIDZIENNIK_MESSAGE_READ_DATE.find(body.html())?.let { + Regexes.MOBIDZIENNIK_MESSAGE_READ_DATE.find(bodyHtml)?.let { val date = Date( it[3].toIntOrNull() ?: 2019, monthFromName(it[2]), @@ -61,50 +60,47 @@ class MobidziennikWebGetMessage(override val data: DataMobidziennik, } val recipient = MessageRecipientFull( - profileId, - -1, - -1, - readDate, - message.id + profileId = profileId, + id = -1, + messageId = message.id, + readDate = readDate ) recipient.fullName = profile?.accountName ?: profile?.studentNameLong ?: "" messageRecipientList.add(recipient) } else { - message.senderId = -1 - message.senderReplyId = -1 + message.senderId = null - content.select("table.spis tr:has(td)")?.forEach { recipientEl -> - val senderEl = recipientEl.select("td:eq(0)").first() + content.select("table.spis tr:has(td)").forEach { recipientEl -> + val senderEl = recipientEl.select("td:eq(1)").first() ?: return@forEach val senderName = senderEl.text().fixName() val teacher = data.teacherList.singleOrNull { it.fullNameLastFirst == senderName } val receiverId = teacher?.id ?: -1 var readDate = 0L - val isReadEl = recipientEl.select("td:eq(2)").first() - if (isReadEl.ownText() != "NIE") { - val readDateEl = recipientEl.select("td:eq(3) small").first() + val isReadEl = recipientEl.select("td:eq(4)").first() ?: return@forEach + if (isReadEl.html().contains("tak")) { + val readDateEl = recipientEl.select("td:eq(5) small").first() ?: return@forEach Regexes.MOBIDZIENNIK_MESSAGE_SENT_READ_DATE.find(readDateEl.ownText())?.let { val date = Date( - it[3].toIntOrNull() ?: 2019, - monthFromName(it[2]), - it[1].toIntOrNull() ?: 1 + it[3].toIntOrNull() ?: 2019, + monthFromName(it[2]), + it[1].toIntOrNull() ?: 1 ) val time = Time.fromH_m_s( - it[4] // TODO blank string safety + it[4] // TODO blank string safety ) readDate = date.combineWith(time) } } val recipient = MessageRecipientFull( - profileId, - receiverId, - -1, - readDate, - message.id + profileId = profileId, + id = receiverId, + messageId = message.id, + readDate = readDate ) recipient.fullName = teacher?.fullName ?: "?" @@ -114,25 +110,23 @@ class MobidziennikWebGetMessage(override val data: DataMobidziennik, } // this line removes the sender and read date details - body.select("div").remove() + body?.select("div")?.remove() // this needs to be at the end message.apply { - this.body = body.html() + this.body = body?.html() clearAttachments() - content.select("ul li").map { it.select("a").first() }.forEach { - val attachmentName = it.ownText() - Regexes.MOBIDZIENNIK_MESSAGE_ATTACHMENT.find(it.outerHtml())?.let { match -> - val attachmentId = match[1].toLong() - var size = match[2].toFloatOrNull() ?: -1f - when (match[3]) { - "K" -> size *= 1024f - "M" -> size *= 1024f * 1024f - "G" -> size *= 1024f * 1024f * 1024f - } - message.addAttachment(attachmentId, attachmentName, size.toLong()) + Regexes.MOBIDZIENNIK_WEB_ATTACHMENT.findAll(text).forEach { match -> + val attachmentId = match[2].toLong() + val attachmentName = match[3] + var size = match[4].toFloatOrNull() ?: -1f + when (match[5]) { + "K" -> size *= 1024f + "M" -> size *= 1024f * 1024f + "G" -> size *= 1024f * 1024f * 1024f } + message.addAttachment(attachmentId, attachmentName, size.toLong()) } } @@ -142,14 +136,15 @@ class MobidziennikWebGetMessage(override val data: DataMobidziennik, Metadata.TYPE_MESSAGE, message.id, true, - true, - message.addedDate + true )) } message.recipients = messageRecipientList data.messageRecipientList.addAll(messageRecipientList) + data.messageList.add(message) + data.messageListReplace = true EventBus.getDefault().postSticky(MessageGetEvent(message)) onSuccess() diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGetRecipientList.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGetRecipientList.kt index 1118da48..b6f2afa7 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGetRecipientList.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGetRecipientList.kt @@ -9,12 +9,12 @@ import androidx.room.OnConflictStrategy import com.google.gson.JsonObject import com.google.gson.JsonParser import org.greenrobot.eventbus.EventBus -import pl.szczodrzynski.edziennik.* import pl.szczodrzynski.edziennik.data.api.Regexes 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.events.RecipientListGetEvent import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.ext.* class MobidziennikWebGetRecipientList(override val data: DataMobidziennik, val onSuccess: () -> Unit @@ -26,7 +26,7 @@ class MobidziennikWebGetRecipientList(override val data: DataMobidziennik, init { webGet(TAG, "/mobile/dodajwiadomosc") { text -> Regexes.MOBIDZIENNIK_MESSAGE_RECIPIENTS_JSON.find(text)?.let { match -> - val recipientLists = JsonParser().parse(match[1]).asJsonArray + val recipientLists = JsonParser.parseString(match[1]).asJsonArray recipientLists?.asJsonObjectList()?.forEach { list -> val listType = list.getString("typ")?.toIntOrNull() ?: -1 val listName = list.getString("nazwa") ?: "" @@ -56,20 +56,21 @@ class MobidziennikWebGetRecipientList(override val data: DataMobidziennik, } private fun processRecipient(listType: Int, listName: String, recipient: JsonObject) { - val id = recipient.getLong("id") ?: -1 + val id = recipient.getString("id") ?: return + val idLong = id.replace(Regexes.NOT_DIGITS, "").toLongOrNull() ?: return // get teacher by ID or create it - val teacher = data.teacherList[id] ?: Teacher(data.profileId, id).apply { + val teacher = data.teacherList[idLong] ?: Teacher(data.profileId, idLong).apply { val fullName = recipient.getString("nazwa")?.fixName() name = fullName ?: "" fullName?.splitName()?.let { name = it.second surname = it.first } - data.teacherList[id] = this + data.teacherList[idLong] = this } teacher.apply { - loginId = id.toString() + loginId = id when (listType) { 1 -> setTeacherType(Teacher.TYPE_PRINCIPAL) 2 -> setTeacherType(Teacher.TYPE_TEACHER) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGrades.kt index de058c91..285441b6 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGrades.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebGrades.kt @@ -14,9 +14,9 @@ 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.Metadata import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS -import pl.szczodrzynski.edziennik.fixWhiteSpaces -import pl.szczodrzynski.edziennik.get -import pl.szczodrzynski.edziennik.singleOrNull +import pl.szczodrzynski.edziennik.ext.fixWhiteSpaces +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.ext.singleOrNull import pl.szczodrzynski.edziennik.utils.models.Date import pl.szczodrzynski.edziennik.utils.models.Time @@ -46,7 +46,7 @@ class MobidziennikWebGrades(override val data: DataMobidziennik, when (e.tagName()) { "div" -> { Regexes.MOBIDZIENNIK_GRADES_SUBJECT_NAME.find(e.outerHtml())?.let { - subjectName = it[1] + subjectName = it[1].trim() } } "span" -> { @@ -125,7 +125,8 @@ class MobidziennikWebGrades(override val data: DataMobidziennik, comment = null, semester = gradeSemester, teacherId = teacherId, - subjectId = subjectId + subjectId = subjectId, + addedDate = gradeAddedDateMillis ) gradeObject.classAverage = gradeClassAverage @@ -137,8 +138,7 @@ class MobidziennikWebGrades(override val data: DataMobidziennik, Metadata.TYPE_GRADE, gradeObject.id, profile.empty, - profile.empty, - gradeAddedDateMillis + profile.empty )) } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebHomework.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebHomework.kt new file mode 100644 index 00000000..f9638ac1 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebHomework.kt @@ -0,0 +1,80 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-3-31. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.web + +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.data.api.Regexes +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.ENDPOINT_MOBIDZIENNIK_WEB_HOMEWORK +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.MobidziennikWeb +import pl.szczodrzynski.edziennik.data.api.events.EventGetEvent +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.ext.get + +class MobidziennikWebHomework(override val data: DataMobidziennik, + override val lastSync: Long?, + val type: Int = TYPE_CURRENT, + val event: EventFull, + val onSuccess: (endpointId: Int) -> Unit +) : MobidziennikWeb(data, lastSync) { + companion object { + private const val TAG = "MobidziennikWebHomework" + const val TYPE_CURRENT = 0 + const val TYPE_PAST = 1 + } + + init { + val endpoint = when (type) { + TYPE_PAST -> "zadaniadomowearchiwalne" + else -> "zadaniadomowe" + } + webGet(TAG, "/mobile/$endpoint") { text -> + MobidziennikLuckyNumberExtractor(data, text) + + Regexes.MOBIDZIENNIK_MOBILE_HOMEWORK_ROW.findAll(text).forEach { homeworkMatch -> + val tableRow = homeworkMatch[1].ifBlank { return@forEach } + + /*val items = Regexes.MOBIDZIENNIK_HOMEWORK_ITEM.findAll(tableRow).map { match -> + match[1] to match[2].fixWhiteSpaces() + }.toList()*/ + + val id = Regexes.MOBIDZIENNIK_MOBILE_HOMEWORK_ID.find(tableRow)?.get(1)?.toLongOrNull() ?: return@forEach + if (event.id != id) + return@forEach + + //val homeworkBody = Regexes.MOBIDZIENNIK_HOMEWORK_BODY.find(tableRow)?.get(1) ?: "" + + event.attachmentIds = mutableListOf() + event.attachmentNames = mutableListOf() + Regexes.MOBIDZIENNIK_MOBILE_HOMEWORK_ATTACHMENT.findAll(tableRow).onEach { + event.attachmentIds?.add(it[1].toLongOrNull() ?: return@onEach) + event.attachmentNames?.add(it[2]) + } + + event.homeworkBody = "" + event.isDownloaded = true + } + + //data.eventList.add(eventObject) + //data.metadataList.add( + // Metadata( + // profileId, + // Metadata.TYPE_EVENT, + // eventObject.id, + // profile?.empty ?: false, + // profile?.empty ?: false, + // System.currentTimeMillis() /* no addedDate here though */ + // )) + + // not used as an endpoint + //data.setSyncNext(ENDPOINT_MOBIDZIENNIK_WEB_HOMEWORK, SYNC_ALWAYS) + data.eventList.add(event) + data.eventListReplace = true + + EventBus.getDefault().postSticky(EventGetEvent(event)) + onSuccess(ENDPOINT_MOBIDZIENNIK_WEB_HOMEWORK) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebMessagesAll.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebMessagesAll.kt index 61c9222e..aebff41e 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebMessagesAll.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebMessagesAll.kt @@ -5,18 +5,19 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.web import org.jsoup.Jsoup -import pl.szczodrzynski.edziennik.DAY import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_ALL import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.MobidziennikWeb import pl.szczodrzynski.edziennik.data.db.entity.Message -import pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_RECEIVED -import pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_SENT +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.MessageRecipient import pl.szczodrzynski.edziennik.data.db.entity.Metadata -import pl.szczodrzynski.edziennik.fixName -import pl.szczodrzynski.edziennik.singleOrNull +import pl.szczodrzynski.edziennik.ext.DAY +import pl.szczodrzynski.edziennik.ext.fixName +import pl.szczodrzynski.edziennik.ext.singleOrNull import pl.szczodrzynski.edziennik.utils.models.Date +import java.net.URLEncoder class MobidziennikWebMessagesAll(override val data: DataMobidziennik, override val lastSync: Long?, @@ -27,44 +28,45 @@ class MobidziennikWebMessagesAll(override val data: DataMobidziennik, } init { - webGet(TAG, "/dziennik/wyszukiwarkawiadomosci?q=+") { text -> + val query = URLEncoder.encode(data.profile?.studentNameLong ?: "a", "UTF-8") + webGet(TAG, "/dziennik/wyszukiwarkawiadomosci?q=$query") { text -> MobidziennikLuckyNumberExtractor(data, text) val doc = Jsoup.parse(text) - val listElement = doc.getElementsByClass("spis")?.first() + val listElement = doc.getElementsByClass("spis").first() if (listElement == null) { - data.setSyncNext(ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_ALL, 7*DAY) + data.setSyncNext(ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_ALL, 7* DAY) onSuccess(ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_ALL) return@webGet } val list = listElement.getElementsByClass("podswietl") - list?.forEach { item -> + list.forEach { item -> val id = item.attr("rel").replace("[^\\d]".toRegex(), "").toLongOrNull() ?: return@forEach val subjectEl = item.select("td:eq(0) div").first() - val subject = subjectEl.text() + val subject = subjectEl?.text() ?: "" val addedDateEl = item.select("td:eq(1)").first() - val addedDate = Date.fromIsoHm(addedDateEl.text()) + val addedDate = Date.fromIsoHm(addedDateEl?.text()) val typeEl = item.select("td:eq(2) img").first() var type = TYPE_RECEIVED - if (typeEl.outerHtml().contains("mail_send.png")) + if (typeEl?.outerHtml()?.contains("mail_send.png") == true) type = TYPE_SENT val senderEl = item.select("td:eq(3) div").first() - var senderId: Long = -1 + var senderId: Long? = null if (type == TYPE_RECEIVED) { // search sender teacher - val senderName = senderEl.text().fixName() - senderId = data.teacherList.singleOrNull { it.fullNameLastFirst == senderName }?.id ?: -1 + val senderName = senderEl?.text().fixName() + senderId = data.teacherList.singleOrNull { it.fullNameLastFirst == senderName }?.id data.messageRecipientList.add(MessageRecipient(profileId, -1, id)) } else { // TYPE_SENT, so multiple recipients possible - val recipientNames = senderEl.text().split(", ") - for (recipientName in recipientNames) { + val recipientNames = senderEl?.text()?.split(", ") + recipientNames?.forEach { recipientName -> val name = recipientName.fixName() val recipientId = data.teacherList.singleOrNull { it.fullNameLastFirst == name }?.id ?: -1 data.messageRecipientIgnoreList.add(MessageRecipient(profileId, recipientId, id)) @@ -72,22 +74,22 @@ class MobidziennikWebMessagesAll(override val data: DataMobidziennik, } val message = Message( - profileId, - id, - subject, - null, - type, - senderId, - -1 + profileId = profileId, + id = id, + type = type, + subject = subject, + body = null, + senderId = senderId, + addedDate = addedDate ) - data.messageIgnoreList.add(message) - data.metadataList.add(Metadata(profileId, Metadata.TYPE_MESSAGE, message.id, true, true, addedDate)) + data.messageList.add(message) + data.metadataList.add(Metadata(profileId, Metadata.TYPE_MESSAGE, message.id, true, true)) } // sync every 7 days as we probably don't expect more than // 30 received messages during a week, without any normal sync - data.setSyncNext(ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_ALL, 7*DAY) + data.setSyncNext(ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_ALL, 7* DAY) onSuccess(ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_ALL) } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebMessagesInbox.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebMessagesInbox.kt index ee5cbd24..b3819784 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebMessagesInbox.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebMessagesInbox.kt @@ -12,8 +12,8 @@ import pl.szczodrzynski.edziennik.data.db.entity.Message import pl.szczodrzynski.edziennik.data.db.entity.MessageRecipient import pl.szczodrzynski.edziennik.data.db.entity.Metadata import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS -import pl.szczodrzynski.edziennik.fixName -import pl.szczodrzynski.edziennik.singleOrNull +import pl.szczodrzynski.edziennik.ext.fixName +import pl.szczodrzynski.edziennik.ext.singleOrNull import pl.szczodrzynski.edziennik.utils.models.Date class MobidziennikWebMessagesInbox(override val data: DataMobidziennik, @@ -36,49 +36,57 @@ class MobidziennikWebMessagesInbox(override val data: DataMobidziennik, val doc = Jsoup.parse(text) - val list = doc.getElementsByClass("spis")?.first()?.getElementsByClass("podswietl") + val today = Date.getToday() + var currentYear = today.year + var currentMonth = today.month + + val list = doc.getElementsByClass("spis").first()?.getElementsByClass("podswietl") list?.forEach { item -> val id = item.attr("rel").toLongOrNull() ?: return@forEach val subjectEl = item.select("td:eq(0)").first() var hasAttachments = false - if (subjectEl.getElementsByTag("a").size != 0) { + if (subjectEl?.getElementsByTag("a")?.size ?: 0 > 0) { hasAttachments = true } - val subject = subjectEl.ownText() + val subject = subjectEl?.ownText() ?: "" - val addedDateEl = item.select("td:eq(1) small").first() - val addedDate = Date.fromIsoHm(addedDateEl.text()) + val addedDateEl = item.select("td:eq(4)").first() + val (date, time) = data.parseDateTime(addedDateEl?.text()?.trim() ?: "") + if (date.month > currentMonth) { + currentYear-- + } + currentMonth = date.month + date.year = currentYear - val senderEl = item.select("td:eq(2)").first() - val senderName = senderEl.ownText().fixName() - val senderId = data.teacherList.singleOrNull { it.fullNameLastFirst == senderName }?.id ?: -1 + val senderEl = item.select("td:eq(3)").first() + val senderName = senderEl?.ownText().fixName() + val senderId = data.teacherList.singleOrNull { it.fullNameLastFirst == senderName }?.id data.messageRecipientIgnoreList.add(MessageRecipient(profileId, -1, id)) - val isRead = item.select("td:eq(3) span").first().hasClass("wiadomosc_przeczytana") + val isRead = item.select("td:eq(5) span").first()?.hasClass("wiadomosc_przeczytana") == true val message = Message( - profileId, - id, - subject, - null, - Message.TYPE_RECEIVED, - senderId, - -1 + profileId = profileId, + id = id, + type = Message.TYPE_RECEIVED, + subject = subject, + body = null, + senderId = senderId, + addedDate = date.combineWith(time) ) if (hasAttachments) - message.setHasAttachments() + message.hasAttachments = true - data.messageIgnoreList.add(message) + data.messageList.add(message) data.setSeenMetadataList.add( Metadata( profileId, Metadata.TYPE_MESSAGE, message.id, isRead, - isRead || profile?.empty ?: false, - addedDate + isRead || profile?.empty ?: false )) } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebMessagesSent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebMessagesSent.kt index 8e7123c3..7f249cf6 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebMessagesSent.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebMessagesSent.kt @@ -5,7 +5,6 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.web import org.jsoup.Jsoup -import pl.szczodrzynski.edziennik.DAY import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_MESSAGES import pl.szczodrzynski.edziennik.data.api.Regexes import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik @@ -15,9 +14,10 @@ import pl.szczodrzynski.edziennik.data.db.entity.Message import pl.szczodrzynski.edziennik.data.db.entity.MessageRecipient import pl.szczodrzynski.edziennik.data.db.entity.Metadata import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS -import pl.szczodrzynski.edziennik.fixName -import pl.szczodrzynski.edziennik.get -import pl.szczodrzynski.edziennik.singleOrNull +import pl.szczodrzynski.edziennik.ext.DAY +import pl.szczodrzynski.edziennik.ext.fixName +import pl.szczodrzynski.edziennik.ext.get +import pl.szczodrzynski.edziennik.ext.singleOrNull import pl.szczodrzynski.edziennik.utils.models.Date class MobidziennikWebMessagesSent(override val data: DataMobidziennik, @@ -40,64 +40,74 @@ class MobidziennikWebMessagesSent(override val data: DataMobidziennik, val doc = Jsoup.parse(text) - val list = doc.getElementsByClass("spis")?.first()?.getElementsByClass("podswietl") + val today = Date.getToday() + var currentYear = today.year + var currentMonth = today.month + + val list = doc.getElementsByClass("spis").first()?.getElementsByClass("podswietl") list?.forEach { item -> val id = item.attr("rel").toLongOrNull() ?: return@forEach val subjectEl = item.select("td:eq(0)").first() + val subject = subjectEl?.ownText() ?: "" + + val attachmentsEl = item.select("td:eq(1)").first() var hasAttachments = false - if (subjectEl.getElementsByTag("a").size != 0) { + if (attachmentsEl?.getElementsByTag("a")?.size ?: 0 > 0) { hasAttachments = true } - val subject = subjectEl.ownText() - val readByString = item.select("td:eq(2)").first().text() + val readByString = item.select("td:eq(4)").first()?.text() ?: "" val (readBy, sentTo) = Regexes.MOBIDZIENNIK_MESSAGE_SENT_READ_BY.find(readByString).let { (it?.get(1)?.toIntOrNull() ?: 0) to (it?.get(2)?.toIntOrNull() ?: 0) } - val recipientEl = item.select("td:eq(1) a span").first() - val recipientNames = recipientEl.ownText().split(", ") + val recipientEl = item.select("td:eq(2) a span").first() + val recipientNames = recipientEl?.ownText()?.split(", ") val readState = when (readBy) { 0 -> 0 sentTo -> 1 else -> -1 }.toLong() - for (recipientName in recipientNames) { + recipientNames?.forEach { recipientName -> val name = recipientName.fixName() val recipientId = data.teacherList.singleOrNull { it.fullNameLastFirst == name }?.id ?: -1 data.messageRecipientIgnoreList.add(MessageRecipient(profileId, recipientId, -1, readState, id)) } - val addedDateEl = item.select("td:eq(3) small").first() - val addedDate = Date.fromIsoHm(addedDateEl.text()) + val addedDateEl = item.select("td:eq(3)").first() + val (date, time) = data.parseDateTime(addedDateEl?.text()?.trim() ?: "") + if (date.month > currentMonth) { + currentYear-- + } + currentMonth = date.month + date.year = currentYear val message = Message( - profileId, - id, - subject, - null, - Message.TYPE_SENT, - -1, - -1 + profileId = profileId, + id = id, + type = Message.TYPE_SENT, + subject = subject, + body = null, + senderId = null, + addedDate = date.combineWith(time) ) if (hasAttachments) - message.setHasAttachments() + message.hasAttachments = true - data.messageIgnoreList.add(message) + data.messageList.add(message) data.setSeenMetadataList.add( Metadata( profileId, Metadata.TYPE_MESSAGE, message.id, true, - true, - addedDate + true )) } - data.setSyncNext(ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_SENT, 1*DAY, DRAWER_ITEM_MESSAGES) + data.setSyncNext(ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_SENT, 1* DAY, DRAWER_ITEM_MESSAGES) onSuccess(ENDPOINT_MOBIDZIENNIK_WEB_MESSAGES_SENT) } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebSendMessage.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebSendMessage.kt index 074fb83e..b5a6c5ee 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebSendMessage.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebSendMessage.kt @@ -9,7 +9,6 @@ import pl.szczodrzynski.edziennik.data.api.POST 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.events.MessageSentEvent -import pl.szczodrzynski.edziennik.data.db.entity.Message import pl.szczodrzynski.edziennik.data.db.entity.Metadata import pl.szczodrzynski.edziennik.data.db.entity.Teacher @@ -43,9 +42,9 @@ class MobidziennikWebSendMessage(override val data: DataMobidziennik, // TODO create MobidziennikWebMessagesSent and replace this MobidziennikWebMessagesAll(data, null) { - val message = data.messageIgnoreList.firstOrNull { it.type == Message.TYPE_SENT && it.subject == subject } + val message = data.messageList.firstOrNull { it.isSent && it.subject == subject } val metadata = data.metadataList.firstOrNull { it.thingType == Metadata.TYPE_MESSAGE && it.thingId == message?.id } - val event = MessageSentEvent(data.profileId, message, metadata?.addedDate) + 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/mobidziennik/data/web/MobidziennikWebTimetable.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebTimetable.kt new file mode 100644 index 00000000..dd0ff03f --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/mobidziennik/data/web/MobidziennikWebTimetable.kt @@ -0,0 +1,365 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-9-8. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.web + +import android.annotation.SuppressLint +import org.jsoup.Jsoup +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.api.Regexes +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.DataMobidziennik +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.ENDPOINT_MOBIDZIENNIK_WEB_TIMETABLE +import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.MobidziennikWeb +import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel.Timetable.Companion.between +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.DAY +import pl.szczodrzynski.edziennik.ext.MS +import pl.szczodrzynski.edziennik.ext.get +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 +import kotlin.collections.set + +class MobidziennikWebTimetable( + override val data: DataMobidziennik, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : MobidziennikWeb(data, lastSync) { + companion object { + private const val TAG = "MobidziennikWebTimetable" + } + + private val rangesH = mutableMapOf, Date>() + private val hoursV = mutableMapOf>() + private var startDate: Date + + private fun parseCss(css: String): Map { + return css.split(";").mapNotNull { + val spl = it.split(":") + if (spl.size != 2) + return@mapNotNull null + return@mapNotNull spl[0].trim() to spl[1].trim() + }.toMap() + } + + private fun getRangeH(h: Float): Date? { + return rangesH.entries.firstOrNull { + h in it.key + }?.value + } + + private fun stringToDate(date: String): Date? { + val items = date.split(" ") + val day = items.getOrNull(0)?.toIntOrNull() ?: return null + val year = items.getOrNull(2)?.toIntOrNull() ?: return null + val month = when (items.getOrNull(1)) { + "stycznia" -> 1 + "lutego" -> 2 + "marca" -> 3 + "kwietnia" -> 4 + "maja" -> 5 + "czerwca" -> 6 + "lipca" -> 7 + "sierpnia" -> 8 + "września" -> 9 + "października" -> 10 + "listopada" -> 11 + "grudnia" -> 12 + else -> return null + } + return Date(year, month, day) + } + + init { + val currentWeekStart = Week.getWeekStart() + val nextWeekEnd = Week.getWeekEnd().stepForward(0, 0, 7) + if (Date.getToday().weekDay > 4) { + currentWeekStart.stepForward(0, 0, 7) + } + startDate = data.arguments?.getString("weekStart")?.let { + Date.fromY_m_d(it) + } ?: currentWeekStart + + val syncFutureDate = startDate > nextWeekEnd + val syncPastDate = startDate < currentWeekStart + val syncExtraLessons = System.currentTimeMillis() - (lastSync ?: 0) > 2 * DAY * MS + // sync not needed - everything present in the "API" + if (!syncFutureDate && !syncPastDate && !syncExtraLessons) { + onSuccess(ENDPOINT_MOBIDZIENNIK_WEB_TIMETABLE) + } + else { + val types = when { + syncFutureDate || syncPastDate -> mutableListOf("podstawowy", "pozalekcyjny") + syncExtraLessons -> mutableListOf("pozalekcyjny") + else -> mutableListOf() + } + + val syncingExtra = types.contains("pozalekcyjny") + + syncTypes(types, startDate) { + if (syncingExtra) { + val endDate = startDate.clone().stepForward(0, 0, 7) + data.toRemove.add(between(startDate, endDate, isExtra = true)) + } + + // set as synced now only when not syncing future/past date + // (to avoid waiting 2 days for normal sync after future/past sync) + if (!syncFutureDate && !syncPastDate) + data.setSyncNext(ENDPOINT_MOBIDZIENNIK_WEB_TIMETABLE, SYNC_ALWAYS) + onSuccess(ENDPOINT_MOBIDZIENNIK_WEB_TIMETABLE) + } + } + } + + private fun syncTypes(types: MutableList, startDate: Date, onSuccess: () -> Unit) { + if (types.isEmpty()) { + onSuccess() + return + } + val type = types.removeAt(0) + webGet(TAG, "/dziennik/planlekcji?typ=$type&tydzien=${startDate.stringY_m_d}") { html -> + MobidziennikLuckyNumberExtractor(data, html) + readRangesH(html) + readRangesV(html) + readLessons(html, isExtra = type == "pozalekcyjny") + syncTypes(types, startDate, onSuccess) + } + } + + private fun readRangesH(html: String) { + val htmlH = Regexes.MOBIDZIENNIK_TIMETABLE_TOP.find(html) ?: return + val docH = Jsoup.parse(htmlH.value) + + var posH = 0f + for (el in docH.select("div > div")) { + val css = parseCss(el.attr("style")) + val width = css["width"] + ?.trimEnd('%') + ?.toFloatOrNull() + ?: continue + val value = stringToDate(el.attr("title")) + ?: continue + + val range = posH.rangeTo(posH + width) + posH += width + + rangesH[range] = value + } + } + + private fun readRangesV(html: String) { + val htmlV = Regexes.MOBIDZIENNIK_TIMETABLE_LEFT.find(html) ?: return + val docV = Jsoup.parse(htmlV.value) + + for (el in docV.select("div > div")) { + val css = parseCss(el.attr("style")) + val top = css["top"] + ?.trimEnd('%') + ?.toFloatOrNull() + ?: continue + val values = el.text().split(" ") + + val time = values.getOrNull(0)?.let { + Time.fromH_m(it) + } ?: continue + val num = values.getOrNull(1)?.toIntOrNull() + + hoursV[(top * 100).toInt()] = time to num + } + } + + private val whitespaceRegex = "\\s+".toRegex() + private val classroomRegex = "\\((.*)\\)".toRegex() + private fun cleanup(str: String): List { + return str + .replace(whitespaceRegex, " ") + .replace("\n", "") + .replace("<small>", "$") + .replace("</small>", "$") + .replace("<br />", "\n") + .replace("<br/>", "\n") + .replace("<br>", "\n") + .replace("
    ", "\n") + .replace("
    ", "\n") + .replace("
    ", "\n") + .replace("", "%") + .replace("", "%") + .replace("", "") + .replace("", "") + .split("\n") + .map { it.trim() } + } + + @SuppressLint("LongLogTag", "LogNotTimber") + private fun readLessons(html: String, isExtra: Boolean) { + val matches = Regexes.MOBIDZIENNIK_TIMETABLE_CELL.findAll(html) + + val noLessonDays = mutableListOf() + for (i in 0..6) { + noLessonDays.add(startDate.clone().stepForward(0, 0, i)) + } + + for (match in matches) { + val css = parseCss("${match[1]};${match[2]}") + val left = css["left"]?.trimEnd('%')?.toFloatOrNull() ?: continue + val top = css["top"]?.trimEnd('%')?.toFloatOrNull() ?: continue + val width = css["width"]?.trimEnd('%')?.toFloatOrNull() ?: continue + val height = css["height"]?.trimEnd('%')?.toFloatOrNull() ?: continue + + val posH = left + width / 2f + val topInt = (top * 100).toInt() + val bottomInt = ((top + height) * 100).toInt() + + val lessonDate = getRangeH(posH) ?: continue + val (startTime, lessonNumber) = hoursV[topInt] ?: continue + val endTime = hoursV[bottomInt]?.first ?: continue + + noLessonDays.remove(lessonDate) + + var typeName: String? = null + var subjectName: String? = null + var teacherName: String? = null + var classroomName: String? = null + var teamName: String? = null + val items = (cleanup(match[3]) + cleanup(match[4])).toMutableList() + + // comparing items size before and after the iteration + var length = 0 + while (items.isNotEmpty() && length != items.size) { + length = items.size + var i = 0 + while (i < items.size) { + // just to remain safe - I have no idea how all of this works. + if (i < 0) + break + val item = items[i] + when { + // remove empty items + item.isEmpty() -> { + items.remove(item) + i-- + } + // remove HH:MM items - it's calculated from the block position + item.contains(":") && item.contains(" - ") -> { + items.remove(item) + i-- + } + + item.startsWith("%") -> { + // the one wrapped in % is the short subject name + items.remove(item) + // remove the first remaining item + subjectName = items.removeAt(0) + // decrement the index counter + i -= 2 + } + + item.startsWith("$") -> { + typeName = item.trim('$') + items.remove(item) + i-- + } + typeName != null && (item.contains(typeName) || item.contains("
    ")) -> { + 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 index 4857bd09..91390c5c 100644 --- 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 @@ -7,8 +7,8 @@ import pl.szczodrzynski.edziennik.data.api.edziennik.mobidziennik.data.Mobidzien 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.fixName -import pl.szczodrzynski.edziennik.set +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) { @@ -85,7 +85,7 @@ class MobidziennikFirstLogin(val data: DataMobidziennik, val onSuccess: () -> Un profileList.add(profile) } - EventBus.getDefault().post(FirstLoginFinishedEvent(profileList, data.loginStore)) + EventBus.getDefault().postSticky(FirstLoginFinishedEvent(profileList, data.loginStore)) onSuccess() } } 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 index db750981..9258886b 100644 --- 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 @@ -9,10 +9,14 @@ 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.* +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) { 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 index 78526b0c..ce801a73 100644 --- 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 @@ -11,8 +11,8 @@ 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.getUnixDate -import pl.szczodrzynski.edziennik.isNotNullNorEmpty +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) { 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..0eaaebae --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/Podlasie.kt @@ -0,0 +1,171 @@ +/* + * 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.events.UserActionRequiredEvent +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 onRequiresUserAction(event: UserActionRequiredEvent) { + callback.onRequiresUserAction(event) + } + + 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/edudziennik/login/EdudziennikLogin.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/login/PodlasieLogin.kt similarity index 67% rename from app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/edudziennik/login/EdudziennikLogin.kt rename to app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/podlasie/login/PodlasieLogin.kt index 1cb2fd07..406bb997 100644 --- 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/podlasie/login/PodlasieLogin.kt @@ -1,17 +1,17 @@ /* - * Copyright (c) Kacper Ziubryniewicz 2019-12-22 + * Copyright (c) Kacper Ziubryniewicz 2020-5-12 */ -package pl.szczodrzynski.edziennik.data.api.edziennik.edudziennik.login +package pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.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.data.api.LOGIN_METHOD_PODLASIE_API +import pl.szczodrzynski.edziennik.data.api.edziennik.podlasie.DataPodlasie import pl.szczodrzynski.edziennik.utils.Utils -class EdudziennikLogin(val data: DataEdudziennik, val onSuccess: () -> Unit) { +class PodlasieLogin(val data: DataPodlasie, val onSuccess: () -> Unit) { companion object { - private const val TAG = "EdudziennikLogin" + const val TAG = "PodlasieLogin" } private var cancelled = false @@ -45,9 +45,9 @@ class EdudziennikLogin(val data: DataEdudziennik, val onSuccess: () -> Unit) { } 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) } + 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 index dcf569cf..17644978 100644 --- 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 @@ -5,13 +5,13 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.template import pl.szczodrzynski.edziennik.App -import pl.szczodrzynski.edziennik.currentTimeUnix 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.isNotNullNorEmpty +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 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 index 9048bbcf..8abf079f 100644 --- 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 @@ -10,16 +10,17 @@ 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.events.UserActionRequiredEvent 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.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 @@ -79,7 +80,7 @@ class Template(val app: App, val profile: Profile?, val loginStore: LoginStore, } - override fun getAttachment(message: Message, attachmentId: Long, attachmentName: String) { + override fun getAttachment(owner: Any, attachmentId: Long, attachmentName: String) { } @@ -87,6 +88,10 @@ class Template(val app: App, val profile: Profile?, val loginStore: LoginStore, } + override fun getEvent(eventFull: EventFull) { + + } + override fun firstLogin() { TemplateFirstLogin(data) { completed() @@ -104,6 +109,10 @@ class Template(val app: App, val profile: Profile?, val loginStore: LoginStore, callback.onCompleted() } + override fun onRequiresUserAction(event: UserActionRequiredEvent) { + callback.onRequiresUserAction(event) + } + override fun onProgress(step: Float) { callback.onProgress(step) } 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 index d3d4c607..69e8f654 100644 --- 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 @@ -5,11 +5,11 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.template.data import com.google.gson.JsonObject -import pl.szczodrzynski.edziennik.currentTimeUnix 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 { @@ -28,6 +28,7 @@ open class TemplateApi(open val data: DataTemplate, open val lastSync: Long?) { * 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") 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 index 0db508c7..2db8c41b 100644 --- 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 @@ -5,11 +5,11 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.template.data import com.google.gson.JsonObject -import pl.szczodrzynski.edziennik.currentTimeUnix 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 { @@ -28,6 +28,7 @@ open class TemplateWeb(open val data: DataTemplate, open val lastSync: Long?) { * 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") 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 index 632a8e74..d61dc8f9 100644 --- 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 @@ -4,12 +4,12 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.template.data.api -import pl.szczodrzynski.edziennik.DAY 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?, @@ -20,7 +20,7 @@ class TemplateApiSample(override val data: DataTemplate, } init { - apiGet(TAG, "/api/v3/getData.php") { json -> + apiGet(TAG, "/api/v3/getData.php") { _ -> // here you can access and update any fields of the `data` object // ================ 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 index f0ba882e..0732710a 100644 --- 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 @@ -4,13 +4,13 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.template.data.web -import pl.szczodrzynski.edziennik.DAY 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?, @@ -21,7 +21,7 @@ class TemplateWebSample(override val data: DataTemplate, } init { - webGet(TAG, "/api/v3/getData.php") { json -> + webGet(TAG, "/api/v3/getData.php") { // here you can access and update any fields of the `data` object // ================ 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 index 02d58231..ecf41b64 100644 --- 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 @@ -4,12 +4,12 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.template.data.web -import pl.szczodrzynski.edziennik.DAY 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?, @@ -20,7 +20,7 @@ class TemplateWebSample2(override val data: DataTemplate, } init { - webGet(TAG, "/api/v3/getData.php") { json -> + webGet(TAG, "/api/v3/getData.php") { // here you can access and update any fields of the `data` object // ================ 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 index fc1fc20e..f49e433a 100644 --- 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 @@ -4,12 +4,12 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.template.login -import pl.szczodrzynski.edziennik.HOUR 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.currentTimeUnix +import pl.szczodrzynski.edziennik.ext.HOUR +import pl.szczodrzynski.edziennik.ext.currentTimeUnix class TemplateLoginApi(val data: DataTemplate, val onSuccess: () -> Unit) { companion object { 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 index d7a24ef0..2f5b72c6 100644 --- 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 @@ -4,11 +4,11 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.template.login -import pl.szczodrzynski.edziennik.currentTimeUnix 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 { diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/DataUsos.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/DataUsos.kt new file mode 100644 index 00000000..5cd054f8 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/DataUsos.kt @@ -0,0 +1,74 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2022-10-11. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.usos + +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_USOS_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 + +class DataUsos( + app: App, + profile: Profile?, + loginStore: LoginStore, +) : Data(app, profile, loginStore) { + + fun isApiLoginValid() = oauthTokenKey != null && oauthTokenSecret != null && oauthTokenIsUser + + override fun satisfyLoginMethods() { + loginMethods.clear() + if (isApiLoginValid()) { + loginMethods += LOGIN_METHOD_USOS_API + } + } + + override fun generateUserCode() = "$schoolId:${profile?.studentNumber ?: studentId}" + + var schoolId: String? + get() { mSchoolId = mSchoolId ?: loginStore.getLoginData("schoolId", null); return mSchoolId } + set(value) { loginStore.putLoginData("schoolId", value); mSchoolId = value } + private var mSchoolId: String? = null + + var instanceUrl: String? + get() { mInstanceUrl = mInstanceUrl ?: loginStore.getLoginData("instanceUrl", null); return mInstanceUrl } + set(value) { loginStore.putLoginData("instanceUrl", value); mInstanceUrl = value } + private var mInstanceUrl: String? = null + + var oauthLoginResponse: String? + get() { mOauthLoginResponse = mOauthLoginResponse ?: loginStore.getLoginData("oauthLoginResponse", null); return mOauthLoginResponse } + set(value) { loginStore.putLoginData("oauthLoginResponse", value); mOauthLoginResponse = value } + private var mOauthLoginResponse: String? = null + + var oauthConsumerKey: String? + get() { mOauthConsumerKey = mOauthConsumerKey ?: loginStore.getLoginData("oauthConsumerKey", null); return mOauthConsumerKey } + set(value) { loginStore.putLoginData("oauthConsumerKey", value); mOauthConsumerKey = value } + private var mOauthConsumerKey: String? = null + + var oauthConsumerSecret: String? + get() { mOauthConsumerSecret = mOauthConsumerSecret ?: loginStore.getLoginData("oauthConsumerSecret", null); return mOauthConsumerSecret } + set(value) { loginStore.putLoginData("oauthConsumerSecret", value); mOauthConsumerSecret = value } + private var mOauthConsumerSecret: String? = null + + var oauthTokenKey: String? + get() { mOauthTokenKey = mOauthTokenKey ?: loginStore.getLoginData("oauthTokenKey", null); return mOauthTokenKey } + set(value) { loginStore.putLoginData("oauthTokenKey", value); mOauthTokenKey = value } + private var mOauthTokenKey: String? = null + + var oauthTokenSecret: String? + get() { mOauthTokenSecret = mOauthTokenSecret ?: loginStore.getLoginData("oauthTokenSecret", null); return mOauthTokenSecret } + set(value) { loginStore.putLoginData("oauthTokenSecret", value); mOauthTokenSecret = value } + private var mOauthTokenSecret: String? = null + + var oauthTokenIsUser: Boolean + get() { mOauthTokenIsUser = mOauthTokenIsUser ?: loginStore.getLoginData("oauthTokenIsUser", false); return mOauthTokenIsUser ?: false } + set(value) { loginStore.putLoginData("oauthTokenIsUser", value); mOauthTokenIsUser = value } + private var mOauthTokenIsUser: Boolean? = 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 mStudentId: Int? = null +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/Usos.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/Usos.kt new file mode 100644 index 00000000..cbf92ca8 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/Usos.kt @@ -0,0 +1,116 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2022-10-11. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.usos + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.data.UsosData +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.firstlogin.UsosFirstLogin +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.login.UsosLogin +import pl.szczodrzynski.edziennik.data.api.events.UserActionRequiredEvent +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.usosLoginMethods +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 Usos( + val app: App, + val profile: Profile?, + val loginStore: LoginStore, + val callback: EdziennikCallback, +) : EdziennikInterface { + companion object { + private const val TAG = "Usos" + } + + val internalErrorList = mutableListOf() + val data: DataUsos + + init { + data = DataUsos(app, profile, loginStore).apply { + callback = wrapCallback(this@Usos.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(usosLoginMethods, UsosFeatures, featureIds, viewId, onlyEndpoints) + d(TAG, "LoginMethod IDs: ${data.targetLoginMethodIds}") + d(TAG, "Endpoint IDs: ${data.targetEndpointIds}") + UsosLogin(data) { + UsosData(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() { + UsosFirstLogin(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 onRequiresUserAction(event: UserActionRequiredEvent) { + callback.onRequiresUserAction(event) + } + + 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) + } + else -> callback.onError(apiError) + } + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/UsosFeatures.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/UsosFeatures.kt new file mode 100644 index 00000000..50c15582 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/UsosFeatures.kt @@ -0,0 +1,39 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2022-10-11. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.usos + +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.models.Feature + +const val ENDPOINT_USOS_API_USER = 7000 +const val ENDPOINT_USOS_API_TERMS = 7010 +const val ENDPOINT_USOS_API_COURSES = 7020 +const val ENDPOINT_USOS_API_TIMETABLE = 7030 + +val UsosFeatures = listOf( + /* + * Student information + */ + Feature(LOGIN_TYPE_USOS, FEATURE_STUDENT_INFO, listOf( + ENDPOINT_USOS_API_USER to LOGIN_METHOD_USOS_API, + ), listOf(LOGIN_METHOD_USOS_API)), + + /* + * Terms & courses + */ + Feature(LOGIN_TYPE_USOS, FEATURE_SCHOOL_INFO, listOf( + ENDPOINT_USOS_API_TERMS to LOGIN_METHOD_USOS_API, + ), listOf(LOGIN_METHOD_USOS_API)), + Feature(LOGIN_TYPE_USOS, FEATURE_TEAM_INFO, listOf( + ENDPOINT_USOS_API_COURSES to LOGIN_METHOD_USOS_API, + ), listOf(LOGIN_METHOD_USOS_API)), + + /* + * Timetable + */ + Feature(LOGIN_TYPE_USOS, FEATURE_TIMETABLE, listOf( + ENDPOINT_USOS_API_TIMETABLE to LOGIN_METHOD_USOS_API, + ), listOf(LOGIN_METHOD_USOS_API)), +) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/UsosApi.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/UsosApi.kt new file mode 100644 index 00000000..9f716d50 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/UsosApi.kt @@ -0,0 +1,209 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2022-10-13. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.usos.data + +import com.google.gson.JsonArray +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.JsonArrayCallbackHandler +import im.wangchao.mhttp.callback.JsonCallbackHandler +import im.wangchao.mhttp.callback.TextCallbackHandler +import pl.szczodrzynski.edziennik.data.api.ERROR_REQUEST_FAILURE +import pl.szczodrzynski.edziennik.data.api.ERROR_USOS_API_MISSING_RESPONSE +import pl.szczodrzynski.edziennik.data.api.SERVER_USER_AGENT +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.DataUsos +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.login.UsosLoginApi +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.UUID + +open class UsosApi(open val data: DataUsos, open val lastSync: Long?) { + companion object { + private const val TAG = "UsosApi" + } + + enum class ResponseType { + OBJECT, + ARRAY, + PLAIN, + } + + val profileId + get() = data.profile?.id ?: -1 + + val profile + get() = data.profile + + protected fun JsonObject.getLangString(key: String) = + this.getJsonObject(key)?.getString("pl") + + protected fun JsonObject.getLecturerIds(key: String) = + this.getJsonArray(key)?.asJsonObjectList()?.mapNotNull { + val id = it.getLong("id") ?: return@mapNotNull null + val firstName = it.getString("first_name") ?: return@mapNotNull null + val lastName = it.getString("last_name") ?: return@mapNotNull null + data.getTeacher(firstName, lastName, id = id).id + } ?: listOf() + + private fun valueToString(value: Any) = when (value) { + is String -> value + is Number -> value.toString() + is List<*> -> listToString(value) + else -> value.toString() + } + + private fun listToString(list: List<*>): String { + return list.map { + if (it is Pair<*, *> && it.first is String && it.second is List<*>) + return@map "${it.first}[${listToString(it.second as List<*>)}]" + return@map valueToString(it ?: "") + }.joinToString("|") + } + + private fun buildSignature(method: String, url: String, params: Map): String { + val query = params.toQueryString() + val signatureString = listOf( + method.uppercase(), + url.urlEncode(), + query.urlEncode(), + ).joinToString("&") + val signingKey = listOf( + data.oauthConsumerSecret ?: "", + data.oauthTokenSecret ?: "", + ).joinToString("&") { it.urlEncode() } + return signatureString.hmacSHA1(signingKey) + } + + fun apiRequest( + tag: String, + service: String, + params: Map? = null, + fields: List? = null, + responseType: ResponseType, + onSuccess: (data: T, response: Response?) -> Unit, + ) { + val url = "${data.instanceUrl}services/$service" + d(tag, "Request: Usos/Api - $url") + + val formData = mutableMapOf() + if (params != null) + formData.putAll(params.mapValues { + valueToString(it.value) + }) + if (fields != null) + formData["fields"] = valueToString(fields) + + val auth = mutableMapOf( + "realm" to url, + "oauth_consumer_key" to (data.oauthConsumerKey ?: ""), + "oauth_nonce" to UUID.randomUUID().toString(), + "oauth_signature_method" to "HMAC-SHA1", + "oauth_timestamp" to currentTimeUnix().toString(), + "oauth_token" to (data.oauthTokenKey ?: ""), + "oauth_version" to "1.0", + ) + val signature = buildSignature( + method = "POST", + url = url, + params = formData + auth.filterKeys { it.startsWith("oauth_") }, + ) + auth["oauth_signature"] = signature + + val authString = auth.map { + """${it.key}="${it.value.urlEncode()}"""" + }.joinToString(", ") + + Request.builder() + .url(url) + .userAgent(SERVER_USER_AGENT) + .addHeader("Authorization", "OAuth $authString") + .post() + .setTextBody(formData.toQueryString(), MediaTypeUtils.APPLICATION_FORM) + .allowErrorCode(HTTP_BAD_REQUEST) + .allowErrorCode(HTTP_UNAUTHORIZED) + .allowErrorCode(HTTP_FORBIDDEN) + .allowErrorCode(HTTP_NOT_FOUND) + .allowErrorCode(HTTP_UNAVAILABLE) + .callback(getCallback(tag, responseType, onSuccess)) + .build() + .enqueue() + } + + @Suppress("UNCHECKED_CAST") + private fun getCallback( + tag: String, + responseType: ResponseType, + onSuccess: (data: T, response: Response?) -> Unit, + ) = when (responseType) { + ResponseType.OBJECT -> object : JsonCallbackHandler() { + override fun onSuccess(data: JsonObject?, response: Response) { + processResponse(tag, response, data as T?, onSuccess) + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + processError(tag, response, throwable) + } + } + ResponseType.ARRAY -> object : JsonArrayCallbackHandler() { + override fun onSuccess(data: JsonArray?, response: Response) { + processResponse(tag, response, data as T?, onSuccess) + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + processError(tag, response, throwable) + } + } + ResponseType.PLAIN -> object : TextCallbackHandler() { + override fun onSuccess(data: String?, response: Response) { + processResponse(tag, response, data as T?, onSuccess) + } + + override fun onFailure(response: Response?, throwable: Throwable?) { + processError(tag, response, throwable) + } + } + } + + private fun processResponse( + tag: String, + response: Response, + value: T?, + onSuccess: (data: T, response: Response?) -> Unit, + ) { + val errorCode = when { + response.code() == HTTP_UNAUTHORIZED -> { + data.oauthTokenKey = null + data.oauthTokenSecret = null + data.oauthTokenIsUser = false + data.oauthLoginResponse = null + UsosLoginApi(data) { } + return + } + value == null -> ERROR_USOS_API_MISSING_RESPONSE + response.code() == HTTP_OK -> { + onSuccess(value, response) + null + } + else -> response.toErrorCode() + } + if (errorCode != null) { + data.error(tag, errorCode, response, value.toString()) + } + } + + private fun processError( + tag: String, + response: Response?, + throwable: Throwable?, + ) { + data.error(ApiError(tag, ERROR_REQUEST_FAILURE) + .withResponse(response) + .withThrowable(throwable)) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/UsosData.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/UsosData.kt new file mode 100644 index 00000000..d688bebf --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/UsosData.kt @@ -0,0 +1,64 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2022-10-13. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.usos.data + +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.api.edziennik.template.data.web.TemplateWebSample +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.* +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.data.api.UsosApiCourses +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.data.api.UsosApiTerms +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.data.api.UsosApiTimetable +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.data.api.UsosApiUser +import pl.szczodrzynski.edziennik.utils.Utils.d + +class UsosData(val data: DataUsos, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "UsosData" + } + + 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) { + d(TAG, "Using endpoint $endpointId. Last sync time = $lastSync") + when (endpointId) { + ENDPOINT_USOS_API_USER -> { + data.startProgress(R.string.edziennik_progress_endpoint_student_info) + UsosApiUser(data, lastSync, onSuccess) + } + ENDPOINT_USOS_API_TERMS -> { + data.startProgress(R.string.edziennik_progress_endpoint_school_info) + UsosApiTerms(data, lastSync, onSuccess) + } + ENDPOINT_USOS_API_COURSES -> { + data.startProgress(R.string.edziennik_progress_endpoint_teams) + UsosApiCourses(data, lastSync, onSuccess) + } + ENDPOINT_USOS_API_TIMETABLE -> { + data.startProgress(R.string.edziennik_progress_endpoint_timetable) + UsosApiTimetable(data, lastSync, onSuccess) + } + else -> onSuccess(endpointId) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/api/UsosApiCourses.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/api/UsosApiCourses.kt new file mode 100644 index 00000000..e93c63dd --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/api/UsosApiCourses.kt @@ -0,0 +1,87 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2022-10-15. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.usos.data.api + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.data.api.ERROR_USOS_API_INCOMPLETE_RESPONSE +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.DataUsos +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.ENDPOINT_USOS_API_COURSES +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.data.UsosApi +import pl.szczodrzynski.edziennik.data.db.entity.Team +import pl.szczodrzynski.edziennik.ext.* + +class UsosApiCourses( + override val data: DataUsos, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit, +) : UsosApi(data, lastSync) { + companion object { + const val TAG = "UsosApiCourses" + } + + init { + apiRequest( + tag = TAG, + service = "courses/user", + fields = listOf( + // "terms" to listOf("id", "name", "start_date", "end_date"), + "course_editions" to listOf( + "course_id", + "course_name", + // "term_id", + "user_groups" to listOf( + "course_unit_id", + "group_number", + // "class_type", + "class_type_id", + "lecturers", + ), + ), + ), + responseType = ResponseType.OBJECT, + ) { json, response -> + if (!processResponse(json)) { + data.error(TAG, ERROR_USOS_API_INCOMPLETE_RESPONSE, response) + return@apiRequest + } + + data.setSyncNext(ENDPOINT_USOS_API_COURSES, 2 * DAY) + onSuccess(ENDPOINT_USOS_API_COURSES) + } + } + + private fun processResponse(json: JsonObject): Boolean { + // val term = json.getJsonArray("terms")?.firstOrNull() ?: return false + val courseEditions = json.getJsonObject("course_editions") + ?.entrySet() + ?.flatMap { it.value.asJsonArray } + ?.map { it.asJsonObject } ?: return false + + var hasValidTeam = false + for (courseEdition in courseEditions) { + val courseId = courseEdition.getString("course_id") ?: continue + val courseName = courseEdition.getLangString("course_name") ?: continue + val userGroups = courseEdition.getJsonArray("user_groups")?.asJsonObjectList() ?: continue + for (userGroup in userGroups) { + val courseUnitId = userGroup.getLong("course_unit_id") ?: continue + val groupNumber = userGroup.getInt("group_number") ?: continue + // val classType = userGroup.getLangString("class_type") ?: continue + val classTypeId = userGroup.getString("class_type_id") ?: continue + val lecturers = userGroup.getLecturerIds("lecturers") + + data.teamList.put(courseUnitId, Team( + profileId, + courseUnitId, + "${profile?.studentClassName} $classTypeId$groupNumber - $courseName", + 2, + "${data.schoolId}:${courseId} $classTypeId$groupNumber", + lecturers.firstOrNull() ?: -1L, + )) + hasValidTeam = true + } + } + return hasValidTeam + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/api/UsosApiTerms.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/api/UsosApiTerms.kt new file mode 100644 index 00000000..1bf47288 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/api/UsosApiTerms.kt @@ -0,0 +1,64 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2022-10-15. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.usos.data.api + +import com.google.gson.JsonArray +import pl.szczodrzynski.edziennik.data.api.ERROR_USOS_API_INCOMPLETE_RESPONSE +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.DataUsos +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.ENDPOINT_USOS_API_TERMS +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.data.UsosApi +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.models.Date + +class UsosApiTerms( + override val data: DataUsos, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit, +) : UsosApi(data, lastSync) { + companion object { + const val TAG = "UsosApiTerms" + } + + init { + apiRequest( + tag = TAG, + service = "terms/search", + params = mapOf( + "query" to Date.getToday().year.toString(), + ), + responseType = ResponseType.ARRAY, + ) { json, response -> + if (!processResponse(json)) { + data.error(TAG, ERROR_USOS_API_INCOMPLETE_RESPONSE, response) + return@apiRequest + } + + data.setSyncNext(ENDPOINT_USOS_API_TERMS, 7 * DAY) + onSuccess(ENDPOINT_USOS_API_TERMS) + } + } + + private fun processResponse(json: JsonArray): Boolean { + val dates = mutableSetOf() + for (term in json.asJsonObjectList()) { + if (!term.getBoolean("is_active", false)) + continue + val startDate = term.getString("start_date")?.let { Date.fromY_m_d(it) } + val finishDate = term.getString("finish_date")?.let { Date.fromY_m_d(it) } + if (startDate != null) + dates += startDate + if (finishDate != null) + dates += finishDate + } + val datesSorted = dates.sorted() + if (datesSorted.size != 3) + return false + profile?.studentSchoolYearStart = datesSorted[0].year + profile?.dateSemester1Start = datesSorted[0] + profile?.dateSemester2Start = datesSorted[1] + profile?.dateYearEnd = datesSorted[2] + return true + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/api/UsosApiTimetable.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/api/UsosApiTimetable.kt new file mode 100644 index 00000000..6c1acc54 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/api/UsosApiTimetable.kt @@ -0,0 +1,141 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2022-10-16. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.usos.data.api + +import com.google.gson.JsonArray +import pl.szczodrzynski.edziennik.data.api.ERROR_USOS_API_INCOMPLETE_RESPONSE +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.DataUsos +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.ENDPOINT_USOS_API_TIMETABLE +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.data.UsosApi +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.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time +import pl.szczodrzynski.edziennik.utils.models.Week + +class UsosApiTimetable( + override val data: DataUsos, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit, +) : UsosApi(data, lastSync) { + companion object { + const val TAG = "UsosApiTimetable" + } + + init { + val currentWeekStart = Week.getWeekStart() + if (Date.getToday().weekDay > 4) + currentWeekStart.stepForward(0, 0, 7) + + val weekStart = data.arguments + ?.getString("weekStart") + ?.let { Date.fromY_m_d(it) } + ?: currentWeekStart + val weekEnd = weekStart.clone().stepForward(0, 0, 6) + + apiRequest( + tag = TAG, + service = "tt/user", + params = mapOf( + "start" to weekStart.stringY_m_d, + "days" to 7, + ), + fields = listOf( + "type", + "start_time", + "end_time", + "unit_id", + "course_id", + "course_name", + "lecturer_ids", + "building_id", + "room_number", + "classtype_id", + "group_number", + ), + responseType = ResponseType.ARRAY, + ) { json, response -> + if (!processResponse(json, weekStart..weekEnd)) { + data.error(TAG, ERROR_USOS_API_INCOMPLETE_RESPONSE, response) + return@apiRequest + } + + data.toRemove.add(DataRemoveModel.Timetable.between(weekStart, weekEnd)) + data.setSyncNext(ENDPOINT_USOS_API_TIMETABLE, SYNC_ALWAYS) + onSuccess(ENDPOINT_USOS_API_TIMETABLE) + } + } + + private fun processResponse(json: JsonArray, syncRange: ClosedRange): Boolean { + val foundDates = mutableSetOf() + + for (activity in json.asJsonObjectList()) { + val type = activity.getString("type") + if (type !in listOf("classgroup", "classgroup2")) + continue + + val startTime = activity.getString("start_time") ?: continue + val endTime = activity.getString("end_time") ?: continue + val unitId = activity.getLong("unit_id", -1) + val courseName = activity.getLangString("course_name") ?: continue + val courseId = activity.getString("course_id") ?: continue + val lecturerIds = activity.getJsonArray("lecturer_ids")?.map { it.asLong } + val buildingId = activity.getString("building_id") + val roomNumber = activity.getString("room_number") + val classTypeId = activity.getString("classtype_id") + val groupNumber = activity.getString("group_number") + + val lesson = Lesson(profileId, -1).also { + it.type = Lesson.TYPE_NORMAL + it.date = Date.fromY_m_d(startTime) + it.startTime = Time.fromY_m_d_H_m_s(startTime) + it.endTime = Time.fromY_m_d_H_m_s(endTime) + it.subjectId = data.getSubject( + id = null, + name = courseName, + shortName = courseId, + ).id + it.teacherId = lecturerIds?.firstOrNull() ?: -1L + it.teamId = unitId + val groupName = classTypeId?.plus(groupNumber)?.let { s -> "($s)" } + it.classroom = "$buildingId / $roomNumber ${groupName ?: ""}" + it.id = it.buildId() + + it.color = when (classTypeId) { + "WYK" -> 0xff0d6091 + "CW" -> 0xff54306e + "LAB" -> 0xff772747 + "KON" -> 0xff1e5128 + "^P?SEM" -> 0xff1e5128 // TODO make it regex + else -> 0xff08534c + }.toInt() + } + lesson.date?.let { foundDates += it } + + val seen = profile?.empty != false || lesson.date!! < Date.getToday() + data.lessonList.add(lesson) + if (lesson.type != Lesson.TYPE_NORMAL) + data.metadataList += Metadata( + profileId, + Metadata.TYPE_LESSON_CHANGE, + lesson.id, + seen, + seen, + ) + } + + val notFoundDates = syncRange.asSequence() - foundDates + for (date in notFoundDates) { + data.lessonList += Lesson(profileId, date.value.toLong()).also { + it.type = Lesson.TYPE_NO_LESSONS + it.date = date + } + } + return true + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/api/UsosApiUser.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/api/UsosApiUser.kt new file mode 100644 index 00000000..29a3e22b --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/data/api/UsosApiUser.kt @@ -0,0 +1,72 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2022-10-16. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.usos.data.api + +import com.google.gson.JsonObject +import pl.szczodrzynski.edziennik.data.api.ERROR_USOS_NO_STUDENT_PROGRAMMES +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.DataUsos +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.ENDPOINT_USOS_API_USER +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.data.UsosApi +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.* + +class UsosApiUser( + override val data: DataUsos, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit, +) : UsosApi(data, lastSync) { + companion object { + const val TAG = "UsosApiUser" + } + + init { + apiRequest( + tag = TAG, + service = "users/user", + params = mapOf( + "fields" to listOf( + "id", + "first_name", + "last_name", + "student_number", + "student_programmes" to listOf( + "programme" to listOf("id"), + ), + ), + ), + responseType = ResponseType.OBJECT, + ) { json, response -> + val programmes = json.getJsonArray("student_programmes") + if (programmes.isNullOrEmpty()) { + data.error(ApiError(TAG, ERROR_USOS_NO_STUDENT_PROGRAMMES) + .withApiResponse(json) + .withResponse(response)) + return@apiRequest + } + + val firstName = json.getString("first_name") + val lastName = json.getString("last_name") + val studentName = buildFullName(firstName, lastName) + + data.studentId = json.getInt("id") ?: data.studentId + profile?.studentNameLong = studentName + profile?.studentNameShort = studentName.getShortName() + profile?.studentNumber = json.getInt("student_number", -1) + profile?.studentClassName = programmes.getJsonObject(0).getJsonObject("programme").getString("id") + + profile?.studentClassName?.let { + data.getTeam( + id = null, + name = it, + schoolCode = data.schoolId ?: "", + isTeamClass = true, + ) + } + + data.setSyncNext(ENDPOINT_USOS_API_USER, 4 * DAY) + onSuccess(ENDPOINT_USOS_API_USER) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/firstlogin/UsosFirstLogin.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/firstlogin/UsosFirstLogin.kt new file mode 100644 index 00000000..4cb38cc6 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/firstlogin/UsosFirstLogin.kt @@ -0,0 +1,84 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2022-10-14. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.usos.firstlogin + +import com.google.gson.JsonObject +import org.greenrobot.eventbus.EventBus +import pl.szczodrzynski.edziennik.data.api.ERROR_USOS_NO_STUDENT_PROGRAMMES +import pl.szczodrzynski.edziennik.data.api.LOGIN_TYPE_USOS +import pl.szczodrzynski.edziennik.data.api.edziennik.librus.firstlogin.LibrusFirstLogin +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.DataUsos +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.data.UsosApi +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.login.UsosLoginApi +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 UsosFirstLogin(val data: DataUsos, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "UsosFirstLogin" + } + + private val api = UsosApi(data, null) + + init { + val loginStoreId = data.loginStore.id + val loginStoreType = LOGIN_TYPE_USOS + var firstProfileId = loginStoreId + + UsosLoginApi(data) { + api.apiRequest( + tag = TAG, + service = "users/user", + params = mapOf( + "fields" to listOf( + "id", + "first_name", + "last_name", + "student_number", + "student_programmes" to listOf( + "programme" to listOf("id"), + ), + ), + ), + responseType = UsosApi.ResponseType.OBJECT, + ) { json, response -> + val programmes = json.getJsonArray("student_programmes") + if (programmes.isNullOrEmpty()) { + data.error(ApiError(TAG, ERROR_USOS_NO_STUDENT_PROGRAMMES) + .withApiResponse(json) + .withResponse(response)) + return@apiRequest + } + + val firstName = json.getString("first_name") + val lastName = json.getString("last_name") + val studentName = buildFullName(firstName, lastName) + + val profile = Profile( + id = firstProfileId++, + loginStoreId = loginStoreId, loginStoreType = loginStoreType, + name = studentName, + subname = data.schoolId, + studentNameLong = studentName, + studentNameShort = studentName.getShortName(), + accountName = null, // student account + studentData = JsonObject( + "studentId" to json.getInt("id"), + ), + ).also { + it.studentNumber = json.getInt("student_number", -1) + it.studentClassName = programmes.getJsonObject(0).getJsonObject("programme").getString("id") + } + + EventBus.getDefault().postSticky( + FirstLoginFinishedEvent(listOf(profile), data.loginStore), + ) + onSuccess() + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/login/IdziennikLogin.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/login/UsosLogin.kt similarity index 53% rename from app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/login/IdziennikLogin.kt rename to app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/login/UsosLogin.kt index e1cef5c1..599b8f16 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/idziennik/login/IdziennikLogin.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/login/UsosLogin.kt @@ -1,18 +1,17 @@ /* - * Copyright (c) Kuba Szczodrzyński 2019-10-25. + * Copyright (c) Kuba Szczodrzyński 2022-10-11. */ -package pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.login +package pl.szczodrzynski.edziennik.data.api.edziennik.usos.login import pl.szczodrzynski.edziennik.R -import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_IDZIENNIK_API -import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_IDZIENNIK_WEB -import pl.szczodrzynski.edziennik.data.api.edziennik.idziennik.DataIdziennik -import pl.szczodrzynski.edziennik.utils.Utils +import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_USOS_API +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.DataUsos +import pl.szczodrzynski.edziennik.utils.Utils.d -class IdziennikLogin(val data: DataIdziennik, val onSuccess: () -> Unit) { +class UsosLogin(val data: DataUsos, val onSuccess: () -> Unit) { companion object { - private const val TAG = "IdziennikLogin" + private const val TAG = "UsosLogin" } private var cancelled = false @@ -44,15 +43,11 @@ class IdziennikLogin(val data: DataIdziennik, val onSuccess: () -> Unit) { onSuccess(-1) return } - Utils.d(TAG, "Using login method $loginMethodId") + d(TAG, "Using login method $loginMethodId") when (loginMethodId) { - LOGIN_METHOD_IDZIENNIK_WEB -> { - data.startProgress(R.string.edziennik_progress_login_idziennik_web) - IdziennikLoginWeb(data) { onSuccess(loginMethodId) } - } - LOGIN_METHOD_IDZIENNIK_API -> { - data.startProgress(R.string.edziennik_progress_login_idziennik_api) - IdziennikLoginApi(data) { onSuccess(loginMethodId) } + LOGIN_METHOD_USOS_API -> { + data.startProgress(R.string.edziennik_progress_login_usos_api) + UsosLoginApi(data) { onSuccess(loginMethodId) } } } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/login/UsosLoginApi.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/login/UsosLoginApi.kt new file mode 100644 index 00000000..06651477 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/usos/login/UsosLoginApi.kt @@ -0,0 +1,113 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2022-10-11. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.usos.login + +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.DataUsos +import pl.szczodrzynski.edziennik.data.api.edziennik.usos.data.UsosApi +import pl.szczodrzynski.edziennik.data.api.events.UserActionRequiredEvent +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.Utils.d + +class UsosLoginApi(val data: DataUsos, val onSuccess: () -> Unit) { + companion object { + private const val TAG = "UsosLoginApi" + } + + private val api = UsosApi(data, null) + + init { + run { + data.arguments?.getString("oauthLoginResponse")?.let { + data.oauthLoginResponse = it + } + if (data.isApiLoginValid()) { + onSuccess() + } else if (data.oauthLoginResponse != null) { + login() + } else { + authorize() + } + } + } + + private fun authorize() { + data.oauthTokenKey = null + data.oauthTokenSecret = null + api.apiRequest( + tag = TAG, + service = "oauth/request_token", + params = mapOf( + "oauth_callback" to USOS_API_OAUTH_REDIRECT_URL, + "scopes" to USOS_API_SCOPES, + ), + responseType = UsosApi.ResponseType.PLAIN, + ) { text, _ -> + val authorizeData = text.fromQueryString() + data.oauthTokenKey = authorizeData["oauth_token"] + data.oauthTokenSecret = authorizeData["oauth_token_secret"] + data.oauthTokenIsUser = false + + val authUrl = "${data.instanceUrl}services/oauth/authorize" + val authParams = mapOf( + "interactivity" to "confirm_user", + "oauth_token" to (data.oauthTokenKey ?: ""), + ) + data.requireUserAction( + type = UserActionRequiredEvent.Type.OAUTH, + params = Bundle( + "authorizeUrl" to "$authUrl?${authParams.toQueryString()}", + "redirectUrl" to USOS_API_OAUTH_REDIRECT_URL, + "responseStoreKey" to "oauthLoginResponse", + "extras" to data.loginStore.data.toBundle(), + ), + errorText = R.string.notification_user_action_required_oauth_usos, + ) + } + } + + private fun login() { + d(TAG, "Login to ${data.schoolId} with ${data.oauthLoginResponse}") + + val authorizeResponse = data.oauthLoginResponse?.fromQueryString() + ?: return // checked in init {} + if (authorizeResponse["oauth_token"] != data.oauthTokenKey) { + // got different token + data.error(ApiError(TAG, ERROR_USOS_OAUTH_GOT_DIFFERENT_TOKEN) + .withApiResponse(data.oauthLoginResponse)) + return + } + val verifier = authorizeResponse["oauth_verifier"] + if (verifier.isNullOrBlank()) { + data.error(ApiError(TAG, ERROR_USOS_OAUTH_INCOMPLETE_RESPONSE) + .withApiResponse(data.oauthLoginResponse)) + return + } + + api.apiRequest( + tag = TAG, + service = "oauth/access_token", + params = mapOf( + "oauth_verifier" to verifier, + ), + responseType = UsosApi.ResponseType.PLAIN, + ) { text, response -> + val accessData = text.fromQueryString() + data.oauthTokenKey = accessData["oauth_token"] + data.oauthTokenSecret = accessData["oauth_token_secret"] + data.oauthTokenIsUser = data.oauthTokenKey != null && data.oauthTokenSecret != null + data.loginStore.removeLoginData("oauthLoginResponse") + + if (!data.oauthTokenIsUser) + data.error(ApiError(TAG, ERROR_USOS_OAUTH_INCOMPLETE_RESPONSE) + .withApiResponse(text) + .withResponse(response)) + else + 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 index d326ebd4..0c2bc91c 100644 --- 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 @@ -4,52 +4,50 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan +import com.google.gson.JsonObject import pl.szczodrzynski.edziennik.App -import pl.szczodrzynski.edziennik.currentTimeUnix -import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_VULCAN_API +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.data.db.entity.Team -import pl.szczodrzynski.edziennik.isNotNullNorEmpty -import pl.szczodrzynski.edziennik.utils.Utils -import pl.szczodrzynski.edziennik.values +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 isApiLoginValid() = currentSemesterEndDate-30 > currentTimeUnix() - && apiCertificateKey.isNotNullNorEmpty() - && apiCertificatePrivate.isNotNullNorEmpty() + 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 (isApiLoginValid()) { - loginMethods += LOGIN_METHOD_VULCAN_API + if (isWebMainLoginValid()) { + loginMethods += LOGIN_METHOD_VULCAN_WEB_MAIN + } + if (isHebeLoginValid()) { + loginMethods += LOGIN_METHOD_VULCAN_HEBE } } - init { - // during the first sync `profile.studentClassName` is already set - if (teamList.values().none { it.type == Team.TYPE_CLASS }) { - profile?.studentClassName?.also { name -> - val id = Utils.crc16(name.toByteArray()).toLong() + override fun generateUserCode() = "$schoolCode:$studentId" - val teamObject = Team( - profileId, - id, - name, - Team.TYPE_CLASS, - "$schoolName:$name", - -1 - ) - teamList.put(id, teamObject) - } - } + 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" } - override fun generateUserCode() = "$schoolName:$studentId" - /** * A UONET+ client symbol. * @@ -59,8 +57,8 @@ class DataVulcan(app: App, profile: Profile?, loginStore: LoginStore) : Data(app */ private var mSymbol: String? = null var symbol: String? - get() { mSymbol = mSymbol ?: loginStore.getLoginData("deviceSymbol", null); return mSymbol } - set(value) { loginStore.putLoginData("deviceSymbol", value); mSymbol = value } + 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. @@ -75,16 +73,26 @@ class DataVulcan(app: App, profile: Profile?, loginStore: LoginStore) : Data(app set(value) { profile?.putStudentData("schoolSymbol", value) ?: return; mSchoolSymbol = value } /** - * A school ID consisting of the [symbol] and [schoolSymbol]. + * 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 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 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. @@ -124,6 +132,25 @@ class DataVulcan(app: App, profile: Profile?, loginStore: LoginStore) : Data(app 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 */ @@ -154,45 +181,60 @@ class DataVulcan(app: App, profile: Profile?, loginStore: LoginStore) : Data(app * After first login only 3 first characters are stored here. * This is later used to determine the API URL address. */ - private var mApiToken: String? = null - var apiToken: String? - get() { mApiToken = mApiToken ?: loginStore.getLoginData("deviceToken", null); return mApiToken } - set(value) { loginStore.putLoginData("deviceToken", value); mApiToken = value } + 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: String? = null - var apiPin: String? - get() { mApiPin = mApiPin ?: loginStore.getLoginData("devicePin", null); return mApiPin } - set(value) { loginStore.putLoginData("devicePin", value); mApiPin = value } + 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 mApiCertificateKey: String? = null - var apiCertificateKey: String? - get() { mApiCertificateKey = mApiCertificateKey ?: loginStore.getLoginData("certificateKey", null); return mApiCertificateKey } - set(value) { loginStore.putLoginData("certificateKey", value); mApiCertificateKey = 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 } - /** - * This is not meant for normal usage. - * - * It provides a backward compatibility (<4.0) in order - * to migrate and use private keys instead of PFX. - */ - private var mApiCertificatePfx: String? = null - var apiCertificatePfx: String? - get() { mApiCertificatePfx = mApiCertificatePfx ?: loginStore.getLoginData("certificatePfx", null); return mApiCertificatePfx } - set(value) { loginStore.putLoginData("certificatePfx", value); mApiCertificatePfx = 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 mApiCertificatePrivate: String? = null - var apiCertificatePrivate: String? - get() { mApiCertificatePrivate = mApiCertificatePrivate ?: loginStore.getLoginData("certificatePrivate", null); return mApiCertificatePrivate } - set(value) { loginStore.putLoginData("certificatePrivate", value); mApiCertificatePrivate = 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 mMessageBoxKey: String? = null + var messageBoxKey: String? + get() { mMessageBoxKey = mMessageBoxKey ?: profile?.getStudentData("messageBoxKey", null); return mMessageBoxKey } + set(value) { profile?.putStudentData("messageBoxKey", value) ?: return; mMessageBoxKey = value } + + private var mMessageBoxName: String? = null + var messageBoxName: String? + get() { mMessageBoxName = mMessageBoxName ?: profile?.getStudentData("messageBoxName", null); return mMessageBoxName } + set(value) { profile?.putStudentData("messageBoxName", value) ?: return; mMessageBoxName = value } val apiUrl: String? get() { - val url = when (apiToken?.substring(0, 3)) { + 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" @@ -206,6 +248,7 @@ class DataVulcan(app: App, profile: Profile?, loginStore: LoginStore) : Data(app "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 @@ -213,8 +256,65 @@ class DataVulcan(app: App, profile: Profile?, loginStore: LoginStore) : Data(app return if (url != null) "$url/$symbol/" else loginStore.getLoginData("apiUrl", null) } - val fullApiUrl: String? + 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 index 4e6def85..37af4b69 100644 --- 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 @@ -5,26 +5,31 @@ 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.LOGIN_METHOD_VULCAN_API +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.api.VulcanApiMessagesChangeStatus -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.api.VulcanApiSendMessage +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.events.UserActionRequiredEvent 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.prepareFor -import pl.szczodrzynski.edziennik.data.api.vulcanLoginMethods 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 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 { @@ -62,6 +67,11 @@ class Vulcan(val app: App, val profile: Profile?, val loginStore: LoginStore, va } 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:") @@ -86,35 +96,79 @@ class Vulcan(val app: App, val profile: Profile?, val loginStore: LoginStore, va } override fun getMessage(message: MessageFull) { - login(LOGIN_METHOD_VULCAN_API) { - VulcanApiMessagesChangeStatus(data, message) { + 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_API) { - VulcanApiSendMessage(data, recipients, subject, text) { + login(LOGIN_METHOD_VULCAN_HEBE) { + VulcanHebeSendMessage(data, recipients, subject, text) { completed() } } } - override fun markAllAnnouncementsAsRead() { + 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 getAnnouncement(announcement: AnnouncementFull) { - - } - - override fun getAttachment(message: Message, attachmentId: Long, attachmentName: String) { - - } - - override fun getRecipientList() { + override fun getEvent(eventFull: EventFull) { + eventFull.homeworkBody = "" + eventFull.isDownloaded = true + EventBus.getDefault().postSticky(EventGetEvent(eventFull)) + completed() } override fun firstLogin() { VulcanFirstLogin(data) { completed() } } @@ -126,6 +180,7 @@ class Vulcan(val app: App, val profile: Profile?, val loginStore: LoginStore, va private fun wrapCallback(callback: EdziennikCallback): EdziennikCallback { return object : EdziennikCallback { override fun onCompleted() { callback.onCompleted() } + override fun onRequiresUserAction(event: UserActionRequiredEvent) { callback.onRequiresUserAction(event) } override fun onProgress(step: Float) { callback.onProgress(step) } override fun onStartProgress(stringRes: Int) { callback.onStartProgress(stringRes) } override fun onError(apiError: 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 index d1f11822..4def0214 100644 --- 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 @@ -7,87 +7,88 @@ 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_API_UPDATE_SEMESTER = 1000 -const val ENDPOINT_VULCAN_API_PUSH_CONFIG = 1005 -const val ENDPOINT_VULCAN_API_DICTIONARIES = 1010 -const val ENDPOINT_VULCAN_API_TIMETABLE = 1020 -const val ENDPOINT_VULCAN_API_EVENTS = 1030 -const val ENDPOINT_VULCAN_API_GRADES = 1040 -const val ENDPOINT_VULCAN_API_GRADES_SUMMARY = 1050 -const val ENDPOINT_VULCAN_API_HOMEWORK = 1060 -const val ENDPOINT_VULCAN_API_NOTICES = 1070 -const val ENDPOINT_VULCAN_API_ATTENDANCE = 1080 -const val ENDPOINT_VULCAN_API_MESSAGES_INBOX = 1090 -const val ENDPOINT_VULCAN_API_MESSAGES_SENT = 1100 +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_ADDRESSBOOK_2 = 3501 // after message boxes (3500) +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_TEACHERS = 3110 +const val ENDPOINT_VULCAN_HEBE_LUCKY_NUMBER = 3200 +const val ENDPOINT_VULCAN_HEBE_MESSAGE_BOXES = 3500 +const val ENDPOINT_VULCAN_HEBE_MESSAGES_INBOX = 3510 +const val ENDPOINT_VULCAN_HEBE_MESSAGES_SENT = 3520 val VulcanFeatures = listOf( // timetable Feature(LOGIN_TYPE_VULCAN, FEATURE_TIMETABLE, listOf( - ENDPOINT_VULCAN_API_TIMETABLE to LOGIN_METHOD_VULCAN_API - ), listOf(LOGIN_METHOD_VULCAN_API)), + ENDPOINT_VULCAN_HEBE_TIMETABLE to LOGIN_METHOD_VULCAN_HEBE + ), listOf(LOGIN_METHOD_VULCAN_HEBE)), // agenda Feature(LOGIN_TYPE_VULCAN, FEATURE_AGENDA, listOf( - ENDPOINT_VULCAN_API_EVENTS to LOGIN_METHOD_VULCAN_API - ), listOf(LOGIN_METHOD_VULCAN_API)), + ENDPOINT_VULCAN_HEBE_EXAMS to LOGIN_METHOD_VULCAN_HEBE + ), listOf(LOGIN_METHOD_VULCAN_HEBE)), // grades Feature(LOGIN_TYPE_VULCAN, FEATURE_GRADES, listOf( - ENDPOINT_VULCAN_API_GRADES to LOGIN_METHOD_VULCAN_API, - ENDPOINT_VULCAN_API_GRADES_SUMMARY to LOGIN_METHOD_VULCAN_API - ), listOf(LOGIN_METHOD_VULCAN_API)), + 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_API_HOMEWORK to LOGIN_METHOD_VULCAN_API - ), listOf(LOGIN_METHOD_VULCAN_API)), + ENDPOINT_VULCAN_HEBE_HOMEWORK to LOGIN_METHOD_VULCAN_HEBE + ), listOf(LOGIN_METHOD_VULCAN_HEBE)), // behaviour Feature(LOGIN_TYPE_VULCAN, FEATURE_BEHAVIOUR, listOf( - ENDPOINT_VULCAN_API_NOTICES to LOGIN_METHOD_VULCAN_API - ), listOf(LOGIN_METHOD_VULCAN_API)), + ENDPOINT_VULCAN_HEBE_NOTICES to LOGIN_METHOD_VULCAN_HEBE + ), listOf(LOGIN_METHOD_VULCAN_HEBE)), // attendance Feature(LOGIN_TYPE_VULCAN, FEATURE_ATTENDANCE, listOf( - ENDPOINT_VULCAN_API_ATTENDANCE to LOGIN_METHOD_VULCAN_API - ), listOf(LOGIN_METHOD_VULCAN_API)), + 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_API_MESSAGES_INBOX to LOGIN_METHOD_VULCAN_API - ), listOf(LOGIN_METHOD_VULCAN_API)), + 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_API_MESSAGES_SENT to LOGIN_METHOD_VULCAN_API - ), listOf(LOGIN_METHOD_VULCAN_API)), + 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_API_PUSH_CONFIG to LOGIN_METHOD_VULCAN_API - ), listOf(LOGIN_METHOD_VULCAN_API)).withShouldSync { data -> + 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) }, - Feature(LOGIN_TYPE_VULCAN, FEATURE_ALWAYS_NEEDED, listOf( - ENDPOINT_VULCAN_API_UPDATE_SEMESTER to LOGIN_METHOD_VULCAN_API, - ENDPOINT_VULCAN_API_DICTIONARIES to LOGIN_METHOD_VULCAN_API - ), listOf(LOGIN_METHOD_VULCAN_API)) - /*Feature(LOGIN_TYPE_VULCAN, FEATURE_STUDENT_INFO, listOf( - ENDPOINT_VULCAN_API to LOGIN_METHOD_VULCAN_WEB - ), listOf(LOGIN_METHOD_VULCAN_WEB)), - Feature(LOGIN_TYPE_VULCAN, FEATURE_STUDENT_NUMBER, listOf( - ENDPOINT_VULCAN_API to LOGIN_METHOD_VULCAN_WEB - ), listOf(LOGIN_METHOD_VULCAN_WEB)), - Feature(LOGIN_TYPE_VULCAN, FEATURE_SCHOOL_INFO, listOf( - ENDPOINT_VULCAN_API to LOGIN_METHOD_VULCAN_WEB - ), listOf(LOGIN_METHOD_VULCAN_WEB)), - Feature(LOGIN_TYPE_VULCAN, FEATURE_CLASS_INFO, listOf( - ENDPOINT_VULCAN_API to LOGIN_METHOD_VULCAN_WEB - ), listOf(LOGIN_METHOD_VULCAN_WEB)), - Feature(LOGIN_TYPE_VULCAN, FEATURE_TEAM_INFO, listOf( - ENDPOINT_VULCAN_API to LOGIN_METHOD_VULCAN_WEB - ), listOf(LOGIN_METHOD_VULCAN_WEB)), - Feature(LOGIN_TYPE_VULCAN, FEATURE_TEACHERS, listOf( - ENDPOINT_VULCAN_API to LOGIN_METHOD_VULCAN_WEB - ), listOf(LOGIN_METHOD_VULCAN_WEB)), - Feature(LOGIN_TYPE_VULCAN, FEATURE_SUBJECTS, listOf( - ENDPOINT_VULCAN_API to LOGIN_METHOD_VULCAN_WEB - ), listOf(LOGIN_METHOD_VULCAN_WEB)), - Feature(LOGIN_TYPE_VULCAN, FEATURE_CLASSROOMS, listOf( - ENDPOINT_VULCAN_API to LOGIN_METHOD_VULCAN_WEB - ), listOf(LOGIN_METHOD_VULCAN_WEB)),*/ + /** + * 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, + ENDPOINT_VULCAN_HEBE_MESSAGE_BOXES to LOGIN_METHOD_VULCAN_HEBE, + ENDPOINT_VULCAN_HEBE_ADDRESSBOOK_2 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/VulcanApi.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/VulcanApi.kt deleted file mode 100644 index 172be3c0..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/VulcanApi.kt +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-10-19 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data - -import com.google.gson.JsonArray -import com.google.gson.JsonObject -import im.wangchao.mhttp.Request -import im.wangchao.mhttp.Response -import im.wangchao.mhttp.callback.JsonCallbackHandler -import io.github.wulkanowy.signer.android.signContent -import pl.szczodrzynski.edziennik.data.api.* -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.models.ApiError -import pl.szczodrzynski.edziennik.utils.Utils.d -import java.net.HttpURLConnection -import java.util.* - -open class VulcanApi(open val data: DataVulcan, open val lastSync: Long?) { - companion object { - const val TAG = "VulcanApi" - } - - val profileId - get() = data.profile?.id ?: -1 - - val profile - get() = data.profile - - fun apiGet( - tag: String, - endpoint: String, - method: Int = POST, - parameters: Map = emptyMap(), - baseUrl: Boolean = false, - onSuccess: (json: JsonObject, response: Response?) -> Unit - ) { - val url = "${if (baseUrl) data.apiUrl else data.fullApiUrl}$endpoint" - - d(tag, "Request: Vulcan/Api - $url") - - val finalPayload = JsonObject() - parameters.map { (name, value) -> - when (value) { - is JsonObject -> finalPayload.add(name, value) - is JsonArray -> finalPayload.add(name, value) - is String -> finalPayload.addProperty(name, value) - is Int -> finalPayload.addProperty(name, value) - is Long -> finalPayload.addProperty(name, value) - is Float -> finalPayload.addProperty(name, value) - is Char -> finalPayload.addProperty(name, value) - is Boolean -> finalPayload.addProperty(name, value) - } - } - finalPayload.addProperty("RemoteMobileTimeKey", System.currentTimeMillis() / 1000) - finalPayload.addProperty("TimeKey", System.currentTimeMillis() / 1000 - 1) - finalPayload.addProperty("RequestId", UUID.randomUUID().toString()) - finalPayload.addProperty("RemoteMobileAppVersion", VULCAN_API_APP_VERSION) - finalPayload.addProperty("RemoteMobileAppName", VULCAN_API_APP_NAME) - - val callback = object : JsonCallbackHandler() { - override fun onSuccess(json: JsonObject?, response: Response?) { - if (json == null && response?.parserErrorBody == null) { - data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) - .withResponse(response)) - return - } - - if (response?.code() ?: 200 != 200) { - when (response?.code()) { - 503 -> ERROR_VULCAN_API_MAINTENANCE - 400 -> ERROR_VULCAN_API_BAD_REQUEST - else -> ERROR_VULCAN_API_OTHER - }.let { errorCode -> - data.error(ApiError(tag, errorCode) - .withResponse(response) - .withApiResponse(json?.toString() ?: response?.parserErrorBody)) - return - } - } - - if (json == null) { - data.error(ApiError(tag, ERROR_RESPONSE_EMPTY) - .withResponse(response)) - return - } - - try { - onSuccess(json, response) - } catch (e: Exception) { - data.error(ApiError(tag, EXCEPTION_VULCAN_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(VULCAN_API_USER_AGENT) - .addHeader("RequestCertificateKey", data.apiCertificateKey) - .addHeader("RequestSignatureValue", - try { - signContent( - data.apiCertificatePrivate ?: "", - finalPayload.toString() - ) - } catch (e: Exception) {e.printStackTrace();""}) - .apply { - when (method) { - GET -> get() - POST -> post() - } - } - .setJsonBody(finalPayload) - .allowErrorCode(HttpURLConnection.HTTP_BAD_REQUEST) - .allowErrorCode(HttpURLConnection.HTTP_FORBIDDEN) - .allowErrorCode(HttpURLConnection.HTTP_UNAUTHORIZED) - .allowErrorCode(HttpURLConnection.HTTP_UNAVAILABLE) - .callback(callback) - .build() - .enqueue() - } -} 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 index 9ab94c30..4b3f961f 100644 --- 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 @@ -6,7 +6,9 @@ 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.api.* +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) { @@ -14,8 +16,38 @@ class VulcanData(val data: DataVulcan, val onSuccess: () -> Unit) { 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_ADDRESSBOOK_2, + ENDPOINT_VULCAN_HEBE_TIMETABLE, + ENDPOINT_VULCAN_HEBE_EXAMS, + ENDPOINT_VULCAN_HEBE_HOMEWORK, + ENDPOINT_VULCAN_HEBE_NOTICES, + ENDPOINT_VULCAN_HEBE_MESSAGE_BOXES, + ENDPOINT_VULCAN_HEBE_MESSAGES_INBOX, + ENDPOINT_VULCAN_HEBE_MESSAGES_SENT, + ENDPOINT_VULCAN_HEBE_TEACHERS, + ENDPOINT_VULCAN_HEBE_LUCKY_NUMBER + ) + init { - nextEndpoint(onSuccess) + 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) { @@ -29,7 +61,21 @@ class VulcanData(val data: DataVulcan, val onSuccess: () -> Unit) { } val id = data.targetEndpointIds.firstKey() val lastSync = data.targetEndpointIds.remove(id) - useEndpoint(id, lastSync) { endpointId -> + 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) } @@ -38,53 +84,82 @@ class VulcanData(val data: DataVulcan, val onSuccess: () -> Unit) { 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_API_UPDATE_SEMESTER -> { + 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) - VulcanApiUpdateSemester(data, lastSync, onSuccess) + VulcanHebeMain(data, lastSync).getStudents( + profile = data.profile, + profileList = null + ) { + onSuccess(ENDPOINT_VULCAN_HEBE_MAIN) + } } - ENDPOINT_VULCAN_API_PUSH_CONFIG -> { + ENDPOINT_VULCAN_HEBE_PUSH_CONFIG -> { data.startProgress(R.string.edziennik_progress_endpoint_push_config) - VulcanApiPushConfig(data, lastSync, onSuccess) + VulcanHebePushConfig(data, lastSync, onSuccess) } - ENDPOINT_VULCAN_API_DICTIONARIES -> { - data.startProgress(R.string.edziennik_progress_endpoint_dictionaries) - VulcanApiDictionaries(data, lastSync, onSuccess) + ENDPOINT_VULCAN_HEBE_ADDRESSBOOK -> { + data.startProgress(R.string.edziennik_progress_endpoint_addressbook) + VulcanHebeAddressbook(data, lastSync, onSuccess) } - ENDPOINT_VULCAN_API_GRADES -> { - data.startProgress(R.string.edziennik_progress_endpoint_grades) - VulcanApiGrades(data, lastSync, onSuccess) + ENDPOINT_VULCAN_HEBE_ADDRESSBOOK_2 -> { + data.startProgress(R.string.edziennik_progress_endpoint_addressbook) + VulcanHebeAddressbook2(data, lastSync, onSuccess) } - ENDPOINT_VULCAN_API_GRADES_SUMMARY -> { - data.startProgress(R.string.edziennik_progress_endpoint_proposed_grades) - VulcanApiProposedGrades(data, lastSync, onSuccess) + ENDPOINT_VULCAN_HEBE_TEACHERS -> { + data.startProgress(R.string.edziennik_progress_endpoint_teachers) + VulcanHebeTeachers(data, lastSync, onSuccess) } - ENDPOINT_VULCAN_API_EVENTS -> { - data.startProgress(R.string.edziennik_progress_endpoint_events) - VulcanApiEvents(data, isHomework = false, lastSync = lastSync, onSuccess = onSuccess) - } - ENDPOINT_VULCAN_API_HOMEWORK -> { - data.startProgress(R.string.edziennik_progress_endpoint_homework) - VulcanApiEvents(data, isHomework = true, lastSync = lastSync, onSuccess = onSuccess) - } - ENDPOINT_VULCAN_API_NOTICES -> { - data.startProgress(R.string.edziennik_progress_endpoint_notices) - VulcanApiNotices(data, lastSync, onSuccess) - } - ENDPOINT_VULCAN_API_ATTENDANCE -> { - data.startProgress(R.string.edziennik_progress_endpoint_attendance) - VulcanApiAttendance(data, lastSync, onSuccess) - } - ENDPOINT_VULCAN_API_TIMETABLE -> { + ENDPOINT_VULCAN_HEBE_TIMETABLE -> { data.startProgress(R.string.edziennik_progress_endpoint_timetable) - VulcanApiTimetable(data, lastSync, onSuccess) + VulcanHebeTimetable(data, lastSync, onSuccess) } - ENDPOINT_VULCAN_API_MESSAGES_INBOX -> { + 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_MESSAGE_BOXES -> { + data.startProgress(R.string.edziennik_progress_endpoint_messages) + VulcanHebeMessageBoxes(data, lastSync, onSuccess) + } + ENDPOINT_VULCAN_HEBE_MESSAGES_INBOX -> { data.startProgress(R.string.edziennik_progress_endpoint_messages_inbox) - VulcanApiMessagesInbox(data, lastSync, onSuccess) + VulcanHebeMessages(data, lastSync, onSuccess).getMessages(Message.TYPE_RECEIVED) } - ENDPOINT_VULCAN_API_MESSAGES_SENT -> { + ENDPOINT_VULCAN_HEBE_MESSAGES_SENT -> { data.startProgress(R.string.edziennik_progress_endpoint_messages_outbox) - VulcanApiMessagesSent(data, lastSync, onSuccess) + 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..a99ac7a4 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/VulcanHebe.kt @@ -0,0 +1,434 @@ +/* + * 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.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 buildDateTime(): JsonObject { + return JsonObject( + "Timestamp" to System.currentTimeMillis(), + "Date" to Date.getToday().stringY_m_d, + "DateDisplay" to Date.getToday().stringDmy, + "Time" to Time.getNow().stringHMS, + ) + } + + 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 getTeacherRecipient(json: JsonObject): Teacher? { + val globalKey = json.getString("GlobalKey") ?: return null + if (globalKey == data.messageBoxKey) + return null + var name = json.getString("Name") ?: return null + val group = json.getString("Group", "P") + val loginId = "${globalKey};${group};${name}" + val pattern = " - $group - (${data.schoolShort})" + if (name.endsWith(pattern)) + name = name.substringBefore(pattern) + val teacher = data.getTeacherByFirstLast(name, loginId) + if (teacher.type == 0) + teacher.type = Teacher.TYPE_OTHER + return teacher + } + + 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) ?: return null + 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) ?: return null + 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 - WEEK * MS + } ?: 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, + messageBox: String? = 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() + } + HebeFilterType.BY_MESSAGEBOX -> { + query["box"] = messageBox ?: data.messageBoxKey ?: "" + } + } + + 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/api/VulcanApiAttendance.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiAttendance.kt deleted file mode 100644 index 2ec240a4..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiAttendance.kt +++ /dev/null @@ -1,81 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.api - -import androidx.core.util.isEmpty -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.VULCAN_API_ENDPOINT_ATTENDANCE -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_API_ATTENDANCE -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanApi -import pl.szczodrzynski.edziennik.data.db.entity.Attendance -import pl.szczodrzynski.edziennik.data.db.entity.Attendance.TYPE_PRESENT -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 VulcanApiAttendance(override val data: DataVulcan, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : VulcanApi(data, lastSync) { - companion object { - const val TAG = "VulcanApiAttendance" - } - - init { data.profile?.also { profile -> - if (data.attendanceTypes.isEmpty()) { - data.db.attendanceTypeDao().getAllNow(profileId).toSparseArray(data.attendanceTypes) { it.id } - } - - val startDate: String = profile.getSemesterStart(profile.currentSemester).stringY_m_d - val endDate: String = profile.getSemesterEnd(profile.currentSemester).stringY_m_d - - apiGet(TAG, VULCAN_API_ENDPOINT_ATTENDANCE, parameters = mapOf( - "DataPoczatkowa" to startDate, - "DataKoncowa" to endDate, - "IdOddzial" to data.studentClassId, - "IdUczen" to data.studentId, - "IdOkresKlasyfikacyjny" to data.studentSemesterId - )) { json, _ -> - json.getJsonObject("Data")?.getJsonArray("Frekwencje")?.forEach { attendanceEl -> - val attendance = attendanceEl.asJsonObject - - val attendanceCategory = data.attendanceTypes.get(attendance.getLong("IdKategoria") ?: return@forEach) - ?: return@forEach - - val type = attendanceCategory.type - - val id = (attendance.getInt("Dzien") ?: 0) + (attendance.getInt("Numer") ?: 0) - - val lessonDateMillis = Date.fromY_m_d(attendance.getString("DzienTekst")).inMillis - val lessonDate = Date.fromMillis(lessonDateMillis) - - val lessonSemester = profile.dateToSemester(lessonDate) - - val attendanceObject = Attendance( - profileId, - id.toLong(), - -1, - attendance.getLong("IdPrzedmiot") ?: -1, - lessonSemester, - attendance.getString("PrzedmiotNazwa") + attendanceCategory.name.let { " - $it" }, - lessonDate, - data.lessonRanges.get(attendance.getInt("Numer") ?: 0)?.startTime, - type) - - data.attendanceList.add(attendanceObject) - if (attendanceObject.type != TYPE_PRESENT) { - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_ATTENDANCE, - attendanceObject.id, - profile.empty, - profile.empty, - attendanceObject.lessonDate.combineWith(attendanceObject.startTime) - )) - } - } - - data.setSyncNext(ENDPOINT_VULCAN_API_ATTENDANCE, SYNC_ALWAYS) - onSuccess(ENDPOINT_VULCAN_API_ATTENDANCE) - } - } ?: onSuccess(ENDPOINT_VULCAN_API_ATTENDANCE) } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiDictionaries.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiDictionaries.kt deleted file mode 100644 index 76f53cf5..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiDictionaries.kt +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-10-20 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.api - -import com.google.gson.JsonObject -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.VULCAN_API_ENDPOINT_DICTIONARIES -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_API_DICTIONARIES -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanApi -import pl.szczodrzynski.edziennik.data.db.entity.* -import pl.szczodrzynski.edziennik.utils.models.Time - -class VulcanApiDictionaries(override val data: DataVulcan, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : VulcanApi(data, lastSync) { - companion object { - const val TAG = "VulcanApiDictionaries" - } - - init { - apiGet(TAG, VULCAN_API_ENDPOINT_DICTIONARIES) { json, _ -> - val elements = json.getJsonObject("Data") - - elements?.getJsonArray("Pracownicy")?.forEach { saveTeacher(it.asJsonObject) } - elements?.getJsonArray("Przedmioty")?.forEach { saveSubject(it.asJsonObject) } - elements?.getJsonArray("PoryLekcji")?.forEach { saveLessonRange(it.asJsonObject) } - elements?.getJsonArray("KategorieOcen")?.forEach { saveGradeCategory(it.asJsonObject) } - elements?.getJsonArray("KategorieUwag")?.forEach { saveNoticeType(it.asJsonObject) } - elements?.getJsonArray("KategorieFrekwencji")?.forEach { saveAttendanceType(it.asJsonObject) } - - data.setSyncNext(ENDPOINT_VULCAN_API_DICTIONARIES, 4 * DAY) - onSuccess(ENDPOINT_VULCAN_API_DICTIONARIES) - } - } - - private fun saveTeacher(teacher: JsonObject) { - val id = teacher.getLong("Id") ?: return - val name = teacher.getString("Imie") ?: "" - val surname = teacher.getString("Nazwisko") ?: "" - val loginId = teacher.getString("LoginId") ?: "-1" - - val teacherObject = Teacher( - profileId, - id, - name, - surname, - loginId - ) - - data.teacherList.put(id, teacherObject) - } - - private fun saveSubject(subject: JsonObject) { - val id = subject.getLong("Id") ?: return - val longName = subject.getString("Nazwa") ?: "" - val shortName = subject.getString("Kod") ?: "" - - val subjectObject = Subject( - profileId, - id, - longName, - shortName - ) - - data.subjectList.put(id, subjectObject) - } - - private fun saveLessonRange(lessonRange: JsonObject) { - val lessonNumber = lessonRange.getInt("Numer") ?: return - val startTime = lessonRange.getString("PoczatekTekst")?.let { Time.fromH_m(it) } ?: return - val endTime = lessonRange.getString("KoniecTekst")?.let { Time.fromH_m(it) } ?: return - - val lessonRangeObject = LessonRange( - profileId, - lessonNumber, - startTime, - endTime - ) - - data.lessonRanges.put(lessonNumber, lessonRangeObject) - } - - private fun saveGradeCategory(gradeCategory: JsonObject) { - val id = gradeCategory.getLong("Id") ?: return - val name = gradeCategory.getString("Nazwa") ?: "" - - val gradeCategoryObject = GradeCategory( - profileId, - id, - 0.0f, - -1, - name - ) - - data.gradeCategories.put(id, gradeCategoryObject) - } - - private fun saveNoticeType(noticeType: JsonObject) { - val id = noticeType.getLong("Id") ?: return - val name = noticeType.getString("Nazwa") ?: "" - - val noticeTypeObject = NoticeType( - profileId, - id, - name - ) - - data.noticeTypes.put(id, noticeTypeObject) - } - - private fun saveAttendanceType(attendanceType: JsonObject) { - val id = attendanceType.getLong("Id") ?: return - val name = attendanceType.getString("Nazwa") ?: "" - - val absent = attendanceType.getBoolean("Nieobecnosc") ?: false - val excused = attendanceType.getBoolean("Usprawiedliwione") ?: false - val type = if (absent) { - if (excused) - Attendance.TYPE_ABSENT_EXCUSED - else - Attendance.TYPE_ABSENT - } else { - val belated = attendanceType.getBoolean("Spoznienie") ?: false - val released = attendanceType.getBoolean("Zwolnienie") ?: false - val present = attendanceType.getBoolean("Obecnosc") ?: true - if (belated) - if (excused) - Attendance.TYPE_BELATED_EXCUSED - else - Attendance.TYPE_BELATED - else if (released) - Attendance.TYPE_RELEASED - else if (present) - Attendance.TYPE_PRESENT - else - Attendance.TYPE_CUSTOM - } - - val attendanceTypeObject = AttendanceType( - profileId, - id, - name, - type, - -1 - ) - - data.attendanceTypes.put(id, attendanceTypeObject) - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiEvents.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiEvents.kt deleted file mode 100644 index c55dac5d..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiEvents.kt +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-10-20 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.api - -import pl.szczodrzynski.edziennik.data.api.VULCAN_API_ENDPOINT_EVENTS -import pl.szczodrzynski.edziennik.data.api.VULCAN_API_ENDPOINT_HOMEWORK -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_API_EVENTS -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_API_HOMEWORK -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanApi -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.getBoolean -import pl.szczodrzynski.edziennik.getJsonArray -import pl.szczodrzynski.edziennik.getLong -import pl.szczodrzynski.edziennik.getString -import pl.szczodrzynski.edziennik.utils.models.Date - -class VulcanApiEvents(override val data: DataVulcan, - override val lastSync: Long?, - private val isHomework: Boolean, - val onSuccess: (endpointId: Int) -> Unit -) : VulcanApi(data, lastSync) { - companion object { - const val TAG = "VulcanApiEvents" - } - - init { data.profile?.also { profile -> - - val startDate: String = when (profile.empty) { - true -> profile.getSemesterStart(profile.currentSemester).stringY_m_d - else -> Date.getToday().stepForward(0, -1, 0).stringY_m_d - } - val endDate: String = profile.getSemesterEnd(profile.currentSemester).stringY_m_d - - val endpoint = when (isHomework) { - true -> VULCAN_API_ENDPOINT_HOMEWORK - else -> VULCAN_API_ENDPOINT_EVENTS - } - apiGet(TAG, endpoint, parameters = mapOf( - "DataPoczatkowa" to startDate, - "DataKoncowa" to endDate, - "IdOddzial" to data.studentClassId, - "IdUczen" to data.studentId, - "IdOkresKlasyfikacyjny" to data.studentSemesterId - )) { json, _ -> - val events = json.getJsonArray("Data") - - events?.forEach { eventEl -> - val event = eventEl.asJsonObject - - val id = event?.getLong("Id") ?: return@forEach - val eventDate = Date.fromY_m_d(event.getString("DataTekst") ?: return@forEach) - val subjectId = event.getLong("IdPrzedmiot") ?: -1 - val teacherId = event.getLong("IdPracownik") ?: -1 - val topic = event.getString("Opis") ?: "" - - val lessonList = data.db.timetableDao().getForDateNow(profileId, eventDate) - val startTime = lessonList.firstOrNull { it.subjectId == subjectId }?.startTime - - val type = when (isHomework) { - true -> Event.TYPE_HOMEWORK - else -> when (event.getBoolean("Rodzaj")) { - false -> Event.TYPE_SHORT_QUIZ - else -> Event.TYPE_EXAM - } - } - val teamId = event.getLong("IdOddzial") ?: data.teamClass?.id ?: -1 - - val eventObject = Event( - profileId, - id, - eventDate, - startTime, - topic, - -1, - type, - false, - teacherId, - subjectId, - teamId - ) - - data.eventList.add(eventObject) - data.metadataList.add(Metadata( - profileId, - if (isHomework) Metadata.TYPE_HOMEWORK else Metadata.TYPE_EVENT, - id, - profile.empty, - profile.empty, - System.currentTimeMillis() - )) - } - - when (isHomework) { - true -> { - data.toRemove.add(DataRemoveModel.Events.futureWithType(Event.TYPE_HOMEWORK)) - data.setSyncNext(ENDPOINT_VULCAN_API_HOMEWORK, SYNC_ALWAYS) - } - false -> { - data.toRemove.add(DataRemoveModel.Events.futureExceptType(Event.TYPE_HOMEWORK)) - data.setSyncNext(ENDPOINT_VULCAN_API_EVENTS, SYNC_ALWAYS) - } - } - onSuccess(if (isHomework) ENDPOINT_VULCAN_API_HOMEWORK else ENDPOINT_VULCAN_API_EVENTS) - } - } ?: onSuccess(if (isHomework) ENDPOINT_VULCAN_API_HOMEWORK else ENDPOINT_VULCAN_API_EVENTS) } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiGrades.kt deleted file mode 100644 index f62778fc..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiGrades.kt +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-10-19 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.api - -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.VULCAN_API_ENDPOINT_GRADES -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_API_GRADES -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanApi -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.Metadata -import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS -import java.text.DecimalFormat -import kotlin.math.roundToInt - -class VulcanApiGrades(override val data: DataVulcan, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : VulcanApi(data, lastSync) { - companion object { - const val TAG = "VulcanApiGrades" - } - - init { data.profile?.also { profile -> - - apiGet(TAG, VULCAN_API_ENDPOINT_GRADES, parameters = mapOf( - "IdUczen" to data.studentId, - "IdOkresKlasyfikacyjny" to data.studentSemesterId - )) { json, _ -> - val grades = json.getJsonArray("Data") - - grades?.forEach { gradeEl -> - val grade = gradeEl.asJsonObject - - val id = grade.getLong("Id") ?: return@forEach - val categoryId = grade.getLong("IdKategoria") ?: -1 - val category = data.gradeCategories.singleOrNull{ it.categoryId == categoryId }?.text - ?: "" - val teacherId = grade.getLong("IdPracownikD") ?: -1 - val subjectId = grade.getLong("IdPrzedmiot") ?: -1 - val description = grade.getString("Opis") - val comment = grade.getString("Komentarz") - var value = grade.getFloat("Wartosc") - var weight = grade.getFloat("WagaOceny") ?: 0.0f - val modificatorValue = grade.getFloat("WagaModyfikatora") - val numerator = grade.getFloat("Licznik") - val denominator = grade.getFloat("Mianownik") - val addedDate = (grade.getLong("DataModyfikacji") ?: return@forEach) * 1000 - - 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) modificatorValue?.also { value += it } - else weight = 0.0f - - grade.getString("Wpis") ?: "" - } - } - - comment?.also { - if (name == "") name = it - else finalDescription = (if (finalDescription == "") "" else " ") + it - } - - description?.also { - finalDescription = (if (finalDescription == "") "" else " - ") + it - } - - val color = 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() - - val gradeObject = Grade( - profileId = profileId, - id = id, - name = name, - type = TYPE_NORMAL, - value = value ?: 0.0f, - weight = weight, - color = color, - category = category, - description = finalDescription, - comment = null, - semester = data.studentSemesterNumber, - teacherId = teacherId, - subjectId = subjectId - ) - - data.gradeList.add(gradeObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_GRADE, - id, - profile.empty, - profile.empty, - addedDate - - )) - } - - data.toRemove.add(DataRemoveModel.Grades.semesterWithType(data.studentSemesterNumber, Grade.TYPE_NORMAL)) - data.setSyncNext(ENDPOINT_VULCAN_API_GRADES, SYNC_ALWAYS) - onSuccess(ENDPOINT_VULCAN_API_GRADES) - } - } ?: onSuccess(ENDPOINT_VULCAN_API_GRADES) } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiMessagesChangeStatus.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiMessagesChangeStatus.kt deleted file mode 100644 index 3a72c963..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiMessagesChangeStatus.kt +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-11-12 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.api - -import org.greenrobot.eventbus.EventBus -import pl.szczodrzynski.edziennik.data.api.VULCAN_API_ENDPOINT_MESSAGES_CHANGE_STATUS -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanApi -import pl.szczodrzynski.edziennik.data.api.events.MessageGetEvent -import pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_SENT -import pl.szczodrzynski.edziennik.data.db.entity.MessageRecipient -import pl.szczodrzynski.edziennik.data.db.entity.Metadata -import pl.szczodrzynski.edziennik.data.db.full.MessageFull - -class VulcanApiMessagesChangeStatus(override val data: DataVulcan, - private val messageObject: MessageFull, - val onSuccess: () -> Unit -) : VulcanApi(data, null) { - companion object { - const val TAG = "VulcanApiMessagesChangeStatus" - } - - init { - apiGet(TAG, VULCAN_API_ENDPOINT_MESSAGES_CHANGE_STATUS, parameters = mapOf( - "WiadomoscId" to messageObject.id, - "FolderWiadomosci" to "Odebrane", - "Status" to "Widoczna", - "LoginId" to data.studentLoginId, - "IdUczen" to data.studentId - )) { _, _ -> - - if (!messageObject.seen) { - data.setSeenMetadataList.add(Metadata( - profileId, - Metadata.TYPE_MESSAGE, - messageObject.id, - true, - true, - messageObject.addedDate - )) - - messageObject.seen = true - } - - if (messageObject.type != TYPE_SENT) { - 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/api/VulcanApiMessagesInbox.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiMessagesInbox.kt deleted file mode 100644 index e78b157e..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiMessagesInbox.kt +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-11-01 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.api - -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.VULCAN_API_ENDPOINT_MESSAGES_RECEIVED -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_API_MESSAGES_INBOX -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanApi -import pl.szczodrzynski.edziennik.data.db.entity.* -import pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_RECEIVED -import pl.szczodrzynski.edziennik.utils.Utils -import pl.szczodrzynski.edziennik.utils.models.Date -import kotlin.text.replace - -class VulcanApiMessagesInbox(override val data: DataVulcan, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : VulcanApi(data, lastSync) { - companion object { - const val TAG = "VulcanApiMessagesInbox" - } - - init { - data.profile?.also { profile -> - - val startDate = when (profile.empty) { - true -> profile.getSemesterStart(profile.currentSemester).inUnix - else -> Date.getToday().stepForward(0, -2, 0).inUnix - } - val endDate = Date.getToday().stepForward(0, 1, 0).inUnix - - apiGet(TAG, VULCAN_API_ENDPOINT_MESSAGES_RECEIVED, parameters = mapOf( - "DataPoczatkowa" to startDate, - "DataKoncowa" to endDate, - "LoginId" to data.studentLoginId, - "IdUczen" to data.studentId - )) { json, _ -> - json.getJsonArray("Data")?.asJsonObjectList()?.forEach { message -> - val id = message.getLong("WiadomoscId") ?: return@forEach - val subject = message.getString("Tytul") ?: "" - val body = message.getString("Tresc") ?: "" - - val senderLoginId = message.getString("NadawcaId") ?: return@forEach - val senderId = data.teacherList - .singleOrNull { it.loginId == senderLoginId }?.id ?: { - - val senderName = message.getString("Nadawca") ?: "" - - senderName.splitName()?.let { (senderLastName, senderFirstName) -> - val teacherObject = Teacher( - profileId, - -1 * Utils.crc16(senderName.toByteArray()).toLong(), - senderFirstName, - senderLastName, - senderLoginId - ) - data.teacherList.put(teacherObject.id, teacherObject) - teacherObject.id - } - }.invoke() ?: -1 - - val sentDate = message.getLong("DataWyslaniaUnixEpoch")?.let { it * 1000 } - ?: -1 - val readDate = message.getLong("DataPrzeczytaniaUnixEpoch")?.let { it * 1000 } - ?: -1 - - val messageObject = Message( - profileId, - id, - subject, - body.replace("\n", "
    "), - TYPE_RECEIVED, - senderId, - -1 - ) - - val messageRecipientObject = MessageRecipient( - profileId, - -1, - -1, - readDate, - id - ) - - data.messageIgnoreList.add(messageObject) - data.messageRecipientList.add(messageRecipientObject) - data.setSeenMetadataList.add(Metadata( - profileId, - Metadata.TYPE_MESSAGE, - id, - readDate > 0, - readDate > 0, - sentDate - )) - } - - data.setSyncNext(ENDPOINT_VULCAN_API_MESSAGES_INBOX, SYNC_ALWAYS) - onSuccess(ENDPOINT_VULCAN_API_MESSAGES_INBOX) - } - } ?: onSuccess(ENDPOINT_VULCAN_API_MESSAGES_INBOX) - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiMessagesSent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiMessagesSent.kt deleted file mode 100644 index 7437aab4..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiMessagesSent.kt +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-11-5 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.api - -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_MESSAGES -import pl.szczodrzynski.edziennik.data.api.VULCAN_API_ENDPOINT_MESSAGES_SENT -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_API_MESSAGES_SENT -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanApi -import pl.szczodrzynski.edziennik.data.db.entity.Message -import pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_SENT -import pl.szczodrzynski.edziennik.data.db.entity.MessageRecipient -import pl.szczodrzynski.edziennik.data.db.entity.Metadata -import pl.szczodrzynski.edziennik.data.db.entity.Teacher -import pl.szczodrzynski.edziennik.utils.Utils -import pl.szczodrzynski.edziennik.utils.models.Date -import kotlin.text.replace - -class VulcanApiMessagesSent(override val data: DataVulcan, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : VulcanApi(data, lastSync) { - companion object { - const val TAG = "VulcanApiMessagesSent" - } - - init { - data.profile?.also { profile -> - - val startDate = when (profile.empty) { - true -> profile.getSemesterStart(profile.currentSemester).inUnix - else -> Date.getToday().stepForward(0, -2, 0).inUnix - } - val endDate = Date.getToday().stepForward(0, 1, 0).inUnix - - apiGet(TAG, VULCAN_API_ENDPOINT_MESSAGES_SENT, parameters = mapOf( - "DataPoczatkowa" to startDate, - "DataKoncowa" to endDate, - "LoginId" to data.studentLoginId, - "IdUczen" to data.studentId - )) { json, _ -> - json.getJsonArray("Data")?.asJsonObjectList()?.forEach { message -> - val id = message.getLong("WiadomoscId") ?: return@forEach - val subject = message.getString("Tytul") ?: "" - val body = message.getString("Tresc") ?: "" - val readBy = message.getInt("Przeczytane") ?: 0 - val unreadBy = message.getInt("Nieprzeczytane") ?: 0 - val sentDate = message.getLong("DataWyslaniaUnixEpoch")?.let { it * 1000 } ?: -1 - - message.getJsonArray("Adresaci")?.asJsonObjectList() - ?.onEach { receiver -> - - val receiverLoginId = receiver.getString("LoginId") - ?: return@onEach - val receiverId = data.teacherList.singleOrNull { it.loginId == receiverLoginId }?.id - ?: { - val receiverName = receiver.getString("Nazwa") ?: "" - - receiverName.splitName()?.let { (receiverLastName, receiverFirstName) -> - val teacherObject = Teacher( - profileId, - -1 * Utils.crc16(receiverName.toByteArray()).toLong(), - receiverFirstName, - receiverLastName, - receiverLoginId - ) - data.teacherList.put(teacherObject.id, teacherObject) - teacherObject.id - } - }.invoke() ?: -1 - - val readDate: Long = when (readBy) { - 0 -> 0 - else -> when (unreadBy) { - 0 -> 1 - else -> -1 - } - } - - val messageRecipientObject = MessageRecipient( - profileId, - receiverId, - -1, - readDate, - id - ) - - data.messageRecipientList.add(messageRecipientObject) - } - - val messageObject = Message( - profileId, - id, - subject, - body.replace("\n", "
    "), - TYPE_SENT, - -1, - -1 - ) - - data.messageIgnoreList.add(messageObject) - data.setSeenMetadataList.add(Metadata( - profileId, - Metadata.TYPE_MESSAGE, - id, - true, - true, - sentDate - )) - } - - data.setSyncNext(ENDPOINT_VULCAN_API_MESSAGES_SENT, 1 * DAY, DRAWER_ITEM_MESSAGES) - onSuccess(ENDPOINT_VULCAN_API_MESSAGES_SENT) - } - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiNotices.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiNotices.kt deleted file mode 100644 index b2202981..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiNotices.kt +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-10-23 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.api - -import androidx.core.util.isEmpty -import pl.szczodrzynski.edziennik.data.api.VULCAN_API_ENDPOINT_NOTICES -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_API_NOTICES -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanApi -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.getJsonArray -import pl.szczodrzynski.edziennik.getLong -import pl.szczodrzynski.edziennik.getString -import pl.szczodrzynski.edziennik.toSparseArray -import pl.szczodrzynski.edziennik.utils.models.Date - -class VulcanApiNotices(override val data: DataVulcan, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : VulcanApi(data, lastSync) { - companion object { - const val TAG = "VulcanApiNotices" - } - - init { data.profile?.also { profile -> - if (data.noticeTypes.isEmpty()) { - data.db.noticeTypeDao().getAllNow(profileId).toSparseArray(data.noticeTypes) { it.id } - } - - apiGet(TAG, VULCAN_API_ENDPOINT_NOTICES, parameters = mapOf( - "IdUczen" to data.studentId, - "IdOkresKlasyfikacyjny" to data.studentSemesterId - )) { json, _ -> - json.getJsonArray("Data")?.forEach { noticeEl -> - val notice = noticeEl.asJsonObject - - val id = notice.getLong("Id") ?: return@forEach - val text = notice.getString("TrescUwagi") ?: return@forEach - val teacherId = notice.getLong("IdPracownik") ?: -1 - val addedDate = Date.fromY_m_d(notice.getString("DataWpisuTekst")).inMillis - - val noticeObject = Notice( - profileId, - id, - text, - profile.currentSemester, - Notice.TYPE_NEUTRAL, - teacherId - ) - - data.noticeList.add(noticeObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_NOTICE, - id, - profile.empty, - profile.empty, - addedDate - )) - } - - data.setSyncNext(ENDPOINT_VULCAN_API_NOTICES, SYNC_ALWAYS) - onSuccess(ENDPOINT_VULCAN_API_NOTICES) - } - } ?: onSuccess(ENDPOINT_VULCAN_API_NOTICES) } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiProposedGrades.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiProposedGrades.kt deleted file mode 100644 index ee1e250f..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiProposedGrades.kt +++ /dev/null @@ -1,90 +0,0 @@ -package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.api - -import com.google.gson.JsonArray -import pl.szczodrzynski.edziennik.HOUR -import pl.szczodrzynski.edziennik.asJsonObjectList -import pl.szczodrzynski.edziennik.data.api.VULCAN_API_ENDPOINT_GRADES_PROPOSITIONS -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_API_GRADES_SUMMARY -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanApi -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.Metadata -import pl.szczodrzynski.edziennik.getJsonArray -import pl.szczodrzynski.edziennik.getJsonObject -import pl.szczodrzynski.edziennik.utils.Utils - -class VulcanApiProposedGrades(override val data: DataVulcan, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : VulcanApi(data, lastSync) { - companion object { - const val TAG = "VulcanApiProposedGrades" - } - - init { data.profile?.also { profile -> - - apiGet(TAG, VULCAN_API_ENDPOINT_GRADES_PROPOSITIONS, parameters = mapOf( - "IdUczen" to data.studentId, - "IdOkresKlasyfikacyjny" to data.studentSemesterId - )) { json, _ -> - val grades = json.getJsonObject("Data") - - grades.getJsonArray("OcenyPrzewidywane")?.let { - processGradeList(it, isFinal = false) - } - - grades.getJsonArray("OcenyKlasyfikacyjne")?.let { - processGradeList(it, isFinal = true) - } - - data.setSyncNext(ENDPOINT_VULCAN_API_GRADES_SUMMARY, 6*HOUR) - onSuccess(ENDPOINT_VULCAN_API_GRADES_SUMMARY) - } - } ?: onSuccess(ENDPOINT_VULCAN_API_GRADES_SUMMARY) } - - private fun processGradeList(grades: JsonArray, isFinal: Boolean) { - grades.asJsonObjectList()?.forEach { grade -> - val name = grade.get("Wpis").asString - val value = Utils.getGradeValue(name) - val subjectId = grade.get("IdPrzedmiot").asLong - - val id = subjectId * -100 - data.studentSemesterNumber - - val color = Utils.getVulcanGradeColor(name) - - val gradeObject = Grade( - profileId = profileId, - id = id, - name = name, - type = if (data.studentSemesterNumber == 1) { - if (isFinal) TYPE_SEMESTER1_FINAL else TYPE_SEMESTER1_PROPOSED - } else { - if (isFinal) TYPE_SEMESTER2_FINAL else TYPE_SEMESTER2_PROPOSED - }, - value = value, - weight = 0f, - color = color, - category = "", - description = null, - comment = null, - semester = data.studentSemesterNumber, - teacherId = -1, - subjectId = subjectId - ) - - data.gradeList.add(gradeObject) - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_GRADE, - gradeObject.id, - data.profile?.empty ?: false, - data.profile?.empty ?: false, - System.currentTimeMillis() - )) - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiPushConfig.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiPushConfig.kt deleted file mode 100644 index b7e291e2..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiPushConfig.kt +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2020-2-20. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.api - -import pl.szczodrzynski.edziennik.data.api.VULCAN_API_ENDPOINT_PUSH -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_API_PUSH_CONFIG -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanApi -import pl.szczodrzynski.edziennik.data.db.entity.SYNC_ALWAYS - -class VulcanApiPushConfig(override val data: DataVulcan, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : VulcanApi(data, lastSync) { - companion object { - const val TAG = "VulcanApiPushConfig" - } - - init { data.app.config.sync.tokenVulcan?.also { tokenVulcan -> - apiGet(TAG, VULCAN_API_ENDPOINT_PUSH, parameters = mapOf( - "Token" to tokenVulcan, - "IdUczen" to data.studentId, - "PushOcena" to true, - "PushFrekwencja" to true, - "PushUwaga" to true, - "PushWiadomosc" to true - )) { _, _ -> - // sync always: this endpoint has .shouldSync set - data.setSyncNext(ENDPOINT_VULCAN_API_PUSH_CONFIG, SYNC_ALWAYS) - data.app.config.sync.tokenVulcanList = - data.app.config.sync.tokenVulcanList + profileId - onSuccess(ENDPOINT_VULCAN_API_PUSH_CONFIG) - } - } ?: onSuccess(ENDPOINT_VULCAN_API_PUSH_CONFIG) } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiSendMessage.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiSendMessage.kt deleted file mode 100644 index c7f7b29e..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiSendMessage.kt +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-12-29. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.api - -import org.greenrobot.eventbus.EventBus -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.VULCAN_API_ENDPOINT_MESSAGES_ADD -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanApi -import pl.szczodrzynski.edziennik.data.api.events.MessageSentEvent -import pl.szczodrzynski.edziennik.data.db.entity.Message -import pl.szczodrzynski.edziennik.data.db.entity.Metadata -import pl.szczodrzynski.edziennik.data.db.entity.Teacher - -class VulcanApiSendMessage(override val data: DataVulcan, - val recipients: List, - val subject: String, - val text: String, - val onSuccess: () -> Unit -) : VulcanApi(data, null) { - companion object { - private const val TAG = "VulcanApiSendMessage" - } - - init { - val recipientsArray = JsonArray() - for (teacher in recipients) { - teacher.loginId?.let { - recipientsArray += JsonObject( - "LoginId" to it, - "Nazwa" to "${teacher.fullNameLastFirst} - pracownik" - ) - } - } - val params = mapOf( - "NadawcaWiadomosci" to (profile?.accountName ?: profile?.studentNameLong ?: ""), - "Tytul" to subject, - "Tresc" to text, - "Adresaci" to recipientsArray, - "LoginId" to data.studentLoginId, - "IdUczen" to data.studentId - ) - - apiGet(TAG, VULCAN_API_ENDPOINT_MESSAGES_ADD, parameters = params) { json, _ -> - val messageId = json.getJsonObject("Data").getLong("WiadomoscId") - - if (messageId == null) { - // TODO error - return@apiGet - } - - VulcanApiMessagesSent(data, null) { - val message = data.messageIgnoreList.firstOrNull { it.type == Message.TYPE_SENT && it.subject == subject } - val metadata = data.metadataList.firstOrNull { it.thingType == Metadata.TYPE_MESSAGE && it.thingId == messageId } - val event = MessageSentEvent(data.profileId, message, metadata?.addedDate) - - EventBus.getDefault().postSticky(event) - onSuccess() - } - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiTemplate.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiTemplate.kt deleted file mode 100644 index 4148be44..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiTemplate.kt +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-10-20 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.api - -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanApi - -class VulcanApiTemplate(override val data: DataVulcan, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : VulcanApi(data, lastSync) { - companion object { - const val TAG = "VulcanApi" - } - - init { - /* data.profile?.also { profile -> - apiGet(TAG, VULCAN_API_ENDPOINT_) { json, _ -> - - data.setSyncNext(ENDPOINT_VULCAN_API_, SYNC_ALWAYS) - onSuccess() - } - } */ - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiTimetable.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiTimetable.kt deleted file mode 100644 index d8899dbf..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiTimetable.kt +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2019-11-13 - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.api - -import androidx.core.util.set -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.Regexes.VULCAN_SHIFT_ANNOTATION -import pl.szczodrzynski.edziennik.data.api.VULCAN_API_ENDPOINT_TIMETABLE -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_API_TIMETABLE -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanApi -import pl.szczodrzynski.edziennik.data.api.models.DataRemoveModel -import pl.szczodrzynski.edziennik.data.db.entity.* -import pl.szczodrzynski.edziennik.utils.Utils.crc16 -import pl.szczodrzynski.edziennik.utils.Utils.d -import pl.szczodrzynski.edziennik.utils.models.Date -import pl.szczodrzynski.edziennik.utils.models.Week - -class VulcanApiTimetable(override val data: DataVulcan, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : VulcanApi(data, lastSync) { - companion object { - const val TAG = "VulcanApiTimetable" - } - - 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) - - apiGet(TAG, VULCAN_API_ENDPOINT_TIMETABLE, parameters = mapOf( - "DataPoczatkowa" to weekStart.stringY_m_d, - "DataKoncowa" to weekEnd.stringY_m_d, - "IdUczen" to data.studentId, - "IdOddzial" to data.studentClassId, - "IdOkresKlasyfikacyjny" to data.studentSemesterId - )) { json, _ -> - val dates = mutableSetOf() - val lessons = mutableListOf() - - json.getJsonArray("Data")?.asJsonObjectList()?.forEach { lesson -> - if (lesson.getBoolean("PlanUcznia") != true) - return@forEach - val lessonDate = Date.fromY_m_d(lesson.getString("DzienTekst")) - val lessonNumber = lesson.getInt("NumerLekcji") - val lessonRange = data.lessonRanges.singleOrNull { it.lessonNumber == lessonNumber } - val startTime = lessonRange?.startTime - val endTime = lessonRange?.endTime - val teacherId = lesson.getLong("IdPracownik") - val classroom = lesson.getString("Sala") - - val oldTeacherId = lesson.getLong("IdPracownikOld") - - val changeAnnotation = lesson.getString("AdnotacjaOZmianie") ?: "" - val type = when { - changeAnnotation.startsWith("(przeniesiona z") -> Lesson.TYPE_SHIFTED_TARGET - changeAnnotation.startsWith("(przeniesiona na") -> Lesson.TYPE_SHIFTED_SOURCE - changeAnnotation.startsWith("(zastępstwo") -> Lesson.TYPE_CHANGE - lesson.getBoolean("PrzekreslonaNazwa") == true -> Lesson.TYPE_CANCELLED - else -> Lesson.TYPE_NORMAL - } - - val teamId = lesson.getString("PodzialSkrot")?.let { teamName -> - val name = "${data.teamClass?.name} $teamName" - val id = name.crc16().toLong() - var team = data.teamList.singleOrNull { it.name == name } - if (team == null) { - team = Team( - profileId, - id, - name, - Team.TYPE_VIRTUAL, - "${data.schoolName}:$name", - teacherId ?: oldTeacherId ?: -1 - ) - data.teamList[id] = team - } - team.id - } ?: data.teamClass?.id ?: -1 - - val subjectId = lesson.getLong("IdPrzedmiot").let { id -> - // get the specified subject name - val subjectName = lesson.getString("PrzedmiotNazwa") ?: "" - - val condition = when (id) { - // "special" subject - e.g. one time classes, a trip, etc. - 0L -> { subject: Subject -> subject.longName == subjectName } - // normal subject, check if it exists - else -> { subject: Subject -> subject.id == id } - } - - data.subjectList.singleOrNull(condition)?.id ?: { - /** - * CREATE A NEW SUBJECT IF IT DOESN'T EXIST - */ - - val subjectObject = Subject( - profileId, - if (id == null || id == 0L) - -1 * crc16(subjectName.toByteArray()).toLong() - else - id, - subjectName, - subjectName - ) - data.subjectList.put(subjectObject.id, subjectObject) - subjectObject.id - }() - } - - val lessonObject = Lesson(profileId, -1).apply { - this.type = type - - when (type) { - Lesson.TYPE_NORMAL, Lesson.TYPE_CHANGE, Lesson.TYPE_SHIFTED_TARGET -> { - this.date = lessonDate - this.lessonNumber = lessonNumber - this.startTime = startTime - this.endTime = endTime - this.subjectId = subjectId - this.teacherId = teacherId - this.teamId = teamId - this.classroom = classroom - - this.oldTeacherId = oldTeacherId - } - - Lesson.TYPE_CANCELLED, Lesson.TYPE_SHIFTED_SOURCE -> { - this.oldDate = lessonDate - this.oldLessonNumber = lessonNumber - this.oldStartTime = startTime - this.oldEndTime = endTime - this.oldSubjectId = subjectId - this.oldTeacherId = teacherId - this.oldTeamId = teamId - this.oldClassroom = classroom - } - } - - if (type == Lesson.TYPE_SHIFTED_SOURCE || type == Lesson.TYPE_SHIFTED_TARGET) { - val shift = VULCAN_SHIFT_ANNOTATION.find(changeAnnotation) - val oldLessonNumber = shift?.get(2)?.toInt() - val oldLessonDate = shift?.get(3)?.let { Date.fromd_m_Y(it) } - - val oldLessonRange = data.lessonRanges.singleOrNull { it.lessonNumber == oldLessonNumber } - val oldStartTime = oldLessonRange?.startTime - val oldEndTime = oldLessonRange?.endTime - - when (type) { - Lesson.TYPE_SHIFTED_SOURCE -> { - this.lessonNumber = oldLessonNumber - this.date = oldLessonDate - this.startTime = oldStartTime - this.endTime = oldEndTime - } - - Lesson.TYPE_SHIFTED_TARGET -> { - this.oldLessonNumber = oldLessonNumber - this.oldDate = oldLessonDate - this.oldStartTime = oldStartTime - this.oldEndTime = oldEndTime - } - } - } - - this.id = buildId() - } - - val seen = profile.empty || lessonDate < Date.getToday() - - if (type != Lesson.TYPE_NORMAL) { - data.metadataList.add(Metadata( - profileId, - Metadata.TYPE_LESSON_CHANGE, - lessonObject.id, - seen, - seen, - System.currentTimeMillis() - )) - } - - dates.add(lessonDate.value) - lessons.add(lessonObject) - } - - val date: Date = weekStart.clone() - while (date <= weekEnd) { - if (!dates.contains(date.value)) { - lessons.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 ${weekStart.stringY_m_d} and ${weekEnd.stringY_m_d} - timetable downloaded for $getDate") - - data.lessonList.addAll(lessons) - data.toRemove.add(DataRemoveModel.Timetable.between(weekStart, weekEnd)) - - data.setSyncNext(ENDPOINT_VULCAN_API_TIMETABLE, SYNC_ALWAYS) - onSuccess(ENDPOINT_VULCAN_API_TIMETABLE) - } - }} -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiUpdateSemester.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiUpdateSemester.kt deleted file mode 100644 index 1f03484c..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/api/VulcanApiUpdateSemester.kt +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2020-2-1. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.api - -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.ERROR_NO_STUDENTS_IN_ACCOUNT -import pl.szczodrzynski.edziennik.data.api.VULCAN_API_ENDPOINT_STUDENT_LIST -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_API_UPDATE_SEMESTER -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanApi -import pl.szczodrzynski.edziennik.data.api.models.ApiError -import pl.szczodrzynski.edziennik.utils.models.Date - -class VulcanApiUpdateSemester(override val data: DataVulcan, - override val lastSync: Long?, - val onSuccess: (endpointId: Int) -> Unit -) : VulcanApi(data, lastSync) { - companion object { - const val TAG = "VulcanApiUpdateSemester" - } - - init { data.profile?.also { profile -> - apiGet(TAG, VULCAN_API_ENDPOINT_STUDENT_LIST, baseUrl = true) { json, response -> - val students = json.getJsonArray("Data") - - if (students == null || students.isEmpty()) { - data.error(ApiError(TAG, ERROR_NO_STUDENTS_IN_ACCOUNT) - .withResponse(response) - .withApiResponse(json)) - return@apiGet - } - - students.asJsonObjectList().firstOrNull { - it.getInt("Id") == data.studentId - }?.let { student -> - val studentClassId = student.getInt("IdOddzial") ?: return@let - val studentClassName = student.getString("OkresPoziom").toString() + (student.getString("OddzialSymbol") ?: return@let) - val studentSemesterId = student.getInt("IdOkresKlasyfikacyjny") ?: return@let - - val currentSemesterStartDate = student.getLong("OkresDataOd") ?: return@let - val currentSemesterEndDate = (student.getLong("OkresDataDo") ?: return@let) + 86400 - val studentSemesterNumber = student.getInt("OkresNumer") ?: return@let - - var dateSemester1Start: Date? = null - var dateSemester2Start: Date? = null - var dateYearEnd: Date? = null - when (studentSemesterNumber) { - 1 -> { - dateSemester1Start = Date.fromMillis(currentSemesterStartDate * 1000) - dateSemester2Start = Date.fromMillis(currentSemesterEndDate * 1000) - } - 2 -> { - dateSemester2Start = Date.fromMillis(currentSemesterStartDate * 1000) - dateYearEnd = Date.fromMillis(currentSemesterEndDate * 1000) - } - } - - data.studentClassId = studentClassId - data.studentSemesterId = studentSemesterId - data.studentSemesterNumber = studentSemesterNumber - data.currentSemesterEndDate = currentSemesterEndDate - profile.studentClassName = studentClassName - dateSemester1Start?.let { - profile.dateSemester1Start = it - profile.studentSchoolYearStart = it.year - } - dateSemester2Start?.let { profile.dateSemester2Start = it } - dateYearEnd?.let { profile.dateYearEnd = it } - } - - data.setSyncNext(ENDPOINT_VULCAN_API_UPDATE_SEMESTER, if (data.studentSemesterNumber == 2) 7*DAY else 2*DAY) - onSuccess(ENDPOINT_VULCAN_API_UPDATE_SEMESTER) - } - } ?: onSuccess(ENDPOINT_VULCAN_API_UPDATE_SEMESTER) } -} 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..bd8b58e5 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/HebeFilterType.kt @@ -0,0 +1,12 @@ +/* + * 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_MESSAGEBOX("byBox"), + 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..d7bec22b --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeAddressbook.kt @@ -0,0 +1,123 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-21. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import androidx.core.util.set +import androidx.room.OnConflictStrategy +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 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, + null + ).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) + if (roleText != null) + teacher.typeDescription = roleText + } + + if (teacher.type == 0) + teacher.setTeacherType(typeBase) + } + data.teacherOnConflictStrategy = OnConflictStrategy.REPLACE + 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/VulcanHebeAddressbook2.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeAddressbook2.kt new file mode 100644 index 00000000..2ac843a2 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeAddressbook2.kt @@ -0,0 +1,61 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-21. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import androidx.room.OnConflictStrategy +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_MESSAGEBOX_ADDRESSBOOK +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_HEBE_ADDRESSBOOK_2 +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +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_STUDENT +import pl.szczodrzynski.edziennik.data.db.entity.Teacher.Companion.TYPE_TEACHER +import pl.szczodrzynski.edziennik.ext.DAY +import pl.szczodrzynski.edziennik.ext.MINUTE +import pl.szczodrzynski.edziennik.ext.getString + +class VulcanHebeAddressbook2( + override val data: DataVulcan, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : VulcanHebe(data, lastSync) { + companion object { + const val TAG = "VulcanHebeAddressbook2" + } + + init { let { + if (data.messageBoxKey == null) { + data.setSyncNext(ENDPOINT_VULCAN_HEBE_ADDRESSBOOK_2, 30 * MINUTE) + onSuccess(ENDPOINT_VULCAN_HEBE_ADDRESSBOOK_2) + return@let + } + + apiGetList( + TAG, + VULCAN_HEBE_ENDPOINT_MESSAGEBOX_ADDRESSBOOK, + HebeFilterType.BY_MESSAGEBOX, + messageBox = data.messageBoxKey, + lastSync = lastSync, + includeFilterType = false + ) { list, _ -> + list.forEach { person -> + val teacher = getTeacherRecipient(person) ?: return@forEach + val group = person.getString("Group", "P") + if (teacher.type == TYPE_OTHER) { + teacher.type = when (group) { + "P" -> TYPE_TEACHER // Pracownik + "O" -> TYPE_PARENT // Opiekun + "U" -> TYPE_STUDENT // Uczeń + else -> TYPE_OTHER + } + } + } + data.teacherOnConflictStrategy = OnConflictStrategy.REPLACE + data.setSyncNext(ENDPOINT_VULCAN_HEBE_ADDRESSBOOK_2, 2 * DAY) + onSuccess(ENDPOINT_VULCAN_HEBE_ADDRESSBOOK_2) + } + }} +} 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/VulcanHebeMessageBoxes.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeMessageBoxes.kt new file mode 100644 index 00000000..df6613ba --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeMessageBoxes.kt @@ -0,0 +1,51 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2022-9-16. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_MESSAGEBOX +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.ENDPOINT_VULCAN_HEBE_MESSAGE_BOXES +import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanHebe +import pl.szczodrzynski.edziennik.ext.DAY +import pl.szczodrzynski.edziennik.ext.getString + +class VulcanHebeMessageBoxes( + override val data: DataVulcan, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : VulcanHebe(data, lastSync) { + companion object { + const val TAG = "VulcanHebeMessageBoxes" + } + + init { + apiGetList( + TAG, + VULCAN_HEBE_ENDPOINT_MESSAGEBOX, + lastSync = lastSync + ) { list, _ -> + var found = false + for (messageBox in list) { + val name = messageBox.getString("Name") ?: continue + val studentName = profile?.studentNameLong ?: continue + if (!name.contains(studentName)) + continue + + data.messageBoxKey = messageBox.getString("GlobalKey") + data.messageBoxName = name + found = true + break + } + if (!found && list.isNotEmpty()) { + list.firstOrNull()?.let { messageBox -> + data.messageBoxKey = messageBox.getString("GlobalKey") + data.messageBoxName = messageBox.getString("Name") + } + } + data.setSyncNext(ENDPOINT_VULCAN_HEBE_MESSAGE_BOXES, 7 * DAY) + onSuccess(ENDPOINT_VULCAN_HEBE_MESSAGE_BOXES) + } + } +} 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..affca1e1 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeMessages.kt @@ -0,0 +1,160 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-21. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_MESSAGES +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_MESSAGEBOX_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.Message +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.data.db.entity.MessageRecipient +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 + +class VulcanHebeMessages( + override val data: DataVulcan, + override val lastSync: Long?, + val onSuccess: (endpointId: Int) -> Unit +) : VulcanHebe(data, lastSync) { + companion object { + const val TAG = "VulcanHebeMessages" + } + + 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 + } + + val messageBox = data.messageBoxKey + if (messageBox == null) { + onSuccess(endpointId) + return + } + + apiGetList( + TAG, + VULCAN_HEBE_ENDPOINT_MESSAGEBOX_MESSAGES, + HebeFilterType.BY_MESSAGEBOX, + messageBox = data.messageBoxKey, + folder = folder, + lastSync = lastSync + ) { list, _ -> + list.forEach { message -> + val uuid = message.getString("Id") ?: return@forEach + val id = Utils.crc32(uuid.toByteArray()) + val globalKey = message.getString("GlobalKey", "") + val threadKey = message.getString("ThreadKey", "") + val subject = message.getString("Subject") ?: return@forEach + var 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 senderId = if (messageType == TYPE_RECEIVED) + getTeacherRecipient(sender)?.id + else + null + + val meta = mutableMapOf( + "uuid" to uuid, + "globalKey" to globalKey, + "threadKey" to threadKey, + ) + val metaString = meta.map { "${it.key}=${it.value}" }.join("&") + body = "[META:${metaString}]" + body + body = body.replace("\n", "
    ") + + val messageObject = Message( + profileId = profileId, + id = id, + type = messageType, + subject = subject, + body = body, + senderId = senderId, + addedDate = sentDate + ) + + val receivers = message.getJsonArray("Receiver") + ?.asJsonObjectList() + ?: return@forEach + + for (receiver in receivers) { + val recipientId = if (messageType == TYPE_SENT) + getTeacherRecipient(receiver)?.id ?: -1 + else + -1 + + val receiverReadDate = receiver.getLong("HasRead", -1) + + val messageRecipientObject = MessageRecipient( + profileId, + recipientId, + -1, + receiverReadDate, + id + ) + data.messageRecipientList.add(messageRecipientObject) + } + + val attachments = message.getJsonArray("Attachments") + ?.asJsonObjectList() + ?: return@forEach + + messageObject.attachmentIds = mutableListOf() + messageObject.attachmentNames = mutableListOf() + messageObject.attachmentSizes = mutableListOf() + 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..2144a768 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeMessagesChangeStatus.kt @@ -0,0 +1,71 @@ +/* + * 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_MESSAGEBOX_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 { let { + val messageKey = messageObject.body?.let { data.parseMessageMeta(it) }?.get("uuid") ?: run { + EventBus.getDefault().postSticky(MessageGetEvent(messageObject)) + onSuccess() + return@let + } + + apiPost( + TAG, + VULCAN_HEBE_ENDPOINT_MESSAGEBOX_STATUS, + payload = JsonObject( + "BoxKey" to data.messageBoxKey, + "MessageKey" to messageKey, + "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..5e607caa --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeSendMessage.kt @@ -0,0 +1,119 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-22. + */ + +package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.hebe + +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.ERROR_MESSAGE_NOT_SENT +import pl.szczodrzynski.edziennik.data.api.ERROR_VULCAN_HEBE_MISSING_SENDER_ENTRY +import pl.szczodrzynski.edziennik.data.api.VULCAN_HEBE_ENDPOINT_MESSAGEBOX_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.* +import java.util.UUID + +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.messageBoxKey == null || data.messageBoxName == null) { + VulcanHebeMessageBoxes(data, 0) { + if (data.messageBoxKey == null || data.messageBoxName == null) { + data.error(TAG, ERROR_VULCAN_HEBE_MISSING_SENDER_ENTRY) + } + else { + sendMessage() + } + } + } + else { + sendMessage() + } + } + + private fun sendMessage() { + val uuid = UUID.randomUUID().toString() + val globalKey = UUID.randomUUID().toString() + val partition = "${data.symbol}-${data.schoolSymbol}" + + val recipientsArray = JsonArray() + recipients.forEach { teacher -> + val loginId = teacher.loginId?.split(";", limit = 3) ?: return@forEach + val key = loginId.getOrNull(0) ?: teacher.loginId + val group = loginId.getOrNull(1) + val name = loginId.getOrNull(2) + if (key?.toIntOrNull() != null) { + // raise error for old-format (non-UUID) login IDs + data.error(TAG, ERROR_MESSAGE_NOT_SENT) + return + } + recipientsArray += JsonObject( + "Id" to "${data.messageBoxKey}-${key}", + "Partition" to partition, + "Owner" to data.messageBoxKey, + "GlobalKey" to key, + "Name" to name, + "Group" to group, + "Initials" to "", + "HasRead" to 0, + ) + } + + val sender = JsonObject( + "Id" to "0", + "Partition" to partition, + "Owner" to data.messageBoxKey, + "GlobalKey" to data.messageBoxKey, + "Name" to data.messageBoxName, + "Group" to "", + "Initials" to "", + "HasRead" to 0, + ) + + apiPost( + TAG, + VULCAN_HEBE_ENDPOINT_MESSAGEBOX_SEND, + payload = JsonObject( + "Id" to uuid, + "GlobalKey" to globalKey, + "Partition" to partition, + "ThreadKey" to globalKey, // TODO correct threadKey for reply messages + "Subject" to subject, + "Content" to text, + "Status" to 1, + "Owner" to data.messageBoxKey, + "DateSent" to buildDateTime(), + "DateRead" to null, + "Sender" to sender, + "Receiver" to recipientsArray, + "Attachments" to JsonArray(), + ) + ) { _: JsonObject, _ -> + // TODO handle errors + + 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..7be65e34 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/data/hebe/VulcanHebeTeachers.kt @@ -0,0 +1,61 @@ +/* + * 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) + "Dyrektor" -> teacher.setTeacherType(Teacher.TYPE_PRINCIPAL) + 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 index 291cb37b..61502488 100644 --- 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 @@ -6,110 +6,124 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.firstlogin import org.greenrobot.eventbus.EventBus import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.LOGIN_TYPE_VULCAN -import pl.szczodrzynski.edziennik.data.api.VULCAN_API_ENDPOINT_STUDENT_LIST +import pl.szczodrzynski.edziennik.data.api.* import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.VulcanApi -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.login.VulcanLoginApi +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.utils.models.Date +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 api = VulcanApi(data, null) + 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 { - val loginStoreId = data.loginStore.id - val loginStoreType = LOGIN_TYPE_VULCAN - var firstProfileId = loginStoreId + 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) - VulcanLoginApi(data) { - api.apiGet(TAG, VULCAN_API_ENDPOINT_STUDENT_LIST, baseUrl = true) { json, response -> - val students = json.getJsonArray("Data") + if (data.symbol != null && data.symbol != "default") { + tryingSymbols += data.symbol ?: "default" + } + else { - if (students == null || students.isEmpty()) { - EventBus.getDefault().post(FirstLoginFinishedEvent(listOf(), data.loginStore)) - onSuccess() - return@apiGet + tryingSymbols += certificate.userInstances } - students.forEach { studentEl -> - val student = studentEl.asJsonObject - - val schoolSymbol = student.getString("JednostkaSprawozdawczaSymbol") ?: return@forEach - val schoolName = "${data.symbol}_$schoolSymbol" - val studentId = student.getInt("Id") ?: return@forEach - val studentLoginId = student.getInt("UzytkownikLoginId") ?: return@forEach - val studentClassId = student.getInt("IdOddzial") ?: return@forEach - val studentClassName = student.getString("OkresPoziom").toString() + (student.getString("OddzialSymbol") ?: return@forEach) - val studentSemesterId = student.getInt("IdOkresKlasyfikacyjny") ?: return@forEach - val studentFirstName = student.getString("Imie") ?: "" - val studentLastName = student.getString("Nazwisko") ?: "" - val studentNameLong = "$studentFirstName $studentLastName".fixName() - val studentNameShort = "$studentFirstName ${studentLastName[0]}.".fixName() - - val userLogin = student.getString("UzytkownikLogin") ?: "" - val currentSemesterStartDate = student.getLong("OkresDataOd") ?: return@forEach - val currentSemesterEndDate = (student.getLong("OkresDataDo") ?: return@forEach) + 86400 - val studentSemesterNumber = student.getInt("OkresNumer") ?: return@forEach - - val isParent = student.getString("UzytkownikRola") == "opiekun" - val accountName = if (isParent) - student.getString("UzytkownikNazwa")?.swapFirstLastName()?.fixName() - else null - - var dateSemester1Start: Date? = null - var dateSemester2Start: Date? = null - var dateYearEnd: Date? = null - when (studentSemesterNumber) { - 1 -> { - dateSemester1Start = Date.fromMillis(currentSemesterStartDate * 1000) - dateSemester2Start = Date.fromMillis(currentSemesterEndDate * 1000) - } - 2 -> { - dateSemester2Start = Date.fromMillis(currentSemesterStartDate * 1000) - dateYearEnd = Date.fromMillis(currentSemesterEndDate * 1000) - } - } - - val profile = Profile( - firstProfileId++, - loginStoreId, - loginStoreType, - studentNameLong, - userLogin, - studentNameLong, - studentNameShort, - accountName - ).apply { - this.studentClassName = studentClassName - studentData["studentId"] = studentId - studentData["studentLoginId"] = studentLoginId - studentData["studentClassId"] = studentClassId - studentData["studentSemesterId"] = studentSemesterId - studentData["studentSemesterNumber"] = studentSemesterNumber - studentData["schoolSymbol"] = schoolSymbol - studentData["schoolName"] = schoolName - studentData["currentSemesterEndDate"] = currentSemesterEndDate - } - dateSemester1Start?.let { - profile.dateSemester1Start = it - profile.studentSchoolYearStart = it.year - } - dateSemester2Start?.let { profile.dateSemester2Start = it } - dateYearEnd?.let { profile.dateYearEnd = it } - - profileList.add(profile) - } - - EventBus.getDefault().post(FirstLoginFinishedEvent(profileList, data.loginStore)) + 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 index 4c11caf3..3cbb7ea7 100644 --- 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 @@ -5,7 +5,8 @@ package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.login import pl.szczodrzynski.edziennik.R -import pl.szczodrzynski.edziennik.data.api.LOGIN_METHOD_VULCAN_API +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 @@ -45,9 +46,13 @@ class VulcanLogin(val data: DataVulcan, val onSuccess: () -> Unit) { } Utils.d(TAG, "Using login method $loginMethodId") when (loginMethodId) { - LOGIN_METHOD_VULCAN_API -> { + 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) - VulcanLoginApi(data) { onSuccess(loginMethodId) } + VulcanLoginHebe(data) { onSuccess(loginMethodId) } } } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/login/VulcanLoginApi.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/login/VulcanLoginApi.kt deleted file mode 100644 index 4385b18a..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/edziennik/vulcan/login/VulcanLoginApi.kt +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-10-6. - */ - -package pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.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 io.github.wulkanowy.signer.android.getPrivateKeyFromCert -import pl.szczodrzynski.edziennik.currentTimeUnix -import pl.szczodrzynski.edziennik.data.api.* -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.DataVulcan -import pl.szczodrzynski.edziennik.data.api.edziennik.vulcan.data.api.VulcanApiUpdateSemester -import pl.szczodrzynski.edziennik.data.api.models.ApiError -import pl.szczodrzynski.edziennik.getJsonObject -import pl.szczodrzynski.edziennik.getString -import pl.szczodrzynski.edziennik.isNotNullNorEmpty -import pl.szczodrzynski.edziennik.utils.Utils.d -import java.net.HttpURLConnection.HTTP_BAD_REQUEST -import java.util.* -import java.util.regex.Pattern - -class VulcanLoginApi(val data: DataVulcan, val onSuccess: () -> Unit) { - companion object { - private const val TAG = "VulcanLoginApi" - } - - init { run { - if (data.profile != null && data.isApiLoginValid()) { - onSuccess() - } - else { - // < v4.0 - PFX to Private Key migration - if (data.apiCertificatePfx.isNotNullNorEmpty()) { - try { - data.apiCertificatePrivate = getPrivateKeyFromCert( - if (data.apiToken?.get(0) == 'F') VULCAN_API_PASSWORD_FAKELOG else VULCAN_API_PASSWORD, - data.apiCertificatePfx ?: "" - ) - data.loginStore.removeLoginData("certificatePfx") - } catch (e: Throwable) { - e.printStackTrace() - } finally { - onSuccess() - return@run - } - } - - if (data.apiCertificateKey.isNotNullNorEmpty() - && data.apiCertificatePrivate.isNotNullNorEmpty() - && data.symbol.isNotNullNorEmpty()) { - // (see data.isApiLoginValid()) - // the semester end date is over - VulcanApiUpdateSemester(data, null) { onSuccess() } - return@run - } - - if (data.symbol.isNotNullNorEmpty() && data.apiToken.isNotNullNorEmpty() && data.apiPin.isNotNullNorEmpty()) { - loginWithToken() - } - else { - data.error(ApiError(TAG, ERROR_LOGIN_DATA_MISSING)) - } - } - }} - - private fun loginWithToken() { - d(TAG, "Request: Vulcan/Login/Api - ${data.apiUrl}/$VULCAN_API_ENDPOINT_CERTIFICATE") - - val callback = object : JsonCallbackHandler() { - override fun onSuccess(json: JsonObject?, response: Response?) { - if (json == null) { - if (response?.code() == HTTP_BAD_REQUEST) { - data.error(TAG, ERROR_LOGIN_VULCAN_INVALID_SYMBOL, response) - return - } - data.error(ApiError(TAG, ERROR_RESPONSE_EMPTY) - .withResponse(response)) - return - } - - var tokenStatus = json.getString("TokenStatus") - if (tokenStatus == "Null" || tokenStatus == "CertGenerated") - tokenStatus = null - val error = tokenStatus ?: json.getString("Message") - error?.let { code -> - when (code) { - "TokenNotFound" -> ERROR_LOGIN_VULCAN_INVALID_TOKEN - "TokenDead" -> ERROR_LOGIN_VULCAN_EXPIRED_TOKEN - "WrongPIN" -> { - Pattern.compile("Liczba pozostałych prób: ([0-9])", Pattern.DOTALL).matcher(tokenStatus).let { matcher -> - if (matcher.matches()) - ERROR_LOGIN_VULCAN_INVALID_PIN + 1 + matcher.group(1).toInt() - else - ERROR_LOGIN_VULCAN_INVALID_PIN - } - } - "Broken" -> ERROR_LOGIN_VULCAN_INVALID_PIN_0_REMAINING - "OnlyKindergarten" -> ERROR_LOGIN_VULCAN_ONLY_KINDERGARTEN - "NoPupils" -> ERROR_LOGIN_VULCAN_NO_PUPILS - else -> ERROR_LOGIN_VULCAN_OTHER - }.let { errorCode -> - data.error(ApiError(TAG, errorCode) - .withApiResponse(json) - .withResponse(response)) - return - } - } - - val cert = json.getJsonObject("TokenCert") - if (cert == null) { - data.error(ApiError(TAG, ERROR_LOGIN_VULCAN_OTHER) - .withApiResponse(json) - .withResponse(response)) - return - } - - data.apiCertificateKey = cert.getString("CertyfikatKlucz") - data.apiToken = data.apiToken?.substring(0, 3) - data.apiCertificatePrivate = getPrivateKeyFromCert( - if (data.apiToken?.get(0) == 'F') VULCAN_API_PASSWORD_FAKELOG else VULCAN_API_PASSWORD, - cert.getString("CertyfikatPfx") ?: "" - ) - data.loginStore.removeLoginData("certificatePfx") - data.loginStore.removeLoginData("devicePin") - onSuccess() - } - - override fun onFailure(response: Response?, throwable: Throwable?) { - data.error(ApiError(TAG, ERROR_REQUEST_FAILURE) - .withResponse(response) - .withThrowable(throwable)) - } - } - - Request.builder() - .url("${data.apiUrl}$VULCAN_API_ENDPOINT_CERTIFICATE") - .userAgent(VULCAN_API_USER_AGENT) - .addHeader("RequestMobileType", "RegisterDevice") - .addParameter("PIN", data.apiPin) - .addParameter("TokenKey", data.apiToken) - .addParameter("DeviceId", UUID.randomUUID().toString()) - .addParameter("DeviceName", VULCAN_API_DEVICE_NAME) - .addParameter("DeviceNameUser", "") - .addParameter("DeviceDescription", "") - .addParameter("DeviceSystemType", "Android") - .addParameter("DeviceSystemVersion", Build.VERSION.RELEASE) - .addParameter("RemoteMobileTimeKey", currentTimeUnix()) - .addParameter("TimeKey", currentTimeUnix() - 1) - .addParameter("RequestId", UUID.randomUUID().toString()) - .addParameter("AppVersion", VULCAN_API_APP_VERSION) - .addParameter("RemoteMobileAppVersion", VULCAN_API_APP_VERSION) - .addParameter("RemoteMobileAppName", VULCAN_API_APP_NAME) - .postJson() - .allowErrorCode(HTTP_BAD_REQUEST) - .callback(callback) - .build() - .enqueue() - } -} 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/AttachmentGetEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/events/AttachmentGetEvent.kt index cbc85b7d..52415c56 100644 --- 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 @@ -4,11 +4,21 @@ package pl.szczodrzynski.edziennik.data.api.events -data class AttachmentGetEvent(val profileId: Int, val messageId: Long, val attachmentId: Long, +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/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 index d88fa652..3995842a 100644 --- 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 @@ -4,13 +4,16 @@ 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 +import android.os.Bundle + +data class UserActionRequiredEvent( + val profileId: Int?, + val type: Type, + val params: Bundle, + val errorText: Int, +) { + enum class Type { + RECAPTCHA, + OAUTH, } } 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 index c1c878b4..4943ff1e 100644 --- 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 @@ -4,6 +4,7 @@ package pl.szczodrzynski.edziennik.data.api.interfaces +import pl.szczodrzynski.edziennik.data.api.events.UserActionRequiredEvent import pl.szczodrzynski.edziennik.data.api.models.Feature import pl.szczodrzynski.edziennik.data.api.models.LoginMethod @@ -14,4 +15,5 @@ import pl.szczodrzynski.edziennik.data.api.models.LoginMethod */ interface EdziennikCallback : EndpointCallback { fun onCompleted() + fun onRequiresUserAction(event: UserActionRequiredEvent) } 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 index e19a19ee..153bbe18 100644 --- 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 @@ -5,9 +5,9 @@ package pl.szczodrzynski.edziennik.data.api.interfaces import com.google.gson.JsonObject -import pl.szczodrzynski.edziennik.data.db.entity.Message 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 { @@ -16,8 +16,9 @@ interface EdziennikInterface { fun sendMessage(recipients: List, subject: String, text: String) fun markAllAnnouncementsAsRead() fun getAnnouncement(announcement: AnnouncementFull) - fun getAttachment(message: Message, attachmentId: Long, attachmentName: String) + 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/models/ApiError.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/models/ApiError.kt index d99e16a2..b631ed7d 100644 --- 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 @@ -5,6 +5,7 @@ package pl.szczodrzynski.edziennik.data.api.models import android.content.Context +import android.os.Bundle import com.google.gson.JsonObject import im.wangchao.mhttp.Request import im.wangchao.mhttp.Response @@ -13,8 +14,8 @@ 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.stackTraceString -import pl.szczodrzynski.edziennik.toErrorCode +import pl.szczodrzynski.edziennik.ext.stackTraceString +import pl.szczodrzynski.edziennik.ext.toErrorCode class ApiError(val tag: String, var errorCode: Int) { companion object { @@ -30,6 +31,7 @@ class ApiError(val tag: String, var errorCode: Int) { var request: Request? = null var response: Response? = null var isCritical = true + var params: Bundle? = null fun withThrowable(throwable: Throwable?): ApiError { this.throwable = throwable @@ -58,6 +60,11 @@ class ApiError(val tag: String, var errorCode: Int) { return this } + fun withParams(bundle: Bundle): ApiError { + this.params = bundle + return this + } + fun getStringText(context: Context): String { return context.resources.getIdentifier("error_${errorCode}", "string", context.packageName).let { if (it != 0) 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 index b5086539..9b7137fc 100644 --- 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 @@ -1,16 +1,23 @@ package pl.szczodrzynski.edziennik.data.api.models +import android.os.Bundle 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.* +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.api.Regexes.MESSAGE_META +import pl.szczodrzynski.edziennik.data.api.events.UserActionRequiredEvent +import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikCallback 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 @@ -32,7 +39,7 @@ abstract class Data(val app: App, val profile: Profile?, val loginStore: LoginSt /** * A callback passed to all [Feature]s and [LoginMethod]s */ - lateinit var callback: EndpointCallback + lateinit var callback: EdziennikCallback /** * A list of [LoginMethod]s *already fulfilled* during this sync. @@ -86,6 +93,9 @@ abstract class Data(val app: App, val profile: Profile?, val loginStore: LoginSt val gradeCategories = LongSparseArray() var teacherOnConflictStrategy = OnConflictStrategy.IGNORE + var eventListReplace = false + var messageListReplace = false + var announcementListReplace = false val classrooms = LongSparseArray() val attendanceTypes = LongSparseArray() @@ -118,14 +128,12 @@ abstract class Data(val app: App, val profile: Profile?, val loginStore: LoginSt val attendanceList = mutableListOf() val announcementList = mutableListOf() - val announcementIgnoreList = mutableListOf() val luckyNumberList = mutableListOf() val teacherAbsenceList = mutableListOf() val messageList = mutableListOf() - val messageIgnoreList = mutableListOf() val messageRecipientList = mutableListOf() val messageRecipientIgnoreList = mutableListOf() @@ -135,7 +143,7 @@ abstract class Data(val app: App, val profile: Profile?, val loginStore: LoginSt val db: AppDb by lazy { app.db } init { - if (App.devMode) { + if (App.debugMode) { fakeLogin = loginStore.hasLoginData("fakeLogin") } clear() @@ -177,11 +185,9 @@ abstract class Data(val app: App, val profile: Profile?, val loginStore: LoginSt noticeList.clear() attendanceList.clear() announcementList.clear() - announcementIgnoreList.clear() luckyNumberList.clear() teacherAbsenceList.clear() messageList.clear() - messageIgnoreList.clear() messageRecipientList.clear() messageRecipientIgnoreList.clear() metadataList.clear() @@ -197,6 +203,13 @@ abstract class Data(val app: App, val profile: Profile?, val loginStore: LoginSt 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) @@ -277,34 +290,19 @@ abstract class Data(val app: App, val profile: Profile?, val loginStore: LoginSt d("Metadata saved in ${System.currentTimeMillis()-startTime} ms") startTime = System.currentTimeMillis() - if (lessonList.isNotEmpty()) { - db.timetableDao() += lessonList - } - if (gradeList.isNotEmpty()) { - db.gradeDao().addAll(gradeList) - } - if (eventList.isNotEmpty()) { - db.eventDao().addAll(eventList) - } + 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().addAll(noticeList) + db.noticeDao().putAll(noticeList) } - if (attendanceList.isNotEmpty()) - db.attendanceDao().addAll(attendanceList) - if (announcementList.isNotEmpty()) - db.announcementDao().addAll(announcementList) - if (announcementIgnoreList.isNotEmpty()) - db.announcementDao().addAllIgnore(announcementIgnoreList) - if (luckyNumberList.isNotEmpty()) - db.luckyNumberDao().addAll(luckyNumberList) - if (teacherAbsenceList.isNotEmpty()) - db.teacherAbsenceDao().addAll(teacherAbsenceList) + db.attendanceDao().putAll(attendanceList, removeNotKept = true) + db.announcementDao().putAll(announcementList, forceReplace = announcementListReplace, removeNotKept = false) + db.luckyNumberDao().putAll(luckyNumberList) + db.teacherAbsenceDao().putAll(teacherAbsenceList) - if (messageList.isNotEmpty()) - db.messageDao().addAll(messageList) - if (messageIgnoreList.isNotEmpty()) - db.messageDao().addAllIgnore(messageIgnoreList) + db.messageDao().putAll(messageList, forceReplace = messageListReplace, removeNotKept = false) if (messageRecipientList.isNotEmpty()) db.messageRecipientDao().addAll(messageRecipientList) if (messageRecipientIgnoreList.isNotEmpty()) @@ -345,7 +343,7 @@ abstract class Data(val app: App, val profile: Profile?, val loginStore: LoginSt } fun shouldSyncLuckyNumber(): Boolean { - return (db.luckyNumberDao().getNearestFutureNow(profileId, Date.getToday().value) ?: -1) == -1 + return db.luckyNumberDao().getNearestFutureNow(profileId, Date.getToday()) == null } /*fun error(tag: String, errorCode: Int, response: Response? = null, throwable: Throwable? = null, apiResponse: JsonObject? = null) { @@ -378,6 +376,15 @@ abstract class Data(val app: App, val profile: Profile?, val loginStore: LoginSt callback.onError(apiError) } + fun requireUserAction(type: UserActionRequiredEvent.Type, params: Bundle, errorText: Int) { + callback.onRequiresUserAction(UserActionRequiredEvent( + profileId = profile?.id, + type = type, + params = params, + errorText = errorText, + )) + } + fun progress(step: Float) { callback.onProgress(step) } @@ -385,4 +392,134 @@ abstract class Data(val app: App, val profile: Profile?, val loginStore: LoginSt 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, id: Long? = null): Teacher { + val teacher = teacherList.singleOrNull { it.fullName == "$firstName $lastName" } + return validateTeacher(teacher, firstName, lastName, loginId, id) + } + + 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, null) + } + + 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, null) + else + validateTeacher(teacher, nameParts[1], nameParts[0], loginId, null) + } + + 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, null) + else + validateTeacher(teacher, nameParts[0], nameParts[1], loginId, null) + } + + 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?, + id: Long? + ): Teacher { + val obj = teacher ?: Teacher(profileId, -1, firstName, lastName, loginId).also { + it.id = id ?: it.fullName.crc32() + teacherList[it.id] = it + } + return obj.also { + if (loginId != null) + it.loginId = loginId + if (firstName.length > 1) + it.name = firstName + it.surname = lastName + } + } + + fun parseMessageMeta(body: String): Map? { + val match = MESSAGE_META.find(body) ?: return null + return match[1].split("&").associateBy( + { it.substringBefore("=") }, + { it.substringAfter("=") }, + ) + } } 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 index ccccc00e..73096f28 100644 --- 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 @@ -11,19 +11,19 @@ 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?) : DataRemoveModel() { + data class Timetable(private val dateFrom: Date?, private val dateTo: Date?, private val isExtra: Boolean?) : DataRemoveModel() { companion object { - fun from(dateFrom: Date) = Timetable(dateFrom, null) - fun to(dateTo: Date) = Timetable(null, dateTo) - fun between(dateFrom: Date, dateTo: Date) = Timetable(dateFrom, dateTo) + 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.clearBetweenDates(profileId, dateFrom, dateTo) + dao.dontKeepBetweenDates(profileId, dateFrom, dateTo, isExtra ?: false) } else { - dateFrom?.let { dateFrom -> dao.clearFromDate(profileId, dateFrom) } - dateTo?.let { dateTo -> dao.clearToDate(profileId, dateTo) } + dateFrom?.let { dateFrom -> dao.dontKeepFromDate(profileId, dateFrom, isExtra ?: false) } + dateTo?.let { dateTo -> dao.dontKeepToDate(profileId, dateTo, isExtra ?: false) } } } } @@ -38,12 +38,12 @@ open class DataRemoveModel { fun commit(profileId: Int, dao: GradeDao) { if (all) { - if (type != null) dao.clearWithType(profileId, type) + if (type != null) dao.dontKeepWithType(profileId, type) else dao.clear(profileId) } semester?.let { - if (type != null) dao.clearForSemesterWithType(profileId, it, type) - else dao.clearForSemester(profileId, it) + if (type != null) dao.dontKeepForSemesterWithType(profileId, it, type) + else dao.dontKeepForSemester(profileId, it) } } } @@ -53,12 +53,15 @@ open class DataRemoveModel { 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.removeFutureWithType(profileId, Date.getToday(), it) } - exceptType?.let { dao.removeFutureExceptType(profileId, Date.getToday(), it) } - exceptTypes?.let { dao.removeFutureExceptTypes(profileId, Date.getToday(), it) } + 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()) } } @@ -69,7 +72,7 @@ open class DataRemoveModel { fun commit(profileId: Int, dao: AttendanceDao) { if (dateFrom != null) { - dao.clearAfterDate(profileId, dateFrom) + dao.dontKeepAfterDate(profileId, dateFrom) } } } 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 index eb70ab9a..a9f6a69f 100644 --- 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 @@ -5,6 +5,7 @@ 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 @@ -12,21 +13,25 @@ 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.ApiResponse -import pl.szczodrzynski.edziennik.data.api.szkolny.response.Update -import pl.szczodrzynski.edziennik.data.api.szkolny.response.WebPushResponse -import pl.szczodrzynski.edziennik.data.db.entity.Event -import pl.szczodrzynski.edziennik.data.db.entity.FeedbackMessage -import pl.szczodrzynski.edziennik.data.db.entity.Notification -import pl.szczodrzynski.edziennik.data.db.entity.Profile +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.ui.modules.error.ErrorDetailsDialog -import pl.szczodrzynski.edziennik.ui.modules.error.ErrorSnackbar +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 @@ -52,6 +57,7 @@ class SzkolnyApi(val app: App) : CoroutineScope { val okHttpClient: OkHttpClient = app.http.newBuilder() .followRedirects(true) .callTimeout(10, SECONDS) + .addInterceptor(ApiCacheInterceptor(app)) .addInterceptor(SignatureInterceptor(app)) .build() @@ -73,7 +79,7 @@ class SzkolnyApi(val app: App) : CoroutineScope { suspend inline fun runCatching(errorSnackbar: ErrorSnackbar, crossinline block: SzkolnyApi.() -> T?): T? { return try { - withContext(Dispatchers.Default) { block() } + withContext(Dispatchers.Default) { block.invoke(this@SzkolnyApi) } } catch (e: Exception) { errorSnackbar.addError(e.toApiError(TAG)).show() @@ -82,20 +88,28 @@ class SzkolnyApi(val app: App) : CoroutineScope { } suspend inline fun runCatching(activity: AppCompatActivity, crossinline block: SzkolnyApi.() -> T?): T? { return try { - withContext(Dispatchers.Default) { block() } + withContext(Dispatchers.Default) { block.invoke(this@SzkolnyApi) } } catch (e: Exception) { - ErrorDetailsDialog( + 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(e.toApiError(TAG)), + listOf(apiError), R.string.error_occured - ) + ).show() + null + } null } } inline fun runCatching(block: SzkolnyApi.() -> T, onError: (e: Throwable) -> Unit): T? { return try { - block() + block.invoke(this@SzkolnyApi) } catch (e: Exception) { onError(e) @@ -110,8 +124,35 @@ class SzkolnyApi(val app: App) : CoroutineScope { * or null if it's a HTTP call error. */ @Throws(Exception::class) - private inline fun parseResponse(response: Response>): T { + 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 } @@ -129,10 +170,13 @@ class SzkolnyApi(val app: App) : CoroutineScope { } } + if (body?.errors?.any { it.toErrorCode() == ERROR_API_INVALID_SIGNATURE } == true) { + app.config.apiInvalidCert = Signing.appCertificate.md5() + } + throw SzkolnyApiException(body?.errors?.firstOrNull()) } - @Throws(Exception::class) private fun getDevice() = run { val config = app.config val device = Device( @@ -145,60 +189,74 @@ class SzkolnyApi(val app: App) : CoroutineScope { appVersionCode = BuildConfig.VERSION_CODE, syncInterval = app.config.sync.interval ) - device.toString().md5().let { - if (it == config.hash) - null - else { - config.hash = it - device - } - } + 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): List { + 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 = 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 } - ) - user.toString().md5().let { - if (it == config.hash) - null - else { - config.hash = it - user - } - } - }, + users = users.keys(), lastSync = lastSyncTime, notifications = notifications.map { ServerSyncRequest.Notification(it.profileName ?: "", it.type, it.text) } )).execute() - val (events, hasBrowsers) = parseResponse(response) + 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 @@ -207,38 +265,106 @@ class SzkolnyApi(val app: App) : CoroutineScope { seen = profile.empty notified = profile.empty - if (profile.userCode == event.sharedBy) sharedBy = "self" + if (profile.userCode == event.sharedBy) { + sharedBy = "self" + addedManually = true + } else { + sharedBy = eventSharedBy + } } } } - return eventList + 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(), - sharedByName = event.sharedByName, - shareTeamCode = team.code, - event = event + 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 unshareEvent(event: Event) { - val team = app.db.teamDao().getByIdNow(event.profileId, event.teamId) + 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.shareEvent(EventShareRequest( - deviceId = app.deviceId, - device = getDevice(), - sharedByName = event.sharedByName, - unshareTeamCode = team.code, - eventId = event.id + 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) } @@ -257,7 +383,7 @@ class SzkolnyApi(val app: App) : CoroutineScope { pairToken = pairToken )).execute() - return parseResponse(response).browsers + return parseResponse(response, updateDeviceHash = true).browsers } @Throws(Exception::class) @@ -268,7 +394,7 @@ class SzkolnyApi(val app: App) : CoroutineScope { action = "listBrowsers" )).execute() - return parseResponse(response).browsers + return parseResponse(response, updateDeviceHash = true).browsers } @Throws(Exception::class) @@ -280,7 +406,7 @@ class SzkolnyApi(val app: App) : CoroutineScope { browserId = browserId )).execute() - return parseResponse(response).browsers + return parseResponse(response, updateDeviceHash = true).browsers } @Throws(Exception::class) @@ -291,7 +417,7 @@ class SzkolnyApi(val app: App) : CoroutineScope { appVersion = BuildConfig.VERSION_NAME, errors = errors )).execute() - parseResponse(response) + parseResponse(response, updateDeviceHash = true) } @Throws(Exception::class) @@ -301,7 +427,7 @@ class SzkolnyApi(val app: App) : CoroutineScope { device = getDevice(), userCode = userCode )).execute() - parseResponse(response) + parseResponse(response, updateDeviceHash = true) } @Throws(Exception::class) @@ -320,6 +446,36 @@ class SzkolnyApi(val app: App) : CoroutineScope { text = text )).execute() - return parseResponse(response).message + return parseResponse(response, updateDeviceHash = true).message + } + + @Throws(Exception::class) + fun getRealms(registerName: String): List { + val response = api.platforms(registerName).execute() + if (response.isSuccessful && response.body() != null) { + return parseResponse(response) + } + 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/SzkolnyService.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/SzkolnyService.kt index 0e3dd574..cca9475a 100644 --- 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 @@ -6,11 +6,9 @@ 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.Body -import retrofit2.http.GET -import retrofit2.http.POST -import retrofit2.http.Query +import retrofit2.http.* interface SzkolnyService { @@ -20,6 +18,9 @@ interface SzkolnyService { @POST("share") fun shareEvent(@Body request: EventShareRequest): Call> + @POST("share") + fun shareNote(@Body request: NoteShareRequest): Call> + @POST("webPush") fun webPush(@Body request: WebPushRequest): Call> @@ -29,9 +30,21 @@ interface SzkolnyService { @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("platforms/{registerName}") + fun platforms(@Path("registerName") registerName: String): Call>> } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/interceptor/ApiCacheInterceptor.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/interceptor/ApiCacheInterceptor.kt new file mode 100644 index 00000000..f1f8e341 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/interceptor/ApiCacheInterceptor.kt @@ -0,0 +1,42 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-3-29. + */ + +package pl.szczodrzynski.edziennik.data.api.szkolny.interceptor + +import okhttp3.* +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.szkolny.response.ApiResponse +import pl.szczodrzynski.edziennik.ext.md5 + +class ApiCacheInterceptor(val app: App) : Interceptor { + + override fun intercept(chain: Interceptor.Chain): Response { + val request = chain.request() + if (request.url().host() == "api.szkolny.eu" + && Signing.appCertificate.md5() == app.config.apiInvalidCert + && !app.buildManager.isSigned + ) { + val response = ApiResponse( + success = false, + errors = listOf(ApiResponse.Error("InvalidSignature", "")) + ) + + return Response.Builder() + .request(request) + .protocol(Protocol.HTTP_1_1) + .code(401) + .message("Unauthorized") + .addHeader("Content-Type", "application/json") + .body( + ResponseBody.create( + MediaType.parse("application/json"), + app.gson.toJson(response) + ) + ) + .build() + } + + return chain.proceed(request) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/interceptor/SignatureInterceptor.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/interceptor/SignatureInterceptor.kt index 8d2becf4..b766cea5 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/interceptor/SignatureInterceptor.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/interceptor/SignatureInterceptor.kt @@ -6,7 +6,12 @@ package pl.szczodrzynski.edziennik.data.api.szkolny.interceptor import okhttp3.Interceptor import okhttp3.Response -import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.BuildConfig +import pl.szczodrzynski.edziennik.ext.bodyToString +import pl.szczodrzynski.edziennik.ext.currentTimeUnix +import pl.szczodrzynski.edziennik.ext.hmacSHA1 +import pl.szczodrzynski.edziennik.ext.md5 class SignatureInterceptor(val app: App) : Interceptor { companion object { @@ -26,6 +31,8 @@ class SignatureInterceptor(val app: App) : Interceptor { .header("X-AppVersion", BuildConfig.VERSION_CODE.toString()) .header("X-Timestamp", timestamp.toString()) .header("X-Signature", sign(timestamp, body, url)) + .header("X-AppBuild", BuildConfig.BUILD_TYPE) + .header("X-AppFlavor", BuildConfig.FLAVOR) .build()) } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/interceptor/Signing.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/interceptor/Signing.kt index 42bd1b08..068268ca 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/interceptor/Signing.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/interceptor/Signing.kt @@ -9,7 +9,7 @@ import android.content.pm.PackageInfo import android.content.pm.PackageManager import android.util.Base64 import pl.szczodrzynski.edziennik.BuildConfig -import pl.szczodrzynski.edziennik.sha256 +import pl.szczodrzynski.edziennik.ext.sha256 import java.security.MessageDigest object Signing { @@ -39,13 +39,13 @@ object Signing { val appPassword by lazy { iLoveApple( "ThisIsOurHardWorkPleaseDoNotCopyOrSteal(c)2019.KubaSz".sha256(), - BuildConfig.VERSION_NAME, + BuildConfig.VERSION_BASE.substringBeforeLast('+'), BuildConfig.VERSION_CODE.toLong() ) } /*fun provideKey(param1: String, param2: Long): ByteArray {*/ fun pleaseStopRightNow(param1: String, param2: Long): ByteArray { - return "$param1.MTIzNDU2Nzg5MDmD46bIpY===.$param2".sha256() + return "$param1.MTIzNDU2Nzg5MD5fPgIjyZ===.$param2".sha256() } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/request/EventShareRequest.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/request/EventShareRequest.kt index 624b8b0f..aba026a4 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/request/EventShareRequest.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/request/EventShareRequest.kt @@ -12,7 +12,9 @@ data class EventShareRequest ( val action: String = "event", - val sharedByName: String, + val userCode: String, + val studentNameLong: String, + val shareTeamCode: String? = null, val unshareTeamCode: String? = null, val requesterName: String? = null, diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/request/NoteShareRequest.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/request/NoteShareRequest.kt new file mode 100644 index 00000000..122ea542 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/request/NoteShareRequest.kt @@ -0,0 +1,25 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-26. + */ + +package pl.szczodrzynski.edziennik.data.api.szkolny.request + +import pl.szczodrzynski.edziennik.data.db.entity.Note + +data class NoteShareRequest ( + val deviceId: String, + val device: Device? = null, + + val action: String = "note", + + val userCode: String, + val studentNameLong: String, + + val shareTeamCode: String? = null, + val unshareTeamCode: String? = null, + val requesterName: String? = null, + + val noteId: Long? = null, + val note: Note? = null +) + diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/ApiResponse.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/ApiResponse.kt index ac56f53f..0987dcef 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/ApiResponse.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/ApiResponse.kt @@ -10,7 +10,10 @@ data class ApiResponse ( val errors: List? = null, - val data: T? = null + val data: T? = null, + + val update: Update? = null, + val registerAvailability: Map? = null ) { data class Error (val code: String, val reason: String) } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/ContributorsResponse.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/ContributorsResponse.kt new file mode 100644 index 00000000..f824280a --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/ContributorsResponse.kt @@ -0,0 +1,20 @@ +package pl.szczodrzynski.edziennik.data.api.szkolny.response + +import android.os.Parcelable +import kotlinx.parcelize.Parcelize + +data class ContributorsResponse( + val contributors: List, + val translators: List +) { + + @Parcelize + data class Item( + val login: String, + val name: String?, + val avatarUrl: String, + val profileUrl: String, + val itemUrl: String, + val contributions: Int? + ) : Parcelable +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/RegisterAvailabilityStatus.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/RegisterAvailabilityStatus.kt new file mode 100644 index 00000000..617a7167 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/RegisterAvailabilityStatus.kt @@ -0,0 +1,26 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-9-2. + */ + +package pl.szczodrzynski.edziennik.data.api.szkolny.response + +import pl.szczodrzynski.edziennik.BuildConfig +import pl.szczodrzynski.edziennik.ext.DAY +import pl.szczodrzynski.edziennik.ext.currentTimeUnix + +data class RegisterAvailabilityStatus( + val available: Boolean, + val name: String?, + val userMessage: Message?, + val nextCheckAt: Long = currentTimeUnix() + 7 * DAY, + val minVersionCode: Int = BuildConfig.VERSION_CODE +) { + data class Message( + val title: String, + val contentShort: String, + val contentLong: String, + val icon: String?, + val image: String?, + val url: String? + ) +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/ServerSyncResponse.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/ServerSyncResponse.kt index 0ed11f9c..e7158754 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/ServerSyncResponse.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/ServerSyncResponse.kt @@ -4,9 +4,11 @@ package pl.szczodrzynski.edziennik.data.api.szkolny.response +import pl.szczodrzynski.edziennik.data.db.entity.Note import pl.szczodrzynski.edziennik.data.db.full.EventFull data class ServerSyncResponse( val events: List, + val notes: List, val hasBrowsers: Boolean? = null ) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/UpdateResponse.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/UpdateResponse.kt index a2028926..63a8ce9d 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/UpdateResponse.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/szkolny/response/UpdateResponse.kt @@ -11,5 +11,6 @@ data class Update( val releaseNotes: String?, val releaseType: String, val isOnGooglePlay: Boolean, - val downloadUrl: String? -) \ No newline at end of file + val downloadUrl: String?, + val updateMandatory: Boolean +) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/task/AppSync.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/task/AppSync.kt index 56d5132a..0b13c867 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/task/AppSync.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/task/AppSync.kt @@ -5,10 +5,13 @@ package pl.szczodrzynski.edziennik.data.api.task import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.api.ERROR_API_INVALID_SIGNATURE import pl.szczodrzynski.edziennik.data.api.szkolny.SzkolnyApi +import pl.szczodrzynski.edziennik.data.api.szkolny.SzkolnyApiException import pl.szczodrzynski.edziennik.data.db.entity.Metadata import pl.szczodrzynski.edziennik.data.db.entity.Notification import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.toErrorCode import pl.szczodrzynski.edziennik.utils.models.Date class AppSync(val app: App, val notifications: MutableList, val profiles: List, val api: SzkolnyApi) { @@ -27,25 +30,34 @@ class AppSync(val app: App, val notifications: MutableList, val pr */ fun run(lastSyncTime: Long, markAsSeen: Boolean = false): Int { val blacklistedIds = app.db.eventDao().blacklistedIds - val events = api.getEvents(profiles, notifications, blacklistedIds, lastSyncTime) + val (events, notes) = try { + api.getEvents(profiles, notifications, blacklistedIds, lastSyncTime) + } catch (e: SzkolnyApiException) { + if (e.toErrorCode() == ERROR_API_INVALID_SIGNATURE) + return 0 + throw e + } app.config.sync.lastAppSync = System.currentTimeMillis() + if (notes.isNotEmpty()) { + app.db.noteDao().addAll(notes) + } + if (events.isNotEmpty()) { val today = Date.getToday() app.db.metadataDao().addAllIgnore(events.map { event -> - val isPast = event.eventDate < today + val isPast = event.date < today Metadata( event.profileId, Metadata.TYPE_EVENT, event.id, isPast || markAsSeen || event.seen, - isPast || markAsSeen || event.notified, - event.addedDate + isPast || markAsSeen || event.notified ) }) - return app.db.eventDao().addAll(events).size + return app.db.eventDao().upsertAll(events).size } - return 0; + return 0 } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/task/Notifications.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/task/Notifications.kt index 7c049f5a..3913709a 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/task/Notifications.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/task/Notifications.kt @@ -8,8 +8,9 @@ import pl.szczodrzynski.edziennik.App import pl.szczodrzynski.edziennik.MainActivity import pl.szczodrzynski.edziennik.R import pl.szczodrzynski.edziennik.data.db.entity.* -import pl.szczodrzynski.edziennik.getNotificationTitle +import pl.szczodrzynski.edziennik.ext.getNotificationTitle import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Week class Notifications(val app: App, val notifications: MutableList, val profiles: List) { companion object { @@ -34,6 +35,7 @@ class Notifications(val app: App, val notifications: MutableList, announcementNotifications() messageNotifications() luckyNumberNotifications() + teacherAbsenceNotifications() } private fun timetableNotifications() { @@ -41,82 +43,122 @@ class Notifications(val app: App, val notifications: MutableList, val text = app.getString( R.string.notification_lesson_change_format, lesson.getDisplayChangeType(app), - if (lesson.displayDate == null) "" else lesson.displayDate!!.formattedString, + lesson.displayDate?.formattedString ?: "", lesson.changeSubjectName ) + val textLong = app.getString( + R.string.notification_lesson_change_long_format, + lesson.getDisplayChangeType(app), + lesson.displayDate?.formattedString ?: "-", + lesson.displayDate?.weekDay?.let { Week.getFullDayName(it) } ?: "-", + lesson.changeSubjectName, + lesson.changeTeacherName + ) notifications += Notification( id = Notification.buildId(lesson.profileId, Notification.TYPE_TIMETABLE_LESSON_CHANGE, lesson.id), title = app.getNotificationTitle(Notification.TYPE_TIMETABLE_LESSON_CHANGE), text = text, + textLong = textLong, type = Notification.TYPE_TIMETABLE_LESSON_CHANGE, profileId = lesson.profileId, profileName = profiles.singleOrNull { it.id == lesson.profileId }?.name, viewId = MainActivity.DRAWER_ITEM_TIMETABLE, - addedDate = lesson.addedDate + addedDate = System.currentTimeMillis() ).addExtra("timetableDate", lesson.displayDate?.stringY_m_d ?: "") } } private fun eventNotifications() { - for (event in app.db.eventDao().notNotifiedNow.filter { it.eventDate >= today }) { - val text = if (event.type == Event.TYPE_HOMEWORK) + app.db.eventDao().getNotNotifiedNow().filter { + it.date >= today + }.forEach { event -> + val text = if (event.isHomework) app.getString( - if (event.subjectLongName.isNullOrEmpty()) - R.string.notification_homework_no_subject_format - else - R.string.notification_homework_format, - event.subjectLongName, - event.eventDate.formattedString + if (event.subjectLongName.isNullOrEmpty()) + R.string.notification_homework_no_subject_format + else + R.string.notification_homework_format, + event.subjectLongName, + event.date.formattedString ) else app.getString( - if (event.subjectLongName.isNullOrEmpty()) - R.string.notification_event_no_subject_format - else - R.string.notification_event_format, - event.typeName, - event.eventDate.formattedString, - event.subjectLongName + if (event.subjectLongName.isNullOrEmpty()) + R.string.notification_event_no_subject_format + else + R.string.notification_event_format, + event.typeName ?: "wydarzenie", + event.date.formattedString, + event.subjectLongName ) - val type = if (event.type == Event.TYPE_HOMEWORK) Notification.TYPE_NEW_HOMEWORK else Notification.TYPE_NEW_EVENT + val textLong = app.getString( + R.string.notification_event_long_format, + event.typeName ?: "-", + event.subjectLongName ?: "-", + event.date.formattedString, + Week.getFullDayName(event.date.weekDay), + event.time?.stringHM ?: app.getString(R.string.event_all_day), + event.topic.take(200) + ) + val type = if (event.isHomework) + Notification.TYPE_NEW_HOMEWORK + else + Notification.TYPE_NEW_EVENT notifications += Notification( - id = Notification.buildId(event.profileId, type, event.id), - title = app.getNotificationTitle(type), - text = text, - type = type, - profileId = event.profileId, - profileName = profiles.singleOrNull { it.id == event.profileId }?.name, - viewId = if (event.type == Event.TYPE_HOMEWORK) MainActivity.DRAWER_ITEM_HOMEWORK else MainActivity.DRAWER_ITEM_AGENDA, - addedDate = event.addedDate - ).addExtra("eventId", event.id).addExtra("eventDate", event.eventDate.value.toLong()) + id = Notification.buildId(event.profileId, type, event.id), + title = app.getNotificationTitle(type), + text = text, + textLong = textLong, + type = type, + profileId = event.profileId, + profileName = profiles.singleOrNull { it.id == event.profileId }?.name, + viewId = if (event.isHomework) MainActivity.DRAWER_ITEM_HOMEWORK else MainActivity.DRAWER_ITEM_AGENDA, + addedDate = event.addedDate + ).addExtra("eventId", event.id).addExtra("eventDate", event.date.value.toLong()) } } fun sharedEventNotifications() { - for (event in app.db.eventDao().notNotifiedNow.filter { it.eventDate >= today && it.sharedBy != null }) { + app.db.eventDao().getNotNotifiedNow().filter { + it.date >= today && it.sharedBy != null && it.sharedBy != "self" + }.forEach { event -> val text = app.getString( - R.string.notification_shared_event_format, - event.sharedByName, - event.typeName ?: "wydarzenie", - event.eventDate.formattedString, - event.topic + R.string.notification_shared_event_format, + event.sharedByName, + event.typeName ?: "wydarzenie", + event.date.formattedString, + event.topicHtml ) - val type = if (event.type == Event.TYPE_HOMEWORK) Notification.TYPE_NEW_HOMEWORK else Notification.TYPE_NEW_EVENT + val textLong = app.getString( + R.string.notification_shared_event_long_format, + event.sharedByName, + event.typeName ?: "-", + event.subjectLongName ?: "-", + event.date.formattedString, + Week.getFullDayName(event.date.weekDay), + event.time?.stringHM ?: app.getString(R.string.event_all_day), + event.topicHtml.take(200) + ) + val type = if (event.isHomework) + Notification.TYPE_NEW_HOMEWORK + else + Notification.TYPE_NEW_EVENT notifications += Notification( - id = Notification.buildId(event.profileId, type, event.id), - title = app.getNotificationTitle(type), - text = text, - type = type, - profileId = event.profileId, - profileName = profiles.singleOrNull { it.id == event.profileId }?.name, - viewId = if (event.type == Event.TYPE_HOMEWORK) MainActivity.DRAWER_ITEM_HOMEWORK else MainActivity.DRAWER_ITEM_AGENDA, - addedDate = event.addedDate - ).addExtra("eventId", event.id).addExtra("eventDate", event.eventDate.value.toLong()) + id = Notification.buildId(event.profileId, type, event.id), + title = app.getNotificationTitle(type), + text = text, + textLong = textLong, + type = type, + profileId = event.profileId, + profileName = profiles.singleOrNull { it.id == event.profileId }?.name, + viewId = if (event.isHomework) MainActivity.DRAWER_ITEM_HOMEWORK else MainActivity.DRAWER_ITEM_AGENDA, + addedDate = event.addedDate + ).addExtra("eventId", event.id).addExtra("eventDate", event.date.value.toLong()) } } private fun gradeNotifications() { - for (grade in app.db.gradeDao().notNotifiedNow) { + for (grade in app.db.gradeDao().getNotNotifiedNow()) { val gradeName = when (grade.type) { Grade.TYPE_SEMESTER1_PROPOSED, Grade.TYPE_SEMESTER2_PROPOSED -> app.getString(R.string.grade_semester_proposed_format_2, grade.name) Grade.TYPE_SEMESTER1_FINAL, Grade.TYPE_SEMESTER2_FINAL -> app.getString(R.string.grade_semester_final_format_2, grade.name) @@ -129,10 +171,20 @@ class Notifications(val app: App, val notifications: MutableList, gradeName, grade.subjectLongName ) + val textLong = app.getString( + R.string.notification_grade_long_format, + gradeName, + grade.weight.toString(), + grade.subjectLongName ?: "-", + grade.category ?: "-", + grade.description ?: "-", + grade.teacherName ?: "-" + ) notifications += Notification( id = Notification.buildId(grade.profileId, Notification.TYPE_NEW_GRADE, grade.id), title = app.getNotificationTitle(Notification.TYPE_NEW_GRADE), text = text, + textLong = textLong, type = Notification.TYPE_NEW_GRADE, profileId = grade.profileId, profileName = profiles.singleOrNull { it.id == grade.profileId }?.name, @@ -143,7 +195,7 @@ class Notifications(val app: App, val notifications: MutableList, } private fun behaviourNotifications() { - for (notice in app.db.noticeDao().notNotifiedNow) { + for (notice in app.db.noticeDao().getNotNotifiedNow()) { val noticeTypeStr = when (notice.type) { Notice.TYPE_POSITIVE -> app.getString(R.string.notification_notice_praise) @@ -154,13 +206,20 @@ class Notifications(val app: App, val notifications: MutableList, val text = app.getString( R.string.notification_notice_format, noticeTypeStr, - notice.teacherFullName, + notice.teacherName, Date.fromMillis(notice.addedDate).formattedString ) + val textLong = app.getString( + R.string.notification_notice_long_format, + noticeTypeStr, + notice.teacherName ?: "-", + notice.text.take(200) + ) notifications += Notification( id = Notification.buildId(notice.profileId, Notification.TYPE_NEW_NOTICE, notice.id), title = app.getNotificationTitle(Notification.TYPE_NEW_NOTICE), text = text, + textLong = textLong, type = Notification.TYPE_NEW_NOTICE, profileId = notice.profileId, profileName = profiles.singleOrNull { it.id == notice.profileId }?.name, @@ -171,9 +230,9 @@ class Notifications(val app: App, val notifications: MutableList, } private fun attendanceNotifications() { - for (attendance in app.db.attendanceDao().notNotifiedNow) { + for (attendance in app.db.attendanceDao().getNotNotifiedNow()) { - val attendanceTypeStr = when (attendance.type) { + val attendanceTypeStr = when (attendance.baseType) { Attendance.TYPE_ABSENT -> app.getString(R.string.notification_absence) Attendance.TYPE_ABSENT_EXCUSED -> app.getString(R.string.notification_absence_excused) Attendance.TYPE_BELATED -> app.getString(R.string.notification_belated) @@ -190,12 +249,23 @@ class Notifications(val app: App, val notifications: MutableList, R.string.notification_attendance_format, attendanceTypeStr, attendance.subjectLongName, - attendance.lessonDate.formattedString + attendance.date.formattedString + ) + val textLong = app.getString( + R.string.notification_attendance_long_format, + attendanceTypeStr, + attendance.date.formattedString, + attendance.startTime?.stringHM ?: "-", + attendance.lessonNumber ?: "-", + attendance.subjectLongName ?: "-", + attendance.teacherName ?: "-", + attendance.lessonTopic ?: "-" ) notifications += Notification( id = Notification.buildId(attendance.profileId, Notification.TYPE_NEW_ATTENDANCE, attendance.id), title = app.getNotificationTitle(Notification.TYPE_NEW_ATTENDANCE), text = text, + textLong = textLong, type = Notification.TYPE_NEW_ATTENDANCE, profileId = attendance.profileId, profileName = profiles.singleOrNull { it.id == attendance.profileId }?.name, @@ -206,10 +276,10 @@ class Notifications(val app: App, val notifications: MutableList, } private fun announcementNotifications() { - for (announcement in app.db.announcementDao().notNotifiedNow) { + for (announcement in app.db.announcementDao().getNotNotifiedNow()) { val text = app.getString( R.string.notification_announcement_format, - announcement.teacherFullName, + announcement.teacherName, announcement.subject ) notifications += Notification( @@ -226,10 +296,10 @@ class Notifications(val app: App, val notifications: MutableList, } private fun messageNotifications() { - for (message in app.db.messageDao().receivedNotNotifiedNow) { + for (message in app.db.messageDao().getNotNotifiedNow()) { val text = app.getString( R.string.notification_message_format, - message.senderFullName, + message.senderName, message.subject ) notifications += Notification( @@ -246,9 +316,9 @@ class Notifications(val app: App, val notifications: MutableList, } private fun luckyNumberNotifications() { - val luckyNumbers = app.db.luckyNumberDao().notNotifiedNow - luckyNumbers?.removeAll { it.date < today } - luckyNumbers?.forEach { luckyNumber -> + val luckyNumbers = app.db.luckyNumberDao().getNotNotifiedNow().toMutableList() + luckyNumbers.removeAll { it.date < today } + luckyNumbers.forEach { luckyNumber -> val profile = profiles.singleOrNull { it.id == luckyNumber.profileId } ?: return@forEach val text = when (profile.studentNumber != -1 && profile.studentNumber == luckyNumber.number) { true -> when (luckyNumber.date.value) { @@ -270,8 +340,27 @@ class Notifications(val app: App, val notifications: MutableList, profileId = luckyNumber.profileId, profileName = profile.name, viewId = MainActivity.DRAWER_ITEM_HOME, - addedDate = luckyNumber.addedDate + addedDate = System.currentTimeMillis() ) } } + + private fun teacherAbsenceNotifications() { + for (teacherAbsence in app.db.teacherAbsenceDao().getNotNotifiedNow()) { + val message = app.getString( + R.string.notification_teacher_absence_new_format, + teacherAbsence.teacherName + ) + notifications += Notification( + id = Notification.buildId(teacherAbsence.profileId, Notification.TYPE_TEACHER_ABSENCE, teacherAbsence.id), + title = app.getNotificationTitle(Notification.TYPE_TEACHER_ABSENCE), + text = message, + type = Notification.TYPE_TEACHER_ABSENCE, + profileId = teacherAbsence.profileId, + profileName = profiles.singleOrNull { it.id == teacherAbsence.profileId }?.name, + viewId = MainActivity.DRAWER_ITEM_AGENDA, + addedDate = teacherAbsence.addedDate + ).addExtra("eventDate", teacherAbsence.dateFrom.value.toLong()) + } + } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/task/PostNotifications.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/task/PostNotifications.kt index 843f2174..41614394 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/task/PostNotifications.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/task/PostNotifications.kt @@ -8,8 +8,15 @@ import android.util.SparseIntArray import androidx.core.app.NotificationCompat import androidx.core.util.forEach import androidx.core.util.set +import com.mikepenz.iconics.IconicsDrawable +import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial +import com.mikepenz.iconics.utils.* import pl.szczodrzynski.edziennik.* import pl.szczodrzynski.edziennik.data.db.entity.Notification.Companion.TYPE_SERVER_MESSAGE +import pl.szczodrzynski.edziennik.ext.Intent +import pl.szczodrzynski.edziennik.ext.asBoldSpannable +import pl.szczodrzynski.edziennik.ext.concat +import pl.szczodrzynski.edziennik.ext.pendingIntentFlag import pl.szczodrzynski.edziennik.utils.models.Time import pl.szczodrzynski.edziennik.data.db.entity.Notification as AppNotification @@ -86,7 +93,7 @@ class PostNotifications(val app: App, nList: List) { MainActivity::class.java, "fragmentId" to MainActivity.DRAWER_ITEM_NOTIFICATIONS ) - val summaryIntent = PendingIntent.getActivity(app, app.notificationChannelsManager.data.id, intent, PendingIntent.FLAG_ONE_SHOT) + val summaryIntent = PendingIntent.getActivity(app, app.notificationChannelsManager.data.id, intent, PendingIntent.FLAG_ONE_SHOT or pendingIntentFlag()) // On Nougat or newer - show maximum 8 notifications // On Marshmallow or older - show maximum 4 notifications @@ -107,6 +114,10 @@ class PostNotifications(val app: App, nList: List) { .setContentText(buildSummaryText(summaryCounts)) .setTicker(newNotificationsText) .setSmallIcon(R.drawable.ic_notification) + .setLargeIcon(IconicsDrawable(app).apply { + icon = CommunityMaterial.Icon.cmd_bell_ring_outline + colorRes = R.color.colorPrimary + }.toBitmap()) .setStyle(NotificationCompat.InboxStyle() .also { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { @@ -137,8 +148,11 @@ class PostNotifications(val app: App, nList: List) { .setSubText(if (it.type == TYPE_SERVER_MESSAGE) null else it.title) .setTicker("${it.profileName}: ${it.title}") .setSmallIcon(R.drawable.ic_notification) + .setLargeIcon(IconicsDrawable(app, it.getLargeIcon()).apply { + colorRes = R.color.colorPrimary + }.toBitmap()) .setStyle(NotificationCompat.BigTextStyle() - .bigText(it.text)) + .bigText(it.textLong ?: it.text)) .setWhen(it.addedDate) .addDefaults() .setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY) @@ -160,6 +174,10 @@ class PostNotifications(val app: App, nList: List) { .setContentText(buildSummaryText(summaryCounts)) .setTicker(newNotificationsText) .setSmallIcon(R.drawable.ic_notification) + .setLargeIcon(IconicsDrawable(app).apply { + icon = CommunityMaterial.Icon.cmd_bell_ring_outline + colorRes = R.color.colorPrimary + }.toBitmap()) .addDefaults() .setGroupSummary(true) .setContentIntent(summaryIntent) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/task/SzkolnyTask.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/task/SzkolnyTask.kt index 3ac80495..39dd7e15 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/api/task/SzkolnyTask.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/api/task/SzkolnyTask.kt @@ -5,12 +5,12 @@ package pl.szczodrzynski.edziennik.data.api.task import pl.szczodrzynski.edziennik.App -import pl.szczodrzynski.edziennik.HOUR import pl.szczodrzynski.edziennik.R import pl.szczodrzynski.edziennik.data.api.interfaces.EdziennikCallback import pl.szczodrzynski.edziennik.data.api.szkolny.SzkolnyApi import pl.szczodrzynski.edziennik.data.db.entity.Notification import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.HOUR import pl.szczodrzynski.edziennik.utils.Utils.d class SzkolnyTask(val app: App, val syncingProfiles: List) : IApiTask(-1) { @@ -31,12 +31,12 @@ class SzkolnyTask(val app: App, val syncingProfiles: List) : IApiTask(- val notifications = Notifications(app, notificationList, profiles) notifications.run() - val appSyncProfiles = profiles.filter { it.registration == Profile.REGISTRATION_ENABLED && !it.archived } + val appSyncProfiles = profiles.filter { it.canShare } // App Sync conditions: // - every 24 hours && any profile is registered // - if there are new notifications && any browser is paired val shouldAppSync = - System.currentTimeMillis() - app.config.sync.lastAppSync > 24*HOUR*1000 + System.currentTimeMillis() - app.config.sync.lastAppSync > 24* HOUR *1000 && appSyncProfiles.isNotEmpty() || notificationList.isNotEmpty() && app.config.sync.webPushEnabled diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/AppDb.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/AppDb.kt index 5b01d476..b7f6ccf2 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/AppDb.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/AppDb.kt @@ -42,8 +42,9 @@ import pl.szczodrzynski.edziennik.data.db.migration.* ConfigEntry::class, LibrusLesson::class, TimetableManual::class, + Note::class, Metadata::class -], version = 79) +], version = 98) @TypeConverters( ConverterTime::class, ConverterDate::class, @@ -82,6 +83,7 @@ abstract class AppDb : RoomDatabase() { abstract fun configDao(): ConfigDao abstract fun librusLessonDao(): LibrusLessonDao abstract fun timetableManualDao(): TimetableManualDao + abstract fun noteDao(): NoteDao abstract fun metadataDao(): MetadataDao companion object { @@ -164,7 +166,26 @@ abstract class AppDb : RoomDatabase() { Migration76(), Migration77(), Migration78(), - Migration79() + Migration79(), + Migration80(), + Migration81(), + Migration82(), + Migration83(), + Migration84(), + Migration85(), + Migration86(), + Migration87(), + Migration88(), + Migration89(), + Migration90(), + Migration91(), + Migration92(), + Migration93(), + Migration94(), + Migration95(), + Migration96(), + Migration97(), + Migration98(), ).allowMainThreadQueries().build() } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/AnnouncementDao.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/AnnouncementDao.java deleted file mode 100644 index ab32fb7c..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/AnnouncementDao.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.dao; - -import androidx.lifecycle.LiveData; -import androidx.room.Dao; -import androidx.room.Insert; -import androidx.room.OnConflictStrategy; -import androidx.room.Query; -import androidx.room.RawQuery; -import androidx.sqlite.db.SimpleSQLiteQuery; -import androidx.sqlite.db.SupportSQLiteQuery; - -import java.util.List; - -import pl.szczodrzynski.edziennik.data.db.entity.Announcement; -import pl.szczodrzynski.edziennik.data.db.entity.Metadata; -import pl.szczodrzynski.edziennik.data.db.full.AnnouncementFull; - -import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_ANNOUNCEMENT; - -@Dao -public abstract class AnnouncementDao { - @Insert(onConflict = OnConflictStrategy.REPLACE) - public abstract long add(Announcement announcement); - - @Insert(onConflict = OnConflictStrategy.REPLACE) - public abstract void addAll(List announcementList); - - @Insert(onConflict = OnConflictStrategy.IGNORE) - public abstract void addAllIgnore(List announcementList); - - @Query("DELETE FROM announcements WHERE profileId = :profileId") - public abstract void clear(int profileId); - - @RawQuery(observedEntities = {Announcement.class, Metadata.class}) - abstract LiveData> getAll(SupportSQLiteQuery query); - public LiveData> getAll(int profileId, String filter) { - return getAll(new SimpleSQLiteQuery("SELECT \n" + - "*, \n" + - "teachers.teacherName || ' ' || teachers.teacherSurname AS teacherFullName\n" + - "FROM announcements \n" + - "LEFT JOIN teachers USING(profileId, teacherId)\n" + - "LEFT JOIN metadata ON announcementId = thingId AND thingType = "+TYPE_ANNOUNCEMENT+" AND metadata.profileId = "+profileId+"\n" + - "WHERE announcements.profileId = "+profileId+" AND "+filter+"\n" + - "ORDER BY addedDate DESC")); - } - public LiveData> getAll(int profileId) { - return getAll(profileId, "1"); - } - public LiveData> getAllWhere(int profileId, String filter) { - return getAll(profileId, filter); - } - - @RawQuery(observedEntities = {Announcement.class, Metadata.class}) - abstract List getAllNow(SupportSQLiteQuery query); - public List getAllNow(int profileId, String filter) { - return getAllNow(new SimpleSQLiteQuery("SELECT \n" + - "*, \n" + - "teachers.teacherName || ' ' || teachers.teacherSurname AS teacherFullName\n" + - "FROM announcements \n" + - "LEFT JOIN teachers USING(profileId, teacherId)\n" + - "LEFT JOIN metadata ON announcementId = thingId AND thingType = "+TYPE_ANNOUNCEMENT+" AND metadata.profileId = "+profileId+"\n" + - "WHERE announcements.profileId = "+profileId+" AND "+filter+"\n" + - "ORDER BY addedDate DESC")); - } - public List getNotNotifiedNow(int profileId) { - return getAllNow(profileId, "notified = 0"); - } - - @Query("SELECT " + - "*, " + - "teachers.teacherName || ' ' || teachers.teacherSurname AS teacherFullName " + - "FROM announcements " + - "LEFT JOIN teachers USING(profileId, teacherId) " + - "LEFT JOIN metadata ON announcementId = thingId AND thingType = "+TYPE_ANNOUNCEMENT+" AND metadata.profileId = announcements.profileId " + - "WHERE notified = 0 " + - "ORDER BY addedDate DESC") - public abstract List getNotNotifiedNow(); -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/AnnouncementDao.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/AnnouncementDao.kt new file mode 100644 index 00000000..88b3ccd1 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/AnnouncementDao.kt @@ -0,0 +1,69 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-25. + */ +package pl.szczodrzynski.edziennik.data.db.dao + +import androidx.lifecycle.LiveData +import androidx.room.Dao +import androidx.room.Query +import androidx.room.RawQuery +import androidx.sqlite.db.SupportSQLiteQuery +import eu.szkolny.selectivedao.annotation.SelectiveDao +import eu.szkolny.selectivedao.annotation.UpdateSelective +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.db.AppDb +import pl.szczodrzynski.edziennik.data.db.entity.Announcement +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.full.AnnouncementFull + +@Dao +@SelectiveDao(db = AppDb::class) +abstract class AnnouncementDao : BaseDao { + companion object { + private const val QUERY = """ + SELECT + *, + teachers.teacherName ||" "|| teachers.teacherSurname AS teacherName + FROM announcements + LEFT JOIN teachers USING(profileId, teacherId) + LEFT JOIN metadata ON announcementId = thingId AND thingType = ${Metadata.TYPE_ANNOUNCEMENT} AND metadata.profileId = announcements.profileId + """ + + private const val ORDER_BY = """ORDER BY addedDate DESC""" + } + + private val selective by lazy { AnnouncementDaoSelective(App.db) } + + @RawQuery(observedEntities = [Announcement::class]) + abstract override fun getRaw(query: SupportSQLiteQuery): LiveData> + @RawQuery(observedEntities = [Announcement::class]) + abstract override fun getOne(query: SupportSQLiteQuery): LiveData + + // SELECTIVE UPDATE + @UpdateSelective(primaryKeys = ["profileId", "announcementId"], skippedColumns = ["addedDate", "announcementText"]) + override fun update(item: Announcement) = selective.update(item) + override fun updateAll(items: List) = selective.updateAll(items) + + // CLEAR + @Query("DELETE FROM announcements WHERE profileId = :profileId") + abstract override fun clear(profileId: Int) + // REMOVE NOT KEPT + @Query("DELETE FROM announcements WHERE keep = 0") + abstract override fun removeNotKept() + + // GET ALL - LIVE DATA + fun getAll(profileId: Int) = + getRaw("$QUERY WHERE announcements.profileId = $profileId $ORDER_BY") + + // GET ALL - NOW + fun getAllNow(profileId: Int) = + getRawNow("$QUERY WHERE announcements.profileId = $profileId $ORDER_BY") + fun getNotNotifiedNow() = + getRawNow("$QUERY WHERE notified = 0 $ORDER_BY") + fun getNotNotifiedNow(profileId: Int) = + getRawNow("$QUERY WHERE announcements.profileId = $profileId AND notified = 0 $ORDER_BY") + + // GET ONE - NOW + fun getByIdNow(profileId: Int, id: Long) = + getOneNow("$QUERY WHERE announcements.profileId = $profileId AND announcementId = $id") +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/AttendanceDao.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/AttendanceDao.java deleted file mode 100644 index 95c3147f..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/AttendanceDao.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.dao; - -import androidx.lifecycle.LiveData; -import androidx.room.Dao; -import androidx.room.Insert; -import androidx.room.OnConflictStrategy; -import androidx.room.Query; -import androidx.room.RawQuery; -import androidx.sqlite.db.SimpleSQLiteQuery; -import androidx.sqlite.db.SupportSQLiteQuery; - -import java.util.List; - -import pl.szczodrzynski.edziennik.data.db.entity.Attendance; -import pl.szczodrzynski.edziennik.data.db.full.AttendanceFull; -import pl.szczodrzynski.edziennik.utils.models.Date; - -import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_ATTENDANCE; - -@Dao -public abstract class AttendanceDao { - @Insert(onConflict = OnConflictStrategy.REPLACE) - public abstract long add(Attendance attendance); - - @Insert(onConflict = OnConflictStrategy.REPLACE) - public abstract void addAll(List attendanceList); - - @Query("DELETE FROM attendances WHERE profileId = :profileId") - public abstract void clear(int profileId); - - @Query("DELETE FROM attendances WHERE profileId = :profileId AND attendanceLessonDate > :date") - public abstract void clearAfterDate(int profileId, Date date); - - @RawQuery(observedEntities = {Attendance.class}) - abstract LiveData> getAll(SupportSQLiteQuery query); - public LiveData> getAll(int profileId, String filter) { - return getAll(new SimpleSQLiteQuery("SELECT \n" + - "*, \n" + - "teachers.teacherName || ' ' || teachers.teacherSurname AS teacherFullName\n" + - "FROM attendances \n" + - "LEFT JOIN teachers USING(profileId, teacherId)\n" + - "LEFT JOIN subjects USING(profileId, subjectId)\n" + - "LEFT JOIN metadata ON attendanceId = thingId AND thingType = " + TYPE_ATTENDANCE + " AND metadata.profileId = "+profileId+"\n" + - "WHERE attendances.profileId = "+profileId+" AND "+filter+"\n" + - "ORDER BY attendanceLessonDate DESC, attendanceStartTime DESC")); - } - public LiveData> getAll(int profileId) { - return getAll(profileId, "1"); - } - public LiveData> getAllWhere(int profileId, String filter) { - return getAll(profileId, filter); - } - - @RawQuery - abstract List getAllNow(SupportSQLiteQuery query); - public List getAllNow(int profileId, String filter) { - return getAllNow(new SimpleSQLiteQuery("SELECT \n" + - "*, \n" + - "teachers.teacherName || ' ' || teachers.teacherSurname AS teacherFullName\n" + - "FROM attendances \n" + - "LEFT JOIN teachers USING(profileId, teacherId)\n" + - "LEFT JOIN subjects USING(profileId, subjectId)\n" + - "LEFT JOIN metadata ON attendanceId = thingId AND thingType = " + TYPE_ATTENDANCE + " AND metadata.profileId = "+profileId+"\n" + - "WHERE attendances.profileId = "+profileId+" AND "+filter+"\n" + - "ORDER BY attendanceLessonDate DESC, attendanceStartTime DESC")); - } - public List getNotNotifiedNow(int profileId) { - return getAllNow(profileId, "notified = 0"); - } - - @Query("SELECT * FROM attendances " + - "LEFT JOIN subjects USING(profileId, subjectId) " + - "LEFT JOIN metadata ON attendanceId = thingId AND thingType = " + TYPE_ATTENDANCE + " AND metadata.profileId = attendances.profileId " + - "WHERE notified = 0 " + - "ORDER BY attendanceLessonDate DESC, attendanceStartTime DESC") - public abstract List getNotNotifiedNow(); - - // only absent and absent_excused count as absences - // all the other types are counted as being present - @Query("SELECT \n" + - "CAST(SUM(CASE WHEN attendanceType != "+Attendance.TYPE_ABSENT+" AND attendanceType != "+ Attendance.TYPE_ABSENT_EXCUSED+" THEN 1 ELSE 0 END) AS float)\n" + - " / \n" + - "CAST(count() AS float)*100 \n" + - "FROM attendances \n" + - "WHERE profileId = :profileId") - public abstract LiveData getAttendancePercentage(int profileId); - - @Query("SELECT \n" + - "CAST(SUM(CASE WHEN attendanceType != "+Attendance.TYPE_ABSENT+" AND attendanceType != "+Attendance.TYPE_ABSENT_EXCUSED+" THEN 1 ELSE 0 END) AS float)\n" + - " / \n" + - "CAST(count() AS float)*100 \n" + - "FROM attendances \n" + - "WHERE profileId = :profileId AND attendanceSemester = :semester") - public abstract float getAttendancePercentageNow(int profileId, int semester); - - @Query("SELECT \n" + - "CAST(SUM(CASE WHEN attendanceType != "+Attendance.TYPE_ABSENT+" AND attendanceType != "+Attendance.TYPE_ABSENT_EXCUSED+" THEN 1 ELSE 0 END) AS float)\n" + - " / \n" + - "CAST(count() AS float)*100 \n" + - "FROM attendances \n" + - "WHERE profileId = :profileId") - public abstract float getAttendancePercentageNow(int profileId); -} - diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/AttendanceDao.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/AttendanceDao.kt new file mode 100644 index 00000000..94be0c34 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/AttendanceDao.kt @@ -0,0 +1,76 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-24. + */ +package pl.szczodrzynski.edziennik.data.db.dao + +import androidx.lifecycle.LiveData +import androidx.room.Dao +import androidx.room.Query +import androidx.room.RawQuery +import androidx.sqlite.db.SupportSQLiteQuery +import eu.szkolny.selectivedao.annotation.SelectiveDao +import eu.szkolny.selectivedao.annotation.UpdateSelective +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.db.AppDb +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.full.AttendanceFull +import pl.szczodrzynski.edziennik.utils.models.Date + +@Dao +@SelectiveDao(db = AppDb::class) +abstract class AttendanceDao : BaseDao { + companion object { + private const val QUERY = """ + SELECT + *, + teachers.teacherName ||" "|| teachers.teacherSurname AS teacherName + FROM attendances + LEFT JOIN teachers USING(profileId, teacherId) + LEFT JOIN subjects USING(profileId, subjectId) + LEFT JOIN metadata ON attendanceId = thingId AND thingType = ${Metadata.TYPE_ATTENDANCE} AND metadata.profileId = attendances.profileId + """ + + private const val ORDER_BY = """ORDER BY attendanceDate DESC, attendanceTime DESC""" + } + + private val selective by lazy { AttendanceDaoSelective(App.db) } + + @RawQuery(observedEntities = [Attendance::class]) + abstract override fun getRaw(query: SupportSQLiteQuery): LiveData> + @RawQuery(observedEntities = [Attendance::class]) + abstract override fun getOne(query: SupportSQLiteQuery): LiveData + + // SELECTIVE UPDATE + @UpdateSelective(primaryKeys = ["profileId", "attendanceId"], skippedColumns = ["addedDate", "announcementText"]) + override fun update(item: Attendance) = selective.update(item) + override fun updateAll(items: List) = selective.updateAll(items) + + // CLEAR + @Query("DELETE FROM attendances WHERE profileId = :profileId") + abstract override fun clear(profileId: Int) + // REMOVE NOT KEPT + @Query("DELETE FROM attendances WHERE keep = 0") + abstract override fun removeNotKept() + + // GET ALL - LIVE DATA + fun getAll(profileId: Int) = + getRaw("$QUERY WHERE attendances.profileId = $profileId $ORDER_BY") + + // GET ALL - NOW + fun getAllNow(profileId: Int) = + getRawNow("$QUERY WHERE attendances.profileId = $profileId $ORDER_BY") + fun getNotNotifiedNow() = + getRawNow("$QUERY WHERE notified = 0 $ORDER_BY") + fun getNotNotifiedNow(profileId: Int) = + getRawNow("$QUERY WHERE attendances.profileId = $profileId AND notified = 0 $ORDER_BY") + fun getAllByDateNow(profileId: Int, date: Date) = + getRawNow("$QUERY WHERE attendances.profileId = $profileId AND attendanceDate = '${date.stringY_m_d}' $ORDER_BY") + + // GET ONE - NOW + fun getByIdNow(profileId: Int, id: Long) = + getOneNow("$QUERY WHERE attendances.profileId = $profileId AND attendanceId = $id") + + @Query("UPDATE attendances SET keep = 0 WHERE profileId = :profileId AND attendanceDate >= :date") + abstract fun dontKeepAfterDate(profileId: Int, date: Date?) +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/BaseDao.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/BaseDao.kt new file mode 100644 index 00000000..60089423 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/BaseDao.kt @@ -0,0 +1,127 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-3-28. + */ + +package pl.szczodrzynski.edziennik.data.db.dao + +import androidx.lifecycle.LiveData +import androidx.room.* +import androidx.sqlite.db.SimpleSQLiteQuery +import androidx.sqlite.db.SupportSQLiteQuery +import pl.szczodrzynski.edziennik.data.db.entity.Keepable + +@Dao +interface BaseDao { + @Transaction + @RawQuery + fun getRaw(query: SupportSQLiteQuery): LiveData> + fun getRaw(query: String) = getRaw(SimpleSQLiteQuery(query)) + @Transaction + @RawQuery + fun getOne(query: SupportSQLiteQuery): LiveData + fun getOne(query: String) = getOne(SimpleSQLiteQuery(query)) + @Transaction + @RawQuery + fun getRawNow(query: SupportSQLiteQuery): List + fun getRawNow(query: String) = getRawNow(SimpleSQLiteQuery(query)) + @Transaction + @RawQuery + fun getOneNow(query: SupportSQLiteQuery): F? + fun getOneNow(query: String) = getOneNow(SimpleSQLiteQuery(query)) + + fun removeNotKept() + + /** + * INSERT an [item] into the database, + * ignoring any conflicts. + */ + @Insert(onConflict = OnConflictStrategy.IGNORE) + fun add(item: T): Long + /** + * INSERT [items] into the database, + * ignoring any conflicts. + */ + @Insert(onConflict = OnConflictStrategy.IGNORE) + fun addAll(items: List): LongArray + + /** + * REPLACE an [item] in the database, + * removing any conflicting rows. + * Creates the item if it does not exist yet. + */ + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun replace(item: T) + /** + * REPLACE [items] in the database, + * removing any conflicting rows. + * Creates items if it does not exist yet. + */ + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun replaceAll(items: List) + + /** + * Selective UPDATE an [item] in the database. + * Do nothing if a matching item does not exist. + */ + fun update(item: T): Long + /** + * Selective UPDATE [items] in the database. + * Do nothing for those items which do not exist. + */ + fun updateAll(items: List): LongArray + + /** + * Remove all items from the database, + * that match the given [profileId]. + */ + fun clear(profileId: Int) + + /** + * INSERT an [item] into the database, + * doing a selective [update] on conflicts. + * @return the newly inserted item's ID or -1L if the item was updated instead + */ + @Transaction + fun upsert(item: T): Long { + val id = add(item) + if (id == -1L) update(item) + return id + } + /** + * INSERT [items] into the database, + * doing a selective [update] on conflicts. + * @return a [LongArray] of IDs of newly inserted items or -1L if the item existed before + */ + @Transaction + fun upsertAll(items: List, removeNotKept: Boolean = false): LongArray { + val insertResult = addAll(items) + val updateList = mutableListOf() + + insertResult.forEachIndexed { index, result -> + if (result == -1L) updateList.add(items[index]) + } + + if (updateList.isNotEmpty()) updateAll(items) + if (removeNotKept) removeNotKept() + return insertResult + } + + /** + * Make sure that [items] are in the database. + * When [forceReplace] == false, do a selective update (UPSERT). + * When [forceReplace] == true, add all items replacing any conflicting ones (REPLACE). + * + * @param forceReplace whether to replace all items instead of selectively updating + * @param removeNotKept whether to remove all items whose [keep] parameter is false + */ + fun putAll(items: List, forceReplace: Boolean = false, removeNotKept: Boolean = false) { + if (items.isEmpty()) + return + if (forceReplace) + replaceAll(items) + else + upsertAll(items, removeNotKept = false) + + if (removeNotKept) removeNotKept() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/EventDao.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/EventDao.java deleted file mode 100644 index 083b499a..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/EventDao.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.dao; - -import android.util.Log; - -import androidx.annotation.NonNull; -import androidx.lifecycle.LiveData; -import androidx.room.Dao; -import androidx.room.Insert; -import androidx.room.OnConflictStrategy; -import androidx.room.Query; -import androidx.room.RawQuery; -import androidx.room.Transaction; -import androidx.sqlite.db.SimpleSQLiteQuery; -import androidx.sqlite.db.SupportSQLiteQuery; - -import java.util.List; - -import pl.szczodrzynski.edziennik.data.db.entity.Event; -import pl.szczodrzynski.edziennik.data.db.full.EventFull; -import pl.szczodrzynski.edziennik.utils.models.Date; -import pl.szczodrzynski.edziennik.utils.models.Time; - -import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_EVENT; -import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_HOMEWORK; -import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_LESSON_CHANGE; - -@Dao -public abstract class EventDao { - @Insert(onConflict = OnConflictStrategy.REPLACE) - public abstract long add(Event event); - - @Insert(onConflict = OnConflictStrategy.REPLACE) - public abstract long[] addAll(List eventList); - - @Query("DELETE FROM events WHERE profileId = :profileId") - public abstract void clear(int profileId); - - @Query("DELETE FROM events WHERE profileId = :profileId AND eventId = :id") - public abstract void remove(int profileId, long id); - @Query("DELETE FROM metadata WHERE profileId = :profileId AND thingType = :thingType AND thingId = :thingId") - public abstract void removeMetadata(int profileId, int thingType, long thingId); - @Transaction - public void remove(int profileId, long type, long id) { - remove(profileId, id); - removeMetadata(profileId, type == Event.TYPE_HOMEWORK ? TYPE_HOMEWORK : TYPE_EVENT, id); - } - @Transaction - public void remove(Event event) { - remove(event.profileId, event.type, event.id); - } - @Transaction - public void remove(int profileId, Event event) { - remove(profileId, event.type, event.id); - } - @Query("DELETE FROM events WHERE teamId = :teamId AND eventId = :id") - public abstract void removeByTeamId(long teamId, long id); - - @RawQuery(observedEntities = {Event.class}) - abstract LiveData> getAll(SupportSQLiteQuery query); - public LiveData> getAll(int profileId, String filter, String limit) { - String query = "SELECT \n" + - "*, \n" + - "teachers.teacherName || ' ' || teachers.teacherSurname AS teacherFullName,\n" + - "eventTypes.eventTypeName AS typeName,\n" + - "eventTypes.eventTypeColor AS typeColor\n" + - "FROM events\n" + - "LEFT JOIN subjects USING(profileId, subjectId)\n" + - "LEFT JOIN teachers USING(profileId, teacherId)\n" + - "LEFT JOIN teams USING(profileId, teamId)\n" + - "LEFT JOIN eventTypes USING(profileId, eventType)\n" + - "LEFT JOIN metadata ON eventId = thingId AND (thingType = " + TYPE_EVENT + " OR thingType = " + TYPE_HOMEWORK + ") AND metadata.profileId = "+profileId+"\n" + - "WHERE events.profileId = "+profileId+" AND events.eventBlacklisted = 0 AND "+filter+"\n" + - "GROUP BY eventId\n" + - "ORDER BY eventDate, eventStartTime ASC "+limit; - Log.d("DB", query); - return getAll(new SimpleSQLiteQuery(query)); - } - public LiveData> getAll(int profileId) { - return getAll(profileId, "1", ""); - } - public List getAllNow(int profileId) { - return getAllNow(profileId, "1"); - } - public LiveData> getAllWhere(int profileId, String filter) { - return getAll(profileId, filter, ""); - } - public LiveData> getAllByType(int profileId, long type, String filter) { - return getAll(profileId, "eventType = "+type+" AND "+filter, ""); - } - public LiveData> getAllByDate(int profileId, @NonNull Date date) { - return getAll(profileId, "eventDate = '"+date.getStringY_m_d()+"'", ""); - } - public List getAllByDateNow(int profileId, @NonNull Date date) { - return getAllNow(profileId, "eventDate = '"+date.getStringY_m_d()+"'"); - } - public LiveData> getAllByDateTime(int profileId, @NonNull Date date, Time time) { - if (time == null) - return getAllByDate(profileId, date); - return getAll(profileId, "eventDate = '"+date.getStringY_m_d()+"' AND eventStartTime = '"+time.getStringValue()+"'", ""); - } - public LiveData> getAllNearest(int profileId, @NonNull Date today, int limit) { - return getAll(profileId, "eventDate >= '"+today.getStringY_m_d()+"'", "LIMIT "+limit); - } - - @RawQuery - abstract List getAllNow(SupportSQLiteQuery query); - public List getAllNow(int profileId, String filter) { - return getAllNow(new SimpleSQLiteQuery("SELECT \n" + - "*, \n" + - "teachers.teacherName || ' ' || teachers.teacherSurname AS teacherFullName,\n" + - "eventTypes.eventTypeName AS typeName,\n" + - "eventTypes.eventTypeColor AS typeColor\n" + - "FROM events \n" + - "LEFT JOIN subjects USING(profileId, subjectId)\n" + - "LEFT JOIN teachers USING(profileId, teacherId)\n" + - "LEFT JOIN teams USING(profileId, teamId)\n" + - "LEFT JOIN eventTypes USING(profileId, eventType)\n" + - "LEFT JOIN metadata ON eventId = thingId AND (thingType = " + TYPE_EVENT + " OR thingType = " + TYPE_HOMEWORK + ") AND metadata.profileId = "+profileId+"\n" + - "WHERE events.profileId = "+profileId+" AND events.eventBlacklisted = 0 AND "+filter+"\n" + - "GROUP BY eventId\n" + - "ORDER BY eventStartTime, addedDate ASC")); - } - public List getNotNotifiedNow(int profileId) { - return getAllNow(profileId, "notified = 0"); - } - - @Query("SELECT eventId FROM events WHERE profileId = :profileId AND eventBlacklisted = 1") - public abstract List getBlacklistedIds(int profileId); - @Query("SELECT eventId FROM events WHERE eventBlacklisted = 1") - public abstract List getBlacklistedIds(); - - @Query("SELECT " + - "*, " + - "eventTypes.eventTypeName AS typeName, " + - "eventTypes.eventTypeColor AS typeColor " + - "FROM events " + - "LEFT JOIN subjects USING(profileId, subjectId) " + - "LEFT JOIN eventTypes USING(profileId, eventType) " + - "LEFT JOIN metadata ON eventId = thingId AND (thingType = " + TYPE_EVENT + " OR thingType = " + TYPE_HOMEWORK + ") AND metadata.profileId = events.profileId " + - "WHERE events.eventBlacklisted = 0 AND notified = 0 " + - "GROUP BY eventId " + - "ORDER BY addedDate ASC") - public abstract List getNotNotifiedNow(); - - public EventFull getByIdNow(int profileId, long eventId) { - List eventList = getAllNow(profileId, "eventId = "+eventId); - return eventList.size() == 0 ? null : eventList.get(0); - } - - @Query("UPDATE events SET eventAddedManually = 1 WHERE profileId = :profileId AND eventDate < :date") - public abstract void convertOlderToManual(int profileId, Date date); - - @Query("DELETE FROM events WHERE profileId = :profileId AND eventAddedManually = 0") - public abstract void removeNotManual(int profileId); - - @RawQuery - abstract long removeFuture(SupportSQLiteQuery query); - @Transaction - public void removeFuture(int profileId, Date todayDate, String filter) { - removeFuture(new SimpleSQLiteQuery("DELETE FROM events WHERE profileId = " + profileId - + " AND eventAddedManually = 0 AND eventDate >= '" + todayDate.getStringY_m_d() + "'" + - " AND " + filter)); - } - - @Query("DELETE FROM events WHERE profileId = :profileId AND eventAddedManually = 0 AND eventDate >= :todayDate AND eventType = :type") - public abstract void removeFutureWithType(int profileId, Date todayDate, long type); - - @Query("DELETE FROM events WHERE profileId = :profileId AND eventAddedManually = 0 AND eventDate >= :todayDate AND eventType != :exceptType") - public abstract void removeFutureExceptType(int profileId, Date todayDate, long exceptType); - - @Transaction - public void removeFutureExceptTypes(int profileId, Date todayDate, List exceptTypes) { - removeFuture(profileId, todayDate, "eventType NOT IN " + exceptTypes.toString().replace('[', '(').replace(']', ')')); - } - - @Query("UPDATE metadata SET seen = :seen WHERE profileId = :profileId AND (thingType = "+TYPE_EVENT+" OR thingType = "+TYPE_LESSON_CHANGE+" OR thingType = "+TYPE_HOMEWORK+") AND thingId IN (SELECT eventId FROM events WHERE profileId = :profileId AND eventDate = :date)") - public abstract void setSeenByDate(int profileId, Date date, boolean seen); - - @Query("UPDATE events SET eventBlacklisted = :blacklisted WHERE profileId = :profileId AND eventId = :eventId") - public abstract void setBlacklisted(int profileId, long eventId, boolean blacklisted); -} - diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/EventDao.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/EventDao.kt new file mode 100644 index 00000000..24e58d02 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/EventDao.kt @@ -0,0 +1,163 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-1-6 + */ +package pl.szczodrzynski.edziennik.data.db.dao + +import androidx.lifecycle.LiveData +import androidx.room.Dao +import androidx.room.Query +import androidx.room.RawQuery +import androidx.room.Transaction +import androidx.sqlite.db.SimpleSQLiteQuery +import androidx.sqlite.db.SupportSQLiteQuery +import eu.szkolny.selectivedao.annotation.SelectiveDao +import eu.szkolny.selectivedao.annotation.UpdateSelective +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.db.AppDb +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time + +@Dao +@SelectiveDao(db = AppDb::class) +abstract class EventDao : BaseDao { + companion object { + private const val QUERY = """ + SELECT + *, + teachers.teacherName ||" "|| teachers.teacherSurname AS teacherName, + eventTypes.eventTypeName AS typeName, + eventTypes.eventTypeColor AS typeColor + FROM events + LEFT JOIN teachers USING(profileId, teacherId) + LEFT JOIN subjects USING(profileId, subjectId) + LEFT JOIN teams USING(profileId, teamId) + LEFT JOIN eventTypes USING(profileId, eventType) + LEFT JOIN metadata ON eventId = thingId AND (thingType = ${Metadata.TYPE_EVENT} OR thingType = ${Metadata.TYPE_HOMEWORK}) AND metadata.profileId = events.profileId + """ + + private const val ORDER_BY = """GROUP BY eventId ORDER BY eventDate, eventTime, addedDate ASC""" + private const val NOT_BLACKLISTED = """events.eventBlacklisted = 0""" + private const val NOT_DONE = """events.eventIsDone = 0""" + } + + private val selective by lazy { EventDaoSelective(App.db) } + + @RawQuery(observedEntities = [Event::class]) + abstract override fun getRaw(query: SupportSQLiteQuery): LiveData> + @RawQuery(observedEntities = [Event::class]) + abstract override fun getOne(query: SupportSQLiteQuery): LiveData + + // SELECTIVE UPDATE + @UpdateSelective(primaryKeys = ["profileId", "eventId"], skippedColumns = ["eventIsDone", "eventBlacklisted", "homeworkBody", "attachmentIds", "attachmentNames"]) + override fun update(item: Event) = selective.update(item) + override fun updateAll(items: List) = selective.updateAll(items) + + // CLEAR + @Query("DELETE FROM events WHERE profileId = :profileId") + abstract override fun clear(profileId: Int) + // REMOVE NOT KEPT + @Query("DELETE FROM events WHERE keep = 0") + abstract override fun removeNotKept() + + // GET ALL - LIVE DATA + fun getAll(profileId: Int) = + getRaw("$QUERY WHERE $NOT_BLACKLISTED AND events.profileId = $profileId $ORDER_BY") + fun getAllByType(profileId: Int, type: Long, filter: String = "1") = + getRaw("$QUERY WHERE $NOT_BLACKLISTED AND events.profileId = $profileId AND eventType = $type AND $filter $ORDER_BY") + fun getAllByDate(profileId: Int, date: Date) = + getRaw("$QUERY WHERE $NOT_BLACKLISTED AND events.profileId = $profileId AND eventDate = '${date.stringY_m_d}' $ORDER_BY") + fun getAllByDateTime(profileId: Int, date: Date, time: Time) = + getRaw("$QUERY WHERE $NOT_BLACKLISTED AND events.profileId = $profileId AND eventDate = '${date.stringY_m_d}' AND eventTime = '${time.stringValue}' $ORDER_BY") + fun getNearestNotDone(profileId: Int, today: Date, limit: Int) = + getRaw("$QUERY WHERE $NOT_BLACKLISTED AND $NOT_DONE AND events.profileId = $profileId AND eventDate >= '${today.stringY_m_d}' $ORDER_BY LIMIT $limit") + + // GET ALL - NOW + fun getAllNow(profileId: Int) = + getRawNow("$QUERY WHERE $NOT_BLACKLISTED AND events.profileId = $profileId $ORDER_BY") + fun getNotNotifiedNow() = + getRawNow("$QUERY WHERE $NOT_BLACKLISTED AND notified = 0 $ORDER_BY") + fun getNotNotifiedNow(profileId: Int) = + getRawNow("$QUERY WHERE $NOT_BLACKLISTED AND events.profileId = $profileId AND notified = 0 $ORDER_BY") + fun getAllByDateNow(profileId: Int, date: Date) = + getRawNow("$QUERY WHERE $NOT_BLACKLISTED AND events.profileId = $profileId AND eventDate = '${date.stringY_m_d}' $ORDER_BY") + + // GET ONE - LIVE DATA + fun getById(profileId: Int, id: Long) = + getOne("$QUERY WHERE events.profileId = $profileId AND eventId = $id") + + // GET ONE - NOW + fun getByIdNow(profileId: Int, id: Long) = + getOneNow("$QUERY WHERE events.profileId = $profileId AND eventId = $id") + + + @Query("SELECT eventId FROM events WHERE profileId = :profileId AND eventBlacklisted = 1") + abstract fun getBlacklistedIds(profileId: Int): List + + @get:Query("SELECT eventId FROM events WHERE eventBlacklisted = 1") + abstract val blacklistedIds: List + + /*@Query("UPDATE events SET eventAddedManually = 1 WHERE profileId = :profileId AND eventDate < :date") + abstract fun convertOlderToManual(profileId: Int, date: Date?) + + @Query("DELETE FROM events WHERE teamId = :teamId AND eventId = :id") + abstract fun removeByTeamId(teamId: Long, id: Long) + + @Query("DELETE FROM events WHERE profileId = :profileId AND eventAddedManually = 0") + abstract fun removeNotManual(profileId: Int)*/ + + @RawQuery + abstract fun dontKeepFuture(query: SupportSQLiteQuery): Long + + @Transaction + open fun dontKeepFuture(profileId: Int, todayDate: Date, filter: String) { + dontKeepFuture(SimpleSQLiteQuery("UPDATE events SET keep = 0 WHERE profileId = " + profileId + + " AND eventAddedManually = 0 AND eventDate >= '" + todayDate.stringY_m_d + "'" + + " AND " + filter)) + } + + @Query("UPDATE events SET keep = 0 WHERE profileId = :profileId AND eventAddedManually = 0 AND eventDate >= :todayDate") + abstract fun dontKeepFuture(profileId: Int, todayDate: Date) + + @Query("UPDATE events SET keep = 0 WHERE profileId = :profileId AND eventAddedManually = 0 AND eventDate >= :todayDate AND eventType = :type") + abstract fun dontKeepFutureWithType(profileId: Int, todayDate: Date, type: Long) + + @Query("UPDATE events SET keep = 0 WHERE profileId = :profileId AND eventAddedManually = 0 AND eventDate >= :todayDate AND eventType != :exceptType") + abstract fun dontKeepFutureExceptType(profileId: Int, todayDate: Date, exceptType: Long) + + @Transaction + open fun dontKeepFutureExceptTypes(profileId: Int, todayDate: Date, exceptTypes: List) { + dontKeepFuture(profileId, todayDate, "eventType NOT IN " + exceptTypes.toString().replace('[', '(').replace(']', ')')) + } + + @Query("UPDATE metadata SET seen = :seen WHERE profileId = :profileId AND (thingType = " + Metadata.TYPE_EVENT + " OR thingType = " + Metadata.TYPE_LESSON_CHANGE + " OR thingType = " + Metadata.TYPE_HOMEWORK + ") AND thingId IN (SELECT eventId FROM events WHERE profileId = :profileId AND eventDate = :date)") + abstract fun setSeenByDate(profileId: Int, date: Date, seen: Boolean) + + @Query("UPDATE events SET eventBlacklisted = :blacklisted WHERE profileId = :profileId AND eventId = :eventId") + abstract fun setBlacklisted(profileId: Int, eventId: Long, blacklisted: Boolean) + + @Query("DELETE FROM events WHERE profileId = :profileId AND eventId = :id") + abstract fun remove(profileId: Int, id: Long) + + @Query("DELETE FROM metadata WHERE profileId = :profileId AND thingType = :thingType AND thingId = :thingId") + abstract fun removeMetadata(profileId: Int, thingType: Int, thingId: Long) + + @Transaction + open fun remove(profileId: Int, type: Long, id: Long) { + remove(profileId, id) + removeMetadata(profileId, if (type == Event.TYPE_HOMEWORK) Metadata.TYPE_HOMEWORK else Metadata.TYPE_EVENT, id) + } + + @Transaction + open fun remove(event: Event) { + remove(event.profileId, event.type, event.id) + } + + @Transaction + open fun remove(profileId: Int, event: Event) { + remove(profileId, event.type, event.id) + } + +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/EventTypeDao.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/EventTypeDao.java deleted file mode 100644 index 25366699..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/EventTypeDao.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.dao; - -import androidx.lifecycle.LiveData; -import androidx.room.Dao; -import androidx.room.Insert; -import androidx.room.OnConflictStrategy; -import androidx.room.Query; - -import java.util.List; - -import pl.szczodrzynski.edziennik.data.db.entity.EventType; - -@Dao -public interface EventTypeDao { - @Insert(onConflict = OnConflictStrategy.REPLACE) - void add(EventType gradeCategory); - - @Insert(onConflict = OnConflictStrategy.REPLACE) - void addAll(List gradeCategoryList); - - @Query("DELETE FROM eventTypes WHERE profileId = :profileId") - void clear(int profileId); - - @Query("SELECT * FROM eventTypes WHERE profileId = :profileId AND eventType = :typeId") - EventType getByIdNow(int profileId, long typeId); - - @Query("SELECT * FROM eventTypes WHERE profileId = :profileId") - LiveData> getAll(int profileId); - - @Query("SELECT * FROM eventTypes WHERE profileId = :profileId") - List getAllNow(int profileId); - - @Query("SELECT * FROM eventTypes") - List getAllNow(); -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/EventTypeDao.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/EventTypeDao.kt new file mode 100644 index 00000000..d5006970 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/EventTypeDao.kt @@ -0,0 +1,55 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-1-6 + */ +package pl.szczodrzynski.edziennik.data.db.dao + +import android.content.Context +import androidx.lifecycle.LiveData +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.COLOR_DEFAULT +import pl.szczodrzynski.edziennik.data.db.entity.EventType +import pl.szczodrzynski.edziennik.data.db.entity.EventType.Companion.SOURCE_DEFAULT + +@Dao +abstract class EventTypeDao { + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract fun add(eventType: EventType) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract fun addAll(eventTypeList: List) + + @Query("DELETE FROM eventTypes WHERE profileId = :profileId") + abstract fun clear(profileId: Int) + + @Query("SELECT * FROM eventTypes WHERE profileId = :profileId AND eventType = :typeId") + abstract fun getByIdNow(profileId: Int, typeId: Long): EventType? + + @Query("SELECT * FROM eventTypes WHERE profileId = :profileId") + abstract fun getAll(profileId: Int): LiveData> + + @Query("SELECT * FROM eventTypes WHERE profileId = :profileId") + abstract fun getAllNow(profileId: Int): List + + @get:Query("SELECT * FROM eventTypes") + abstract val allNow: List + + fun addDefaultTypes(context: Context, profileId: Int): List { + var order = 100 + val colorMap = EventType.getTypeColorMap() + val typeList = EventType.getTypeNameMap().map { (id, name) -> + EventType( + profileId = profileId, + id = id, + name = context.getString(name), + color = colorMap[id] ?: COLOR_DEFAULT, + order = order++, + source = SOURCE_DEFAULT + ) + } + addAll(typeList) + return typeList + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/GradeDao.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/GradeDao.kt index 9c3e93c5..6254f80b 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/GradeDao.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/GradeDao.kt @@ -1,102 +1,103 @@ /* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 + * Copyright (c) Kuba Szczodrzyński 2020-4-24. */ package pl.szczodrzynski.edziennik.data.db.dao import androidx.lifecycle.LiveData -import androidx.room.* -import androidx.sqlite.db.SimpleSQLiteQuery +import androidx.room.Dao +import androidx.room.Query +import androidx.room.RawQuery +import androidx.room.Transaction import androidx.sqlite.db.SupportSQLiteQuery +import eu.szkolny.selectivedao.annotation.SelectiveDao +import eu.szkolny.selectivedao.annotation.UpdateSelective +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.db.AppDb import pl.szczodrzynski.edziennik.data.db.entity.Grade import pl.szczodrzynski.edziennik.data.db.entity.Metadata import pl.szczodrzynski.edziennik.data.db.full.GradeFull +import pl.szczodrzynski.edziennik.utils.models.Date import java.util.* -import kotlin.collections.List import kotlin.collections.component1 import kotlin.collections.component2 -import kotlin.collections.iterator import kotlin.collections.set @Dao -abstract class GradeDao { - @Insert(onConflict = OnConflictStrategy.REPLACE) - abstract fun add(grade: Grade): Long +@SelectiveDao(db = AppDb::class) +abstract class GradeDao : BaseDao { + companion object { + private const val QUERY = """ + SELECT + *, + teachers.teacherName ||" "|| teachers.teacherSurname AS teacherName + FROM grades + LEFT JOIN teachers USING(profileId, teacherId) + LEFT JOIN subjects USING(profileId, subjectId) + LEFT JOIN metadata ON gradeId = thingId AND thingType = ${Metadata.TYPE_GRADE} AND metadata.profileId = grades.profileId + """ - @Insert(onConflict = OnConflictStrategy.REPLACE) - abstract fun addAll(gradeList: List) + private const val ORDER_BY = """ORDER BY addedDate DESC""" + } - @Query("DELETE FROM grades WHERE profileId = :profileId") - abstract fun clear(profileId: Int) - - @Query("DELETE FROM grades WHERE profileId = :profileId AND gradeType = :type") - abstract fun clearWithType(profileId: Int, type: Int) - - @Query("DELETE FROM grades WHERE profileId = :profileId AND gradeSemester = :semester") - abstract fun clearForSemester(profileId: Int, semester: Int) - - @Query("DELETE FROM grades WHERE profileId = :profileId AND gradeSemester = :semester AND gradeType = :type") - abstract fun clearForSemesterWithType(profileId: Int, semester: Int, type: Int) + private val selective by lazy { GradeDaoSelective(App.db) } @RawQuery(observedEntities = [Grade::class]) - abstract fun getAll(query: SupportSQLiteQuery?): LiveData> + abstract override fun getRaw(query: SupportSQLiteQuery): LiveData> + @RawQuery(observedEntities = [Grade::class]) + abstract override fun getOne(query: SupportSQLiteQuery): LiveData - fun getAll(profileId: Int, filter: String, orderBy: String): LiveData> { - return getAll(SimpleSQLiteQuery("SELECT \n" + - "*, \n" + - "teachers.teacherName || ' ' || teachers.teacherSurname AS teacherFullName\n" + - "FROM grades \n" + - "LEFT JOIN subjects USING(profileId, subjectId)\n" + - "LEFT JOIN teachers USING(profileId, teacherId)\n" + - "LEFT JOIN metadata ON gradeId = thingId AND thingType = " + Metadata.TYPE_GRADE + " AND metadata.profileId = " + profileId + "\n" + - "WHERE grades.profileId = " + profileId + " AND " + filter + "\n" + - "ORDER BY " + orderBy)) // TODO: 2019-04-30 why did I add sorting by gradeType??? - } + // SELECTIVE UPDATE + @UpdateSelective(primaryKeys = ["profileId", "gradeId"], skippedColumns = ["addedDate", "gradeClassAverage"]) + override fun update(item: Grade) = selective.update(item) + override fun updateAll(items: List) = selective.updateAll(items) - fun getAllOrderBy(profileId: Int, orderBy: String): LiveData> { - return getAll(profileId, "1", orderBy) - } + // CLEAR + @Query("DELETE FROM grades WHERE profileId = :profileId") + abstract override fun clear(profileId: Int) + // REMOVE NOT KEPT + @Query("DELETE FROM grades WHERE keep = 0") + abstract override fun removeNotKept() - fun getAllWhere(profileId: Int, filter: String): LiveData> { - return getAll(profileId, filter, "addedDate DESC") - } + // GET ALL - LIVE DATA + fun getAll(profileId: Int) = + getRaw("$QUERY WHERE grades.profileId = $profileId $ORDER_BY") + fun getAllFromDate(profileId: Int, date: Date) = + getRaw("$QUERY WHERE grades.profileId = $profileId AND addedDate > ${date.inMillis} $ORDER_BY") + fun getAllBySubject(profileId: Int, subjectId: Long) = + getRaw("$QUERY WHERE grades.profileId = $profileId AND subjectId = $subjectId $ORDER_BY") + fun getAllOrderBy(profileId: Int, orderBy: String) = + getRaw("$QUERY WHERE grades.profileId = $profileId ORDER BY $orderBy") - @RawQuery - abstract fun getAllNow(query: SupportSQLiteQuery?): List + // GET ALL - NOW + fun getAllNow(profileId: Int) = + getRawNow("$QUERY WHERE grades.profileId = $profileId $ORDER_BY") + fun getNotNotifiedNow() = + getRawNow("$QUERY WHERE notified = 0 $ORDER_BY") + fun getNotNotifiedNow(profileId: Int) = + getRawNow("$QUERY WHERE grades.profileId = $profileId AND notified = 0 $ORDER_BY") + fun getByParentIdNow(profileId: Int, parentId: Long) = + getRawNow("$QUERY WHERE grades.profileId = $profileId AND gradeParentId = $parentId $ORDER_BY") - fun getAllNow(profileId: Int, filter: String): List { - return getAllNow(SimpleSQLiteQuery("SELECT \n" + - "*, \n" + - "teachers.teacherName || ' ' || teachers.teacherSurname AS teacherFullName\n" + - "FROM grades \n" + - "LEFT JOIN subjects USING(profileId, subjectId)\n" + - "LEFT JOIN teachers USING(profileId, teacherId)\n" + - "LEFT JOIN metadata ON gradeId = thingId AND thingType = " + Metadata.TYPE_GRADE + " AND metadata.profileId = " + profileId + "\n" + - "WHERE grades.profileId = " + profileId + " AND " + filter + "\n" + - "ORDER BY addedDate DESC")) - } + // GET ONE - NOW + fun getByIdNow(profileId: Int, id: Long) = + getOneNow("$QUERY WHERE grades.profileId = $profileId AND gradeId = $id") - fun getNotNotifiedNow(profileId: Int): List { - return getAllNow(profileId, "notified = 0") - } + @Query("UPDATE grades SET keep = 0 WHERE profileId = :profileId AND gradeType = :type") + abstract fun dontKeepWithType(profileId: Int, type: Int) - fun getAllWithParentIdNow(profileId: Int, parentId: Long): List { - return getAllNow(profileId, "gradeParentId = $parentId") - } + @Query("UPDATE grades SET keep = 0 WHERE profileId = :profileId AND gradeSemester = :semester") + abstract fun dontKeepForSemester(profileId: Int, semester: Int) - @get:Query("SELECT * FROM grades " + - "LEFT JOIN subjects USING(profileId, subjectId) " + - "LEFT JOIN metadata ON gradeId = thingId AND thingType = " + Metadata.TYPE_GRADE + " AND metadata.profileId = grades.profileId " + - "WHERE notified = 0 " + - "ORDER BY addedDate DESC") - abstract val notNotifiedNow: List + @Query("UPDATE grades SET keep = 0 WHERE profileId = :profileId AND gradeSemester = :semester AND gradeType = :type") + abstract fun dontKeepForSemesterWithType(profileId: Int, semester: Int, type: Int) - @RawQuery - abstract fun getNow(query: SupportSQLiteQuery): GradeFull? + + // GRADE DETAILS - MOBIDZIENNIK @Query("UPDATE grades SET gradeClassAverage = :classAverage, gradeColor = :color WHERE profileId = :profileId AND gradeId = :gradeId") abstract fun updateDetailsById(profileId: Int, gradeId: Long, classAverage: Float, color: Int) - @Query("UPDATE metadata SET addedDate = :addedDate WHERE profileId = :profileId AND thingType = " + Metadata.TYPE_GRADE + " AND thingId = :gradeId") + @Query("UPDATE grades SET addedDate = :addedDate WHERE profileId = :profileId AND gradeId = :gradeId") abstract fun updateAddedDateById(profileId: Int, gradeId: Long, addedDate: Long) @Transaction @@ -118,7 +119,7 @@ abstract class GradeDao { @Query("SELECT gradeColor FROM grades WHERE profileId = :profileId ORDER BY gradeId") abstract fun getColors(profileId: Int): List - @Query("SELECT addedDate FROM metadata WHERE profileId = :profileId AND thingType = " + Metadata.TYPE_GRADE + " ORDER BY thingId") + @Query("SELECT addedDate FROM grades WHERE profileId = :profileId ORDER BY gradeId") abstract fun getAddedDates(profileId: Int): List @Transaction @@ -134,8 +135,4 @@ abstract class GradeDao { gradeAddedDates[gradeId] = addedDates.next() } } - - fun getAllFromDate(profileId: Int, date: Long): LiveData> { - return getAllWhere(profileId, "addedDate > $date") - } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/LuckyNumberDao.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/LuckyNumberDao.java deleted file mode 100644 index c1c33c23..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/LuckyNumberDao.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.dao; - -import androidx.annotation.Nullable; -import androidx.lifecycle.LiveData; -import androidx.room.Dao; -import androidx.room.Insert; -import androidx.room.OnConflictStrategy; -import androidx.room.Query; -import androidx.room.RawQuery; -import androidx.sqlite.db.SimpleSQLiteQuery; -import androidx.sqlite.db.SupportSQLiteQuery; - -import java.util.List; - -import pl.szczodrzynski.edziennik.data.db.entity.LuckyNumber; -import pl.szczodrzynski.edziennik.data.db.entity.Metadata; -import pl.szczodrzynski.edziennik.data.db.entity.Notice; -import pl.szczodrzynski.edziennik.data.db.full.LuckyNumberFull; -import pl.szczodrzynski.edziennik.utils.models.Date; - -import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_LUCKY_NUMBER; - -@Dao -public abstract class LuckyNumberDao { - @Insert(onConflict = OnConflictStrategy.REPLACE) - public abstract void add(LuckyNumber luckyNumber); - - @Insert(onConflict = OnConflictStrategy.REPLACE) - public abstract void addAll(List luckyNumberList); - - @Query("DELETE FROM luckyNumbers WHERE profileId = :profileId") - public abstract void clear(int profileId); - - @Query("SELECT * FROM luckyNumbers WHERE profileId = :profileId AND luckyNumberDate = :date") - public abstract LiveData getByDate(int profileId, Date date); - - @Query("SELECT * FROM luckyNumbers WHERE profileId = :profileId AND luckyNumberDate = :date") - public abstract LuckyNumber getByDateNow(int profileId, Date date); - - @Nullable - @Query("SELECT * FROM luckyNumbers WHERE profileId = :profileId AND luckyNumberDate >= :date ORDER BY luckyNumberDate DESC LIMIT 1") - public abstract LuckyNumber getNearestFutureNow(int profileId, int date); - - @Query("SELECT * FROM luckyNumbers WHERE profileId = :profileId AND luckyNumberDate >= :date ORDER BY luckyNumberDate DESC LIMIT 1") - public abstract LiveData getNearestFuture(int profileId, int date); - - @RawQuery(observedEntities = {LuckyNumber.class}) - abstract LiveData> getAll(SupportSQLiteQuery query); - public LiveData> getAll(int profileId, String filter) { - return getAll(new SimpleSQLiteQuery("SELECT\n" + - "*\n" + - "FROM luckyNumbers\n" + - "LEFT JOIN metadata ON luckyNumberDate = thingId AND thingType = "+TYPE_LUCKY_NUMBER+" AND metadata.profileId = "+profileId+"\n" + - "WHERE luckyNumbers.profileId = "+profileId+" AND "+filter+"\n" + - "ORDER BY addedDate DESC")); - } - public LiveData> getAll(int profileId) { - return getAll(profileId, "1"); - } - public LiveData> getAllWhere(int profileId, String filter) { - return getAll(profileId, filter); - } - - @RawQuery(observedEntities = {Notice.class, Metadata.class}) - abstract List getAllNow(SupportSQLiteQuery query); - public List getAllNow(int profileId, String filter) { - return getAllNow(new SimpleSQLiteQuery("SELECT\n" + - "*\n" + - "FROM luckyNumbers\n" + - "LEFT JOIN metadata ON luckyNumberDate = thingId AND thingType = "+TYPE_LUCKY_NUMBER+" AND metadata.profileId = "+profileId+"\n" + - "WHERE luckyNumbers.profileId = "+profileId+" AND "+filter+"\n" + - "ORDER BY addedDate DESC")); - } - public List getNotNotifiedNow(int profileId) { - return getAllNow(profileId, "notified = 0"); - } - - @Query("SELECT * FROM luckyNumbers\n" + - "LEFT JOIN metadata ON luckyNumberDate = thingId AND thingType = "+TYPE_LUCKY_NUMBER+" AND metadata.profileId = luckyNumbers.profileId " + - "WHERE notified = 0 " + - "ORDER BY addedDate DESC") - public abstract List getNotNotifiedNow(); -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/LuckyNumberDao.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/LuckyNumberDao.kt new file mode 100644 index 00000000..3c752124 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/LuckyNumberDao.kt @@ -0,0 +1,74 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-25. + */ +package pl.szczodrzynski.edziennik.data.db.dao + +import androidx.lifecycle.LiveData +import androidx.room.Dao +import androidx.room.Query +import androidx.room.RawQuery +import androidx.sqlite.db.SupportSQLiteQuery +import eu.szkolny.selectivedao.annotation.SelectiveDao +import eu.szkolny.selectivedao.annotation.UpdateSelective +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.db.AppDb +import pl.szczodrzynski.edziennik.data.db.entity.LuckyNumber +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.full.LuckyNumberFull +import pl.szczodrzynski.edziennik.utils.models.Date + +@Dao +@SelectiveDao(db = AppDb::class) +abstract class LuckyNumberDao : BaseDao { + companion object { + private const val QUERY = """ + SELECT + * + FROM luckyNumbers + LEFT JOIN metadata ON luckyNumberDate = thingId AND thingType = ${Metadata.TYPE_LUCKY_NUMBER} AND metadata.profileId = luckyNumbers.profileId + """ + + private const val ORDER_BY = """ORDER BY luckyNumberDate DESC""" + } + + private val selective by lazy { LuckyNumberDaoSelective(App.db) } + + @RawQuery(observedEntities = [LuckyNumber::class]) + abstract override fun getRaw(query: SupportSQLiteQuery): LiveData> + @RawQuery(observedEntities = [LuckyNumber::class]) + abstract override fun getOne(query: SupportSQLiteQuery): LiveData + + // SELECTIVE UPDATE + @UpdateSelective(primaryKeys = ["profileId", "luckyNumberDate"], skippedColumns = ["addedDate"]) + override fun update(item: LuckyNumber) = selective.update(item) + override fun updateAll(items: List) = selective.updateAll(items) + + // CLEAR + @Query("DELETE FROM luckyNumbers WHERE profileId = :profileId") + abstract override fun clear(profileId: Int) + // REMOVE NOT KEPT + @Query("DELETE FROM luckyNumbers WHERE keep = 0") + abstract override fun removeNotKept() + + // GET ALL - LIVE DATA + fun getAll(profileId: Int) = + getRaw("$QUERY WHERE luckyNumbers.profileId = $profileId $ORDER_BY") + + // GET ALL - NOW + fun getAllNow(profileId: Int) = + getRawNow("$QUERY WHERE luckyNumbers.profileId = $profileId $ORDER_BY") + fun getNotNotifiedNow() = + getRawNow("$QUERY WHERE notified = 0 $ORDER_BY") + fun getNotNotifiedNow(profileId: Int) = + getRawNow("$QUERY WHERE luckyNumbers.profileId = $profileId AND notified = 0 $ORDER_BY") + + // GET ONE - LIVE DATA + fun getNearestFuture(profileId: Int, today: Date) = + getOne("$QUERY WHERE luckyNumbers.profileId = $profileId AND luckyNumberDate >= ${today.value} $ORDER_BY LIMIT 1") + + // GET ONE - NOW + fun getByIdNow(profileId: Int, id: Long) = + getOneNow("$QUERY WHERE attendances.profileId = $profileId AND attendanceId = $id") + fun getNearestFutureNow(profileId: Int, today: Date) = + getOneNow("$QUERY WHERE luckyNumbers.profileId = $profileId AND luckyNumberDate >= ${today.value} $ORDER_BY LIMIT 1") +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/MessageDao.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/MessageDao.java deleted file mode 100644 index bc3a46a5..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/MessageDao.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.dao; - -import androidx.annotation.Nullable; -import androidx.lifecycle.LiveData; -import androidx.room.Dao; -import androidx.room.Insert; -import androidx.room.OnConflictStrategy; -import androidx.room.Query; -import androidx.room.RawQuery; -import androidx.sqlite.db.SimpleSQLiteQuery; -import androidx.sqlite.db.SupportSQLiteQuery; - -import java.util.List; - -import pl.szczodrzynski.edziennik.data.db.entity.Message; -import pl.szczodrzynski.edziennik.data.db.entity.Metadata; -import pl.szczodrzynski.edziennik.data.db.full.MessageFull; - -import static pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_DELETED; -import static pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_RECEIVED; -import static pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_SENT; -import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_MESSAGE; - -@Dao -public abstract class MessageDao { - @Insert(onConflict = OnConflictStrategy.REPLACE) - public abstract long add(Message message); - - @Insert(onConflict = OnConflictStrategy.REPLACE) - public abstract void addAll(List messageList); - - @Insert(onConflict = OnConflictStrategy.IGNORE) - public abstract void addAllIgnore(List messageList); - - @Query("DELETE FROM messages WHERE profileId = :profileId") - public abstract void clear(int profileId); - - @RawQuery(observedEntities = {Message.class}) - abstract LiveData> getAll(SupportSQLiteQuery query); - @RawQuery(observedEntities = {Message.class, Metadata.class}) - abstract List getNow(SupportSQLiteQuery query); - @RawQuery(observedEntities = {Message.class, Metadata.class}) - abstract MessageFull getOneNow(SupportSQLiteQuery query); - - public LiveData> getWithMetadataAndSenderName(int profileId, int messageType, String filter) { - return getAll(new SimpleSQLiteQuery("SELECT \n" + - "*, \n" + - "teachers.teacherName || ' ' || teachers.teacherSurname AS senderFullName\n" + - "FROM messages \n" + - "LEFT JOIN teachers ON teachers.profileId = "+profileId+" AND teacherId = senderId\n" + - "LEFT JOIN metadata ON messageId = thingId AND thingType = "+TYPE_MESSAGE+" AND metadata.profileId = "+profileId+"\n" + - "WHERE messages.profileId = "+profileId+" AND messageType = "+messageType+" AND "+filter+"\n" + - "ORDER BY addedDate DESC")); - } - - public LiveData> getWithMetadata(int profileId, int messageType, String filter) { - return getAll(new SimpleSQLiteQuery("SELECT \n" + - "* \n" + - "FROM messages \n" + - "LEFT JOIN metadata ON messageId = thingId AND thingType = "+TYPE_MESSAGE+" AND metadata.profileId = "+profileId+"\n" + - "WHERE messages.profileId = "+profileId+" AND messageType = "+messageType+" AND "+filter+"\n" + - "ORDER BY addedDate DESC")); - } - - @Nullable - public MessageFull getById(int profileId, long messageId) { - return getOneNow(new SimpleSQLiteQuery("SELECT \n" + - "*, \n" + - "teachers.teacherName || ' ' || teachers.teacherSurname AS senderFullName\n" + - "FROM messages \n" + - "LEFT JOIN teachers ON teachers.profileId = "+profileId+" AND teacherId = senderId\n" + - "LEFT JOIN metadata ON messageId = thingId AND thingType = "+TYPE_MESSAGE+" AND metadata.profileId = "+profileId+"\n" + - "WHERE messages.profileId = "+profileId+" AND messageId = "+messageId+"\n" + - "ORDER BY addedDate DESC")); - } - - public LiveData> getReceived(int profileId) { - return getWithMetadataAndSenderName(profileId, TYPE_RECEIVED, "1"); - } - public LiveData> getDeleted(int profileId) { - return getWithMetadataAndSenderName(profileId, TYPE_DELETED, "1"); - } - public LiveData> getSent(int profileId) { - return getWithMetadata(profileId, TYPE_SENT, "1"); - } - - public List getReceivedNow(int profileId, String filter) { - return getNow(new SimpleSQLiteQuery("SELECT \n" + - "*, \n" + - "teachers.teacherName || ' ' || teachers.teacherSurname AS senderFullName\n" + - "FROM messages \n" + - "LEFT JOIN teachers ON teachers.profileId = "+profileId+" AND teacherId = senderId\n" + - "LEFT JOIN metadata ON messageId = thingId AND thingType = "+TYPE_MESSAGE+" AND metadata.profileId = "+profileId+"\n" + - "WHERE messages.profileId = "+profileId+" AND messageType = 0 AND "+filter+"\n" + - "ORDER BY addedDate DESC")); - } - public List getReceivedNotNotifiedNow(int profileId) { - return getReceivedNow(profileId, "notified = 0"); - } - - @Query("SELECT " + - "*, " + - "teachers.teacherName || ' ' || teachers.teacherSurname AS senderFullName " + - "FROM messages " + - "LEFT JOIN teachers ON teachers.profileId = messages.profileId AND teacherId = senderId " + - "LEFT JOIN metadata ON messageId = thingId AND thingType = "+TYPE_MESSAGE+" AND metadata.profileId = messages.profileId " + - "WHERE messageType = 0 AND notified = 0 " + - "ORDER BY addedDate DESC") - public abstract List getReceivedNotNotifiedNow(); -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/MessageDao.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/MessageDao.kt new file mode 100644 index 00000000..af4e608e --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/MessageDao.kt @@ -0,0 +1,78 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-25. + */ +package pl.szczodrzynski.edziennik.data.db.dao + +import androidx.lifecycle.LiveData +import androidx.room.Dao +import androidx.room.Query +import androidx.room.RawQuery +import androidx.sqlite.db.SupportSQLiteQuery +import eu.szkolny.selectivedao.annotation.SelectiveDao +import eu.szkolny.selectivedao.annotation.UpdateSelective +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.db.AppDb +import pl.szczodrzynski.edziennik.data.db.entity.Message +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.full.MessageFull + +@Dao +@SelectiveDao(db = AppDb::class) +abstract class MessageDao : BaseDao { + companion object { + private const val QUERY = """ + SELECT + *, + teachers.teacherName ||" "|| teachers.teacherSurname AS senderName + FROM messages + LEFT JOIN teachers ON teachers.profileId = messages.profileId AND teacherId = senderId + LEFT JOIN metadata ON messageId = thingId AND thingType = ${Metadata.TYPE_MESSAGE} AND metadata.profileId = messages.profileId + """ + + private const val ORDER_BY = """ORDER BY messageIsPinned DESC, addedDate DESC""" + } + + private val selective by lazy { MessageDaoSelective(App.db) } + + @RawQuery(observedEntities = [Message::class]) + abstract override fun getRaw(query: SupportSQLiteQuery): LiveData> + @RawQuery(observedEntities = [Message::class]) + abstract override fun getOne(query: SupportSQLiteQuery): LiveData + + // SELECTIVE UPDATE + @UpdateSelective(primaryKeys = ["profileId", "messageId"], skippedColumns = ["messageType", "messageBody", "messageIsPinned", "attachmentIds", "attachmentNames", "attachmentSizes"]) + override fun update(item: Message) = selective.update(item) + override fun updateAll(items: List) = selective.updateAll(items) + + // CLEAR + @Query("DELETE FROM messages WHERE profileId = :profileId") + abstract override fun clear(profileId: Int) + // REMOVE NOT KEPT + @Query("DELETE FROM messages WHERE keep = 0") + abstract override fun removeNotKept() + + @Query("DELETE FROM messages WHERE profileId = :profileId AND messageId = :messageId") + abstract fun delete(profileId: Int, messageId: Long) + + // GET ALL - LIVE DATA + fun getAll(profileId: Int) = + getRaw("$QUERY WHERE messages.profileId = $profileId $ORDER_BY") + fun getAllByType(profileId: Int, type: Int) = + getRaw("$QUERY WHERE messages.profileId = $profileId AND messageType = $type $ORDER_BY") + fun getReceived(profileId: Int) = getAllByType(profileId, Message.TYPE_RECEIVED) + fun getSent(profileId: Int) = getAllByType(profileId, Message.TYPE_SENT) + fun getDeleted(profileId: Int) = getAllByType(profileId, Message.TYPE_DELETED) + fun getDraft(profileId: Int) = getAllByType(profileId, Message.TYPE_DRAFT) + + // GET ALL - NOW + fun getAllNow(profileId: Int) = + getRawNow("$QUERY WHERE messages.profileId = $profileId $ORDER_BY") + fun getNotNotifiedNow() = + getRawNow("$QUERY WHERE notified = 0 AND messageType = ${Message.TYPE_RECEIVED} $ORDER_BY") + + // GET ONE - NOW + fun getByIdNow(profileId: Int, id: Long) = + getOneNow("$QUERY WHERE messages.profileId = $profileId AND messageId = $id") + + +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/MessageRecipientDao.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/MessageRecipientDao.java index 20e6fe90..b33adbff 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/MessageRecipientDao.java +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/MessageRecipientDao.java @@ -4,8 +4,6 @@ package pl.szczodrzynski.edziennik.data.db.dao; -import java.util.List; - import androidx.room.Dao; import androidx.room.Insert; import androidx.room.OnConflictStrategy; @@ -14,6 +12,8 @@ import androidx.room.RawQuery; import androidx.sqlite.db.SimpleSQLiteQuery; import androidx.sqlite.db.SupportSQLiteQuery; +import java.util.List; + import pl.szczodrzynski.edziennik.data.db.entity.MessageRecipient; import pl.szczodrzynski.edziennik.data.db.full.MessageRecipientFull; @@ -22,6 +22,9 @@ public abstract class MessageRecipientDao { @Query("DELETE FROM messageRecipients WHERE profileId = :profileId") public abstract void clear(int profileId); + @Query("DELETE FROM messageRecipients WHERE profileId = :profileId AND messageId = :messageId") + public abstract void clearFor(int profileId, long messageId); + @Insert(onConflict = OnConflictStrategy.REPLACE) public abstract long add(MessageRecipient messageRecipient); diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/MetadataDao.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/MetadataDao.java index 845941de..ab694702 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/MetadataDao.java +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/MetadataDao.java @@ -4,6 +4,15 @@ package pl.szczodrzynski.edziennik.data.db.dao; +import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_ANNOUNCEMENT; +import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_ATTENDANCE; +import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_EVENT; +import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_GRADE; +import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_HOMEWORK; +import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_LESSON_CHANGE; +import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_MESSAGE; +import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_NOTICE; + import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Insert; @@ -23,15 +32,6 @@ import pl.szczodrzynski.edziennik.data.db.entity.Notice; import pl.szczodrzynski.edziennik.data.db.full.LessonFull; import pl.szczodrzynski.edziennik.utils.models.UnreadCounter; -import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_ANNOUNCEMENT; -import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_ATTENDANCE; -import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_EVENT; -import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_GRADE; -import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_HOMEWORK; -import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_LESSON_CHANGE; -import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_MESSAGE; -import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_NOTICE; - @Dao public abstract class MetadataDao { @Insert(onConflict = OnConflictStrategy.IGNORE) @@ -63,38 +63,38 @@ public abstract class MetadataDao { @Transaction public void setSeen(int profileId, Object o, boolean seen) { if (o instanceof Grade) { - if (add(new Metadata(profileId, TYPE_GRADE, ((Grade) o).getId(), seen, false, 0)) == -1) { + if (add(new Metadata(profileId, TYPE_GRADE, ((Grade) o).getId(), seen, false)) == -1) { updateSeen(profileId, TYPE_GRADE, ((Grade) o).getId(), seen); } } if (o instanceof Attendance) { - if (add(new Metadata(profileId, TYPE_ATTENDANCE, ((Attendance) o).id, seen, false, 0)) == -1) { - updateSeen(profileId, TYPE_ATTENDANCE, ((Attendance) o).id, seen); + if (add(new Metadata(profileId, TYPE_ATTENDANCE, ((Attendance) o).getId(), seen, false)) == -1) { + updateSeen(profileId, TYPE_ATTENDANCE, ((Attendance) o).getId(), seen); } } if (o instanceof Notice) { - if (add(new Metadata(profileId, TYPE_NOTICE, ((Notice) o).id, seen, false, 0)) == -1) { - updateSeen(profileId, TYPE_NOTICE, ((Notice) o).id, seen); + if (add(new Metadata(profileId, TYPE_NOTICE, ((Notice) o).getId(), seen, false)) == -1) { + updateSeen(profileId, TYPE_NOTICE, ((Notice) o).getId(), seen); } } if (o instanceof Event) { - if (add(new Metadata(profileId, ((Event) o).type == Event.TYPE_HOMEWORK ? TYPE_HOMEWORK : TYPE_EVENT, ((Event) o).id, seen, false, 0)) == -1) { - updateSeen(profileId, ((Event) o).type == Event.TYPE_HOMEWORK ? TYPE_HOMEWORK : TYPE_EVENT, ((Event) o).id, seen); + if (add(new Metadata(profileId, ((Event) o).isHomework() ? TYPE_HOMEWORK : TYPE_EVENT, ((Event) o).getId(), seen, false)) == -1) { + updateSeen(profileId, ((Event) o).isHomework() ? TYPE_HOMEWORK : TYPE_EVENT, ((Event) o).getId(), seen); } } if (o instanceof LessonFull) { - if (add(new Metadata(profileId, TYPE_LESSON_CHANGE, ((LessonFull) o).getId(), seen, false, 0)) == -1) { + if (add(new Metadata(profileId, TYPE_LESSON_CHANGE, ((LessonFull) o).getId(), seen, false)) == -1) { updateSeen(profileId, TYPE_LESSON_CHANGE, ((LessonFull) o).getId(), seen); } } if (o instanceof Announcement) { - if (add(new Metadata(profileId, TYPE_ANNOUNCEMENT, ((Announcement) o).id, seen, false, 0)) == -1) { - updateSeen(profileId, TYPE_ANNOUNCEMENT, ((Announcement) o).id, seen); + if (add(new Metadata(profileId, TYPE_ANNOUNCEMENT, ((Announcement) o).getId(), seen, false)) == -1) { + updateSeen(profileId, TYPE_ANNOUNCEMENT, ((Announcement) o).getId(), seen); } } if (o instanceof Message) { - if (add(new Metadata(profileId, TYPE_MESSAGE, ((Message) o).id, seen, false, 0)) == -1) { - updateSeen(profileId, TYPE_MESSAGE, ((Message) o).id, seen); + if (add(new Metadata(profileId, TYPE_MESSAGE, ((Message) o).getId(), seen, false)) == -1) { + updateSeen(profileId, TYPE_MESSAGE, ((Message) o).getId(), seen); } } } @@ -102,38 +102,38 @@ public abstract class MetadataDao { @Transaction public void setNotified(int profileId, Object o, boolean notified) { if (o instanceof Grade) { - if (add(new Metadata(profileId, TYPE_GRADE, ((Grade) o).getId(), false, notified, 0)) == -1) { + if (add(new Metadata(profileId, TYPE_GRADE, ((Grade) o).getId(), false, notified)) == -1) { updateNotified(profileId, TYPE_GRADE, ((Grade) o).getId(), notified); } } if (o instanceof Attendance) { - if (add(new Metadata(profileId, TYPE_ATTENDANCE, ((Attendance) o).id, false, notified, 0)) == -1) { - updateNotified(profileId, TYPE_ATTENDANCE, ((Attendance) o).id, notified); + if (add(new Metadata(profileId, TYPE_ATTENDANCE, ((Attendance) o).getId(), false, notified)) == -1) { + updateNotified(profileId, TYPE_ATTENDANCE, ((Attendance) o).getId(), notified); } } if (o instanceof Notice) { - if (add(new Metadata(profileId, TYPE_NOTICE, ((Notice) o).id, false, notified, 0)) == -1) { - updateNotified(profileId, TYPE_NOTICE, ((Notice) o).id, notified); + if (add(new Metadata(profileId, TYPE_NOTICE, ((Notice) o).getId(), false, notified)) == -1) { + updateNotified(profileId, TYPE_NOTICE, ((Notice) o).getId(), notified); } } if (o instanceof Event) { - if (add(new Metadata(profileId, ((Event) o).type == Event.TYPE_HOMEWORK ? TYPE_HOMEWORK : TYPE_EVENT, ((Event) o).id, false, notified, 0)) == -1) { - updateNotified(profileId, ((Event) o).type == Event.TYPE_HOMEWORK ? TYPE_HOMEWORK : TYPE_EVENT, ((Event) o).id, notified); + if (add(new Metadata(profileId, ((Event) o).isHomework() ? TYPE_HOMEWORK : TYPE_EVENT, ((Event) o).getId(), false, notified)) == -1) { + updateNotified(profileId, ((Event) o).isHomework() ? TYPE_HOMEWORK : TYPE_EVENT, ((Event) o).getId(), notified); } } if (o instanceof LessonFull) { - if (add(new Metadata(profileId, TYPE_LESSON_CHANGE, ((LessonFull) o).getId(), false, notified, 0)) == -1) { + if (add(new Metadata(profileId, TYPE_LESSON_CHANGE, ((LessonFull) o).getId(), false, notified)) == -1) { updateNotified(profileId, TYPE_LESSON_CHANGE, ((LessonFull) o).getId(), notified); } } if (o instanceof Announcement) { - if (add(new Metadata(profileId, TYPE_ANNOUNCEMENT, ((Announcement) o).id, false, notified, 0)) == -1) { - updateNotified(profileId, TYPE_ANNOUNCEMENT, ((Announcement) o).id, notified); + if (add(new Metadata(profileId, TYPE_ANNOUNCEMENT, ((Announcement) o).getId(), false, notified)) == -1) { + updateNotified(profileId, TYPE_ANNOUNCEMENT, ((Announcement) o).getId(), notified); } } if (o instanceof Message) { - if (add(new Metadata(profileId, TYPE_MESSAGE, ((Message) o).id, false, notified, 0)) == -1) { - updateNotified(profileId, TYPE_MESSAGE, ((Message) o).id, notified); + if (add(new Metadata(profileId, TYPE_MESSAGE, ((Message) o).getId(), false, notified)) == -1) { + updateNotified(profileId, TYPE_MESSAGE, ((Message) o).getId(), notified); } } } @@ -141,9 +141,9 @@ public abstract class MetadataDao { @Transaction public void setBoth(int profileId, Event o, boolean seen, boolean notified, long addedDate) { if (o != null) { - if (add(new Metadata(profileId, o.type == Event.TYPE_HOMEWORK ? TYPE_HOMEWORK : TYPE_EVENT, o.id, seen, notified, addedDate)) == -1) { - updateSeen(profileId, o.type == Event.TYPE_HOMEWORK ? TYPE_HOMEWORK : TYPE_EVENT, o.id, seen); - updateNotified(profileId, o.type == Event.TYPE_HOMEWORK ? TYPE_HOMEWORK : TYPE_EVENT, o.id, notified); + if (add(new Metadata(profileId, o.isHomework() ? TYPE_HOMEWORK : TYPE_EVENT, o.getId(), seen, notified)) == -1) { + updateSeen(profileId, o.isHomework() ? TYPE_HOMEWORK : TYPE_EVENT, o.getId(), seen); + updateNotified(profileId, o.isHomework() ? TYPE_HOMEWORK : TYPE_EVENT, o.getId(), notified); } } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/NoteDao.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/NoteDao.kt new file mode 100644 index 00000000..4ad421bc --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/NoteDao.kt @@ -0,0 +1,43 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-23. + */ + +package pl.szczodrzynski.edziennik.data.db.dao + +import androidx.lifecycle.LiveData +import androidx.room.* +import pl.szczodrzynski.edziennik.data.db.entity.Note + +@Dao +interface NoteDao { + companion object { + private const val ORDER_BY = "ORDER BY addedDate DESC" + } + + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun add(note: Note) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun addAll(noteList: List) + + @Delete + fun delete(note: Note) + + @Query("DELETE FROM notes WHERE profileId = :profileId AND noteId = :noteId") + fun remove(profileId: Int, noteId: Long) + + @Query("SELECT * FROM notes WHERE profileId = :profileId AND noteId = :noteId $ORDER_BY") + fun get(profileId: Int, noteId: Long): LiveData + + @Query("SELECT * FROM notes WHERE profileId = :profileId AND noteId = :noteId $ORDER_BY") + fun getNow(profileId: Int, noteId: Long): Note? + + @Query("SELECT * FROM notes WHERE profileId = :profileId $ORDER_BY") + fun getAll(profileId: Int): LiveData> + + @Query("SELECT * FROM notes WHERE profileId = :profileId AND noteOwnerType = :ownerType AND noteOwnerId = :ownerId $ORDER_BY") + fun getAllFor(profileId: Int, ownerType: Note.OwnerType, ownerId: Long): LiveData> + + @Query("SELECT * FROM notes WHERE profileId = :profileId AND noteOwnerType IS NULL $ORDER_BY") + fun getAllNoOwner(profileId: Int): LiveData> +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/NoticeDao.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/NoticeDao.java deleted file mode 100644 index 110544e4..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/NoticeDao.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.dao; - -import androidx.lifecycle.LiveData; -import androidx.room.Dao; -import androidx.room.Insert; -import androidx.room.OnConflictStrategy; -import androidx.room.Query; -import androidx.room.RawQuery; -import androidx.sqlite.db.SimpleSQLiteQuery; -import androidx.sqlite.db.SupportSQLiteQuery; - -import java.util.List; - -import pl.szczodrzynski.edziennik.data.db.entity.Metadata; -import pl.szczodrzynski.edziennik.data.db.entity.Notice; -import pl.szczodrzynski.edziennik.data.db.full.NoticeFull; - -import static pl.szczodrzynski.edziennik.data.db.entity.Metadata.TYPE_NOTICE; - -@Dao -public abstract class NoticeDao { - @Insert(onConflict = OnConflictStrategy.REPLACE) - public abstract long add(Notice notice); - - @Insert(onConflict = OnConflictStrategy.REPLACE) - public abstract void addAll(List noticeList); - - @Query("DELETE FROM notices WHERE profileId = :profileId") - public abstract void clear(int profileId); - - @Query("DELETE FROM notices WHERE profileId = :profileId AND noticeSemester = :semester") - public abstract void clearForSemester(int profileId, int semester); - - @RawQuery(observedEntities = {Notice.class}) - abstract LiveData> getAll(SupportSQLiteQuery query); - public LiveData> getAll(int profileId, String filter) { - return getAll(new SimpleSQLiteQuery("SELECT \n" + - "*, \n" + - "teachers.teacherName || ' ' || teachers.teacherSurname AS teacherFullName\n" + - "FROM notices \n" + - "LEFT JOIN teachers USING(profileId, teacherId)\n" + - "LEFT JOIN metadata ON noticeId = thingId AND thingType = "+TYPE_NOTICE+" AND metadata.profileId = "+profileId+"\n" + - "WHERE notices.profileId = "+profileId+" AND "+filter+"\n" + - "ORDER BY addedDate DESC")); - } - public LiveData> getAll(int profileId) { - return getAll(profileId, "1"); - } - public LiveData> getAllWhere(int profileId, String filter) { - return getAll(profileId, filter); - } - - @RawQuery(observedEntities = {Notice.class, Metadata.class}) - abstract List getAllNow(SupportSQLiteQuery query); - public List getAllNow(int profileId, String filter) { - return getAllNow(new SimpleSQLiteQuery("SELECT \n" + - "*, \n" + - "teachers.teacherName || ' ' || teachers.teacherSurname AS teacherFullName\n" + - "FROM notices \n" + - "LEFT JOIN teachers USING(profileId, teacherId)\n" + - "LEFT JOIN metadata ON noticeId = thingId AND thingType = "+TYPE_NOTICE+" AND metadata.profileId = "+profileId+"\n" + - "WHERE notices.profileId = "+profileId+" AND "+filter+"\n" + - "ORDER BY addedDate DESC")); - } - public List getNotNotifiedNow(int profileId) { - return getAllNow(profileId, "notified = 0"); - } - - @Query("SELECT " + - "*, " + - "teachers.teacherName || ' ' || teachers.teacherSurname AS teacherFullName " + - "FROM notices " + - "LEFT JOIN teachers USING(profileId, teacherId) " + - "LEFT JOIN metadata ON noticeId = thingId AND thingType = "+TYPE_NOTICE+" AND metadata.profileId = notices.profileId " + - "WHERE notified = 0 " + - "ORDER BY addedDate DESC") - public abstract List getNotNotifiedNow(); -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/NoticeDao.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/NoticeDao.kt new file mode 100644 index 00000000..51f3e839 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/NoticeDao.kt @@ -0,0 +1,72 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-25. + */ +package pl.szczodrzynski.edziennik.data.db.dao + +import androidx.lifecycle.LiveData +import androidx.room.Dao +import androidx.room.Query +import androidx.room.RawQuery +import androidx.sqlite.db.SupportSQLiteQuery +import eu.szkolny.selectivedao.annotation.SelectiveDao +import eu.szkolny.selectivedao.annotation.UpdateSelective +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.db.AppDb +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.Notice +import pl.szczodrzynski.edziennik.data.db.full.NoticeFull + +@Dao +@SelectiveDao(db = AppDb::class) +abstract class NoticeDao : BaseDao { + companion object { + private const val QUERY = """ + SELECT + *, + teachers.teacherName ||" "|| teachers.teacherSurname AS teacherName + FROM notices + LEFT JOIN teachers USING(profileId, teacherId) + LEFT JOIN metadata ON noticeId = thingId AND thingType = ${Metadata.TYPE_NOTICE} AND metadata.profileId = notices.profileId + """ + + private const val ORDER_BY = """ORDER BY addedDate DESC""" + } + + private val selective by lazy { NoticeDaoSelective(App.db) } + + @RawQuery(observedEntities = [Notice::class]) + abstract override fun getRaw(query: SupportSQLiteQuery): LiveData> + @RawQuery(observedEntities = [Notice::class]) + abstract override fun getOne(query: SupportSQLiteQuery): LiveData + + // SELECTIVE UPDATE + @UpdateSelective(primaryKeys = ["profileId", "noticeId"], skippedColumns = ["addedDate"]) + override fun update(item: Notice) = selective.update(item) + override fun updateAll(items: List) = selective.updateAll(items) + + // CLEAR + @Query("DELETE FROM notices WHERE profileId = :profileId") + abstract override fun clear(profileId: Int) + // REMOVE NOT KEPT + @Query("DELETE FROM notices WHERE keep = 0") + abstract override fun removeNotKept() + + // GET ALL - LIVE DATA + fun getAll(profileId: Int) = + getRaw("$QUERY WHERE notices.profileId = $profileId $ORDER_BY") + + // GET ALL - NOW + fun getAllNow(profileId: Int) = + getRawNow("$QUERY WHERE notices.profileId = $profileId $ORDER_BY") + fun getNotNotifiedNow() = + getRawNow("$QUERY WHERE notified = 0 $ORDER_BY") + fun getNotNotifiedNow(profileId: Int) = + getRawNow("$QUERY WHERE notices.profileId = $profileId AND notified = 0 $ORDER_BY") + + // GET ONE - NOW + fun getByIdNow(profileId: Int, id: Long) = + getOneNow("$QUERY WHERE notices.profileId = $profileId AND noticeId = $id") + + @Query("UPDATE notices SET keep = 0 WHERE profileId = :profileId AND noticeSemester = :semester") + abstract fun dontKeepSemester(profileId: Int, semester: Int) +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/ProfileDao.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/ProfileDao.kt index 3225141e..6d1e799d 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/ProfileDao.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/ProfileDao.kt @@ -60,4 +60,10 @@ interface ProfileDao { @Query("UPDATE profiles SET empty = 0") fun setAllNotEmpty() + + @Query("SELECT * FROM profiles WHERE archiveId = :archiveId AND archived = 1") + fun getArchivesOf(archiveId: Int): List + + @Query("SELECT * FROM profiles WHERE archiveId = :archiveId AND archived = 0 ORDER BY profileId DESC LIMIT 1") + fun getNotArchivedOf(archiveId: Int): Profile? } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/TeacherAbsenceDao.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/TeacherAbsenceDao.kt index 3da88080..f12248b8 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/TeacherAbsenceDao.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/TeacherAbsenceDao.kt @@ -1,54 +1,74 @@ /* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 + * Copyright (c) Kuba Szczodrzyński 2020-4-25. */ - package pl.szczodrzynski.edziennik.data.db.dao import androidx.lifecycle.LiveData import androidx.room.Dao -import androidx.room.Insert -import androidx.room.OnConflictStrategy import androidx.room.Query +import androidx.room.RawQuery +import androidx.sqlite.db.SupportSQLiteQuery +import eu.szkolny.selectivedao.annotation.SelectiveDao +import eu.szkolny.selectivedao.annotation.UpdateSelective +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.db.AppDb import pl.szczodrzynski.edziennik.data.db.entity.Metadata import pl.szczodrzynski.edziennik.data.db.entity.TeacherAbsence import pl.szczodrzynski.edziennik.data.db.full.TeacherAbsenceFull import pl.szczodrzynski.edziennik.utils.models.Date @Dao -interface TeacherAbsenceDao { +@SelectiveDao(db = AppDb::class) +abstract class TeacherAbsenceDao : BaseDao { + companion object { + private const val QUERY = """ + SELECT + *, + teachers.teacherName ||" "|| teachers.teacherSurname AS teacherName + FROM teacherAbsence + LEFT JOIN teachers USING(profileId, teacherId) + LEFT JOIN metadata ON teacherAbsenceId = thingId AND thingType = ${Metadata.TYPE_TEACHER_ABSENCE} AND metadata.profileId = teacherAbsence.profileId + """ - @Insert(onConflict = OnConflictStrategy.REPLACE) - fun add(teacherAbsence: TeacherAbsence) + private const val ORDER_BY = """ORDER BY teacherAbsenceDateFrom ASC""" + } - @Insert(onConflict = OnConflictStrategy.REPLACE) - fun addAll(teacherAbsenceList: List) + private val selective by lazy { TeacherAbsenceDaoSelective(App.db) } - @Query("SELECT * FROM teacherAbsence WHERE profileId = :profileId") - fun getAll(profileId: Int): List + @RawQuery(observedEntities = [TeacherAbsence::class]) + abstract override fun getRaw(query: SupportSQLiteQuery): LiveData> + @RawQuery(observedEntities = [TeacherAbsence::class]) + abstract override fun getOne(query: SupportSQLiteQuery): LiveData - @Query("SELECT *, teachers.teacherName || ' ' || teachers.teacherSurname as teacherFullName, " + - "metadata.seen, metadata.notified, metadata.addedDate FROM teacherAbsence " + - "LEFT JOIN teachers USING (profileId, teacherId) " + - "LEFT JOIN metadata ON teacherAbsenceId = thingId AND metadata.thingType = " + Metadata.TYPE_TEACHER_ABSENCE + - " AND metadata.profileId = :profileId WHERE teachers.profileId = :profileId") - fun getAllFullNow(profileId: Int): List - - @Query("SELECT *, teachers.teacherName || ' ' || teachers.teacherSurname as teacherFullName, " + - "metadata.seen, metadata.notified, metadata.addedDate FROM teacherAbsence " + - "LEFT JOIN teachers USING (profileId, teacherId) " + - "LEFT JOIN metadata ON teacherAbsenceId = thingId AND metadata.thingType = " + Metadata.TYPE_TEACHER_ABSENCE + - " AND metadata.profileId = :profileId WHERE teachers.profileId = :profileId " + - "AND :date BETWEEN teacherAbsenceDateFrom AND teacherAbsenceDateTo") - fun getAllByDateFull(profileId: Int, date: Date): LiveData> - - @Query("SELECT *, teachers.teacherName || ' ' || teachers.teacherSurname as teacherFullName, " + - "metadata.seen, metadata.notified, metadata.addedDate FROM teacherAbsence " + - "LEFT JOIN teachers USING (profileId, teacherId) " + - "LEFT JOIN metadata ON teacherAbsenceId = thingId AND metadata.thingType = " + Metadata.TYPE_TEACHER_ABSENCE + - " AND metadata.profileId = :profileId WHERE teachers.profileId = :profileId " + - "AND :date BETWEEN teacherAbsenceDateFrom AND teacherAbsenceDateTo") - fun getAllByDateNow(profileId: Int, date: Date): List + // SELECTIVE UPDATE + @UpdateSelective(primaryKeys = ["profileId", "teacherAbsenceId"], skippedColumns = ["addedDate"]) + override fun update(item: TeacherAbsence) = selective.update(item) + override fun updateAll(items: List) = selective.updateAll(items) + // CLEAR @Query("DELETE FROM teacherAbsence WHERE profileId = :profileId") - fun clear(profileId: Int) + abstract override fun clear(profileId: Int) + // REMOVE NOT KEPT + @Query("DELETE FROM teacherAbsence WHERE keep = 0") + abstract override fun removeNotKept() + + // GET ALL - LIVE DATA + fun getAll(profileId: Int) = + getRaw("$QUERY WHERE teacherAbsence.profileId = $profileId $ORDER_BY") + fun getAllByDate(profileId: Int, date: Date) = + getRaw("$QUERY WHERE teacherAbsence.profileId = $profileId AND '${date.stringY_m_d}' BETWEEN teacherAbsenceDateFrom AND teacherAbsenceDateTo $ORDER_BY") + + // GET ALL - NOW + fun getAllNow(profileId: Int) = + getRawNow("$QUERY WHERE teacherAbsence.profileId = $profileId $ORDER_BY") + fun getNotNotifiedNow() = + getRawNow("$QUERY WHERE notified = 0 $ORDER_BY") + fun getNotNotifiedNow(profileId: Int) = + getRawNow("$QUERY WHERE teacherAbsence.profileId = $profileId AND notified = 0 $ORDER_BY") + fun getAllByDateNow(profileId: Int, date: Date) = + getRawNow("$QUERY WHERE teacherAbsence.profileId = $profileId AND '${date.stringY_m_d}' BETWEEN teacherAbsenceDateFrom AND teacherAbsenceDateTo $ORDER_BY") + + // GET ONE - NOW + fun getByIdNow(profileId: Int, id: Long) = + getOneNow("$QUERY WHERE teacherAbsence.profileId = $profileId AND teacherAbsenceId = $id") } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/TeacherDao.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/TeacherDao.kt index d886cd2d..27b9b869 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/TeacherDao.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/TeacherDao.kt @@ -1,10 +1,8 @@ package pl.szczodrzynski.edziennik.data.db.dao import androidx.lifecycle.LiveData -import androidx.room.Dao -import androidx.room.Insert -import androidx.room.OnConflictStrategy -import androidx.room.Query +import androidx.room.* +import androidx.sqlite.db.SupportSQLiteQuery import pl.szczodrzynski.edziennik.data.db.entity.Teacher @Dao @@ -18,6 +16,9 @@ interface TeacherDao { @Insert(onConflict = OnConflictStrategy.IGNORE) fun addAllIgnore(teacherList: List) + @RawQuery + fun query(query: SupportSQLiteQuery): Int + @Query("DELETE FROM teachers WHERE profileId = :profileId") fun clear(profileId: Int) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/TimetableDao.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/TimetableDao.kt index 9ac9709b..4201a51d 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/TimetableDao.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/dao/TimetableDao.kt @@ -1,20 +1,25 @@ /* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 + * Copyright (c) Kuba Szczodrzyński 2020-4-25. */ - package pl.szczodrzynski.edziennik.data.db.dao import androidx.lifecycle.LiveData -import androidx.room.* -import androidx.sqlite.db.SimpleSQLiteQuery +import androidx.room.Dao +import androidx.room.Query +import androidx.room.RawQuery import androidx.sqlite.db.SupportSQLiteQuery +import eu.szkolny.selectivedao.annotation.SelectiveDao +import eu.szkolny.selectivedao.annotation.UpdateSelective +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.data.db.AppDb import pl.szczodrzynski.edziennik.data.db.entity.Lesson import pl.szczodrzynski.edziennik.data.db.entity.Metadata import pl.szczodrzynski.edziennik.data.db.full.LessonFull import pl.szczodrzynski.edziennik.utils.models.Date @Dao -interface TimetableDao { +@SelectiveDao(db = AppDb::class) +abstract class TimetableDao : BaseDao { companion object { private const val QUERY = """ SELECT @@ -25,7 +30,7 @@ interface TimetableDao { oldS.subjectLongName AS oldSubjectName, oldT.teacherName ||" "|| oldT.teacherSurname AS oldTeacherName, oldG.teamName AS oldTeamName, - metadata.seen, metadata.notified, metadata.addedDate + metadata.seen, metadata.notified FROM timetable LEFT JOIN subjects USING(profileId, subjectId) LEFT JOIN teachers USING(profileId, teacherId) @@ -35,111 +40,79 @@ interface TimetableDao { LEFT JOIN teams AS oldG ON timetable.profileId = oldG.profileId AND timetable.oldTeamId = oldG.teamId LEFT JOIN metadata ON id = thingId AND thingType = ${Metadata.TYPE_LESSON_CHANGE} AND metadata.profileId = timetable.profileId """ + + private const val ORDER_BY = """ORDER BY profileId, id, type""" + private const val IS_CHANGED = """type != -1 AND type != 0""" } - @Insert(onConflict = OnConflictStrategy.REPLACE) - operator fun plusAssign(lessonList: List) - - @Query("DELETE FROM timetable WHERE profileId = :profileId") - fun clear(profileId: Int) - - @Query("DELETE FROM timetable WHERE profileId = :profileId AND type != -1 AND ((type != 3 AND date >= :dateFrom) OR ((type = 3 OR type = 1) AND oldDate >= :dateFrom))") - fun clearFromDate(profileId: Int, dateFrom: Date) - - @Query("DELETE FROM timetable WHERE profileId = :profileId AND type != -1 AND ((type != 3 AND date <= :dateTo) OR ((type = 3 OR type = 1) AND oldDate <= :dateTo))") - fun clearToDate(profileId: Int, dateTo: Date) - - @Query("DELETE FROM timetable WHERE profileId = :profileId AND type != -1 AND ((type != 3 AND date >= :dateFrom AND date <= :dateTo) OR ((type = 3 OR type = 1) AND oldDate >= :dateFrom AND oldDate <= :dateTo))") - fun clearBetweenDates(profileId: Int, dateFrom: Date, dateTo: Date) + private val selective by lazy { TimetableDaoSelective(App.db) } @RawQuery(observedEntities = [Lesson::class]) - fun getRaw(query: SupportSQLiteQuery): LiveData> + abstract override fun getRaw(query: SupportSQLiteQuery): LiveData> + @RawQuery(observedEntities = [Lesson::class]) + abstract override fun getOne(query: SupportSQLiteQuery): LiveData - @Query(""" - $QUERY - WHERE timetable.profileId = :profileId AND type != -1 AND type != 0 - ORDER BY id, type - """) - fun getAllChangesNow(profileId: Int): List + // SELECTIVE UPDATE + @UpdateSelective(primaryKeys = ["profileId", "id"], skippedColumns = ["addedDate"]) + override fun update(item: Lesson) = selective.update(item) + override fun updateAll(items: List) = selective.updateAll(items) - @Query(""" - $QUERY - WHERE timetable.profileId = :profileId AND type != -1 AND type != 0 AND ((type != 3 AND date = :date) OR ((type = 3 OR type = 1) AND oldDate = :date)) - ORDER BY id, type - """) - fun getChangesForDateNow(profileId: Int, date: Date): List + // CLEAR + @Query("DELETE FROM timetable WHERE profileId = :profileId") + abstract override fun clear(profileId: Int) + // REMOVE NOT KEPT + @Query("DELETE FROM timetable WHERE keep = 0") + abstract override fun removeNotKept() - fun getForDate(profileId: Int, date: Date) = getRaw(SimpleSQLiteQuery(""" - $QUERY - WHERE timetable.profileId = $profileId AND ((type != 3 AND date = "${date.stringY_m_d}") OR ((type = 3 OR type = 1) AND oldDate = "${date.stringY_m_d}")) - ORDER BY id, type - """)) + // GET ALL - LIVE DATA + fun getAll(profileId: Int) = + getRaw("$QUERY WHERE timetable.profileId = $profileId $ORDER_BY") + fun getAllForDate(profileId: Int, date: Date) = + getRaw("$QUERY WHERE timetable.profileId = $profileId AND ((type != 3 AND date = '${date.stringY_m_d}') OR ((type = 3 OR type = 1) AND oldDate = '${date.stringY_m_d}')) $ORDER_BY") + fun getNextWithSubject(profileId: Int, date: Date, subjectId: Long) = + getOne("$QUERY " + + "WHERE timetable.profileId = $profileId " + + "AND ((type != 3 AND date > '${date.stringY_m_d}') OR ((type = 3 OR type = 1) AND oldDate > '${date.stringY_m_d}')) " + + "AND timetable.subjectId = $subjectId " + + "LIMIT 1") + fun getNextWithSubjectAndTeam(profileId: Int, date: Date, subjectId: Long, teamId: Long) = + getOne("$QUERY " + + "WHERE timetable.profileId = $profileId " + + "AND ((type != 3 AND date > '${date.stringY_m_d}') OR ((type = 3 OR type = 1) AND oldDate > '${date.stringY_m_d}')) " + + "AND timetable.subjectId = $subjectId " + + "AND timetable.teamId = $teamId " + + "LIMIT 1") + fun getBetweenDates(dateFrom: Date, dateTo: Date) = + getRaw("$QUERY WHERE (type != 3 AND date >= '${dateFrom.stringY_m_d}' AND date <= '${dateTo.stringY_m_d}') OR ((type = 3 OR type = 1) AND oldDate >= '${dateFrom.stringY_m_d}' AND oldDate <= '${dateTo.stringY_m_d}') $ORDER_BY") + fun getChanges(profileId: Int) = + getRaw("$QUERY WHERE timetable.profileId = $profileId AND $IS_CHANGED $ORDER_BY") - @Query(""" - $QUERY - WHERE timetable.profileId = :profileId AND ((type != 3 AND date = :date) OR ((type = 3 OR type = 1) AND oldDate = :date)) - ORDER BY id, type - """) - fun getForDateNow(profileId: Int, date: Date): List + // GET ALL - NOW + fun getAllNow(profileId: Int) = + getRawNow("$QUERY WHERE timetable.profileId = $profileId $ORDER_BY") + fun getNotNotifiedNow() = + getRawNow("$QUERY WHERE notified = 0 AND timetable.type NOT IN (${Lesson.TYPE_NORMAL}, ${Lesson.TYPE_NO_LESSONS}, ${Lesson.TYPE_SHIFTED_SOURCE}) $ORDER_BY") + fun getNotNotifiedNow(profileId: Int) = + getRawNow("$QUERY WHERE timetable.profileId = $profileId AND notified = 0 AND timetable.type NOT IN (${Lesson.TYPE_NORMAL}, ${Lesson.TYPE_NO_LESSONS}, ${Lesson.TYPE_SHIFTED_SOURCE}) $ORDER_BY") + fun getAllForDateNow(profileId: Int, date: Date) = + getRawNow("$QUERY WHERE timetable.profileId = $profileId AND ((type != 3 AND date = '${date.stringY_m_d}') OR ((type = 3 OR type = 1) AND oldDate = '${date.stringY_m_d}')) $ORDER_BY") + fun getChangesNow(profileId: Int) = + getRawNow("$QUERY WHERE timetable.profileId = $profileId AND $IS_CHANGED $ORDER_BY") + fun getChangesForDateNow(profileId: Int, date: Date) = + getRawNow("$QUERY WHERE timetable.profileId = $profileId AND $IS_CHANGED AND ((type != 3 AND date = '${date.stringY_m_d}') OR ((type = 3 OR type = 1) AND oldDate = '${date.stringY_m_d}')) $ORDER_BY") + fun getBetweenDatesNow(dateFrom: Date, dateTo: Date) = + getRawNow("$QUERY WHERE (type != 3 AND date >= '${dateFrom.stringY_m_d}' AND date <= '${dateTo.stringY_m_d}') OR ((type = 3 OR type = 1) AND oldDate >= '${dateFrom.stringY_m_d}' AND oldDate <= '${dateTo.stringY_m_d}') $ORDER_BY") - @Query(""" - $QUERY - WHERE timetable.profileId = :profileId AND ((type != 3 AND date > :today) OR ((type = 3 OR type = 1) AND oldDate > :today)) AND timetable.subjectId = :subjectId - ORDER BY id, type - LIMIT 1 - """) - fun getNextWithSubject(profileId: Int, today: Date, subjectId: Long): LiveData + // GET ONE - NOW + fun getByIdNow(profileId: Int, id: Long) = + getOneNow("$QUERY WHERE timetable.profileId = $profileId AND timetable.id = $id") - @Query(""" - $QUERY - WHERE timetable.profileId = :profileId AND ((type != 3 AND date > :today) OR ((type = 3 OR type = 1) AND oldDate > :today)) AND timetable.subjectId = :subjectId AND timetable.teamId = :teamId - ORDER BY id, type - LIMIT 1 - """) - fun getNextWithSubjectAndTeam(profileId: Int, today: Date, subjectId: Long, teamId: Long): LiveData + @Query("UPDATE timetable SET keep = 0 WHERE profileId = :profileId AND isExtra = :isExtra AND type != -1 AND ((type != 3 AND date >= :dateFrom) OR ((type = 3 OR type = 1) AND oldDate >= :dateFrom))") + abstract fun dontKeepFromDate(profileId: Int, dateFrom: Date, isExtra: Boolean) - @Query(""" - $QUERY - WHERE (type != 3 AND date >= :dateFrom AND date <= :dateTo) OR ((type = 3 OR type = 1) AND oldDate >= :dateFrom AND oldDate <= :dateTo) - ORDER BY profileId, id, type - """) - fun getBetweenDatesNow(dateFrom: Date, dateTo: Date): List + @Query("UPDATE timetable SET keep = 0 WHERE profileId = :profileId AND isExtra = :isExtra AND type != -1 AND ((type != 3 AND date <= :dateTo) OR ((type = 3 OR type = 1) AND oldDate <= :dateTo))") + abstract fun dontKeepToDate(profileId: Int, dateTo: Date, isExtra: Boolean) - @Query(""" - $QUERY - WHERE (type != 3 AND date >= :dateFrom AND date <= :dateTo) OR ((type = 3 OR type = 1) AND oldDate >= :dateFrom AND oldDate <= :dateTo) - ORDER BY profileId, id, type - """) - fun getBetweenDates(dateFrom: Date, dateTo: Date): LiveData> - - @Query(""" - $QUERY - WHERE timetable.profileId = :profileId AND timetable.id = :lessonId - ORDER BY id, type - """) - fun getByIdNow(profileId: Int, lessonId: Long): LessonFull? - - @Query(""" - $QUERY - WHERE timetable.profileId = :profileId AND timetable.type NOT IN (${Lesson.TYPE_NORMAL}, ${Lesson.TYPE_NO_LESSONS}, ${Lesson.TYPE_SHIFTED_SOURCE}) AND metadata.notified = 0 - """) - fun getNotNotifiedNow(profileId: Int): List - - @Query(""" - SELECT - timetable.*, - subjects.subjectLongName AS subjectName, - teachers.teacherName ||" "|| teachers.teacherSurname AS teacherName, - oldS.subjectLongName AS oldSubjectName, - oldT.teacherName ||" "|| oldT.teacherSurname AS oldTeacherName, - metadata.seen, metadata.notified, metadata.addedDate - FROM timetable - LEFT JOIN subjects USING(profileId, subjectId) - LEFT JOIN teachers USING(profileId, teacherId) - LEFT JOIN subjects AS oldS ON timetable.profileId = oldS.profileId AND timetable.oldSubjectId = oldS.subjectId - LEFT JOIN teachers AS oldT ON timetable.profileId = oldT.profileId AND timetable.oldTeacherId = oldT.teacherId - LEFT JOIN metadata ON id = thingId AND thingType = ${Metadata.TYPE_LESSON_CHANGE} AND metadata.profileId = timetable.profileId - WHERE timetable.type NOT IN (${Lesson.TYPE_NORMAL}, ${Lesson.TYPE_NO_LESSONS}, ${Lesson.TYPE_SHIFTED_SOURCE}) AND metadata.notified = 0 - """) - fun getNotNotifiedNow(): List + @Query("UPDATE timetable SET keep = 0 WHERE profileId = :profileId AND isExtra = :isExtra AND type != -1 AND ((type != 3 AND date >= :dateFrom AND date <= :dateTo) OR ((type = 3 OR type = 1) AND oldDate >= :dateFrom AND oldDate <= :dateTo))") + abstract fun dontKeepBetweenDates(profileId: Int, dateFrom: Date, dateTo: Date, isExtra: Boolean) } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Announcement.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Announcement.java deleted file mode 100644 index af17e0c3..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Announcement.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.entity; - -import androidx.annotation.Nullable; -import androidx.room.ColumnInfo; -import androidx.room.Entity; -import androidx.room.Ignore; -import androidx.room.Index; - -import pl.szczodrzynski.edziennik.utils.models.Date; - -@Entity(tableName = "announcements", - primaryKeys = {"profileId", "announcementId"}, - indices = {@Index(value = {"profileId"})}) -public class Announcement { - public int profileId; - - @ColumnInfo(name = "announcementId") - public long id; - - @ColumnInfo(name = "announcementSubject") - public String subject; - @Nullable - @ColumnInfo(name = "announcementText") - public String text; - @Nullable - @ColumnInfo(name = "announcementStartDate") - public Date startDate; - @Nullable - @ColumnInfo(name = "announcementEndDate") - public Date endDate; - - public long teacherId; - - @Nullable - @ColumnInfo(name = "announcementIdString") - public String idString; - - @Ignore - public Announcement() {} - - public Announcement(int profileId, long id, String subject, String text, @Nullable Date startDate, @Nullable Date endDate, long teacherId, @Nullable String idString) { - this.profileId = profileId; - this.id = id; - this.subject = subject; - this.text = text; - this.startDate = startDate; - this.endDate = endDate; - this.teacherId = teacherId; - this.idString = idString; - } -} - - - diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Announcement.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Announcement.kt new file mode 100644 index 00000000..82f7bb78 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Announcement.kt @@ -0,0 +1,40 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-24. + */ +package pl.szczodrzynski.edziennik.data.db.entity + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.Ignore +import androidx.room.Index +import pl.szczodrzynski.edziennik.utils.models.Date + +@Entity(tableName = "announcements", + primaryKeys = ["profileId", "announcementId"], + indices = [ + Index(value = ["profileId"]) + ]) +open class Announcement( + val profileId: Int, + @ColumnInfo(name = "announcementId") + var id: Long, + @ColumnInfo(name = "announcementSubject") + var subject: String, + @ColumnInfo(name = "announcementText") + var text: String?, + + @ColumnInfo(name = "announcementStartDate") + var startDate: Date?, + @ColumnInfo(name = "announcementEndDate") + var endDate: Date?, + + var teacherId: Long, + var addedDate: Long = System.currentTimeMillis() +) : Keepable() { + + @ColumnInfo(name = "announcementIdString") + var idString: String? = null + + @Ignore + var showAsUnseen: Boolean? = null +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Attendance.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Attendance.java deleted file mode 100644 index 039dcb0c..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Attendance.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.entity; - -import androidx.annotation.NonNull; -import androidx.room.ColumnInfo; -import androidx.room.Entity; -import androidx.room.Ignore; -import androidx.room.Index; - -import pl.szczodrzynski.edziennik.utils.models.Date; -import pl.szczodrzynski.edziennik.utils.models.Time; - -@Entity(tableName = "attendances", - primaryKeys = {"profileId", "attendanceId", "attendanceLessonDate", "attendanceStartTime"}, - indices = {@Index(value = {"profileId"})}) -public class Attendance { - public int profileId; - - @ColumnInfo(name = "attendanceId") - public long id; - - @NonNull - @ColumnInfo(name = "attendanceLessonDate") - public Date lessonDate; - @NonNull - @ColumnInfo(name = "attendanceStartTime") - public Time startTime; - @ColumnInfo(name = "attendanceLessonTopic") - public String lessonTopic; - @ColumnInfo(name = "attendanceSemester") - public int semester; - public static final int TYPE_PRESENT = 0; - public static final int TYPE_ABSENT = 1; - public static final int TYPE_ABSENT_EXCUSED = 2; - public static final int TYPE_RELEASED = 3; - public static final int TYPE_BELATED = 4; - public static final int TYPE_BELATED_EXCUSED = 5; - public static final int TYPE_CUSTOM = 6; - public static final int TYPE_DAY_FREE = 7; - @ColumnInfo(name = "attendanceType") - public int type = TYPE_PRESENT; - - public long teacherId; - public long subjectId; - - @Ignore - public Attendance() { - this(-1, -1, -1, -1, 0, "", Date.getToday(), Time.getNow(), TYPE_PRESENT); - } - - public Attendance(int profileId, long id, long teacherId, long subjectId, int semester, String lessonTopic, Date lessonDate, Time startTime, int type) { - this.profileId = profileId; - this.id = id; - this.teacherId = teacherId; - this.subjectId = subjectId; - this.semester = semester; - this.lessonTopic = lessonTopic; - this.lessonDate = lessonDate; - this.startTime = startTime; - this.type = type; - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Attendance.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Attendance.kt new file mode 100644 index 00000000..b2ebb5a0 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Attendance.kt @@ -0,0 +1,78 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-24. + */ +package pl.szczodrzynski.edziennik.data.db.entity + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.Ignore +import androidx.room.Index +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time + +@Entity(tableName = "attendances", + primaryKeys = ["profileId", "attendanceId"], + indices = [ + Index(value = ["profileId"]) + ]) +open class Attendance( + val profileId: Int, + @ColumnInfo(name = "attendanceId") + var id: Long, + /** Base type ID used to count attendance stats */ + @ColumnInfo(name = "attendanceBaseType") + var baseType: Int, + /** A full type name coming from the e-register */ + @ColumnInfo(name = "attendanceTypeName") + var typeName: String, + /** A short name to display by default, might be different for non-standard types */ + @ColumnInfo(name = "attendanceTypeShort") + val typeShort: String, + /** A short name that the e-register would display */ + @ColumnInfo(name = "attendanceTypeSymbol") + var typeSymbol: String, + /** A color that the e-register would display, null falls back to app's default */ + @ColumnInfo(name = "attendanceTypeColor") + var typeColor: Int?, + + @ColumnInfo(name = "attendanceDate") + var date: Date, + @ColumnInfo(name = "attendanceTime") + var startTime: Time?, + @ColumnInfo(name = "attendanceSemester") + var semester: Int, + + var teacherId: Long, + var subjectId: Long, + var addedDate: Long = System.currentTimeMillis() +) : Keepable() { + companion object { + const val TYPE_UNKNOWN = -1 // #3f51b5 + const val TYPE_PRESENT = 0 // #009688 + const val TYPE_PRESENT_CUSTOM = 10 // count as presence AND show in the list + custom color, fallback: #3f51b5 + const val TYPE_ABSENT = 1 // #ff3d00 + const val TYPE_ABSENT_EXCUSED = 2 // #76ff03 + const val TYPE_RELEASED = 3 // #9e9e9e + const val TYPE_BELATED = 4 // #ffc107 + const val TYPE_BELATED_EXCUSED = 5 // #ffc107 + const val TYPE_DAY_FREE = 6 // #43a047 + + // attendance bar order: + // day_free, present, present_custom, unknown, belated_excused, belated, released, absent_excused, absent, + } + + @ColumnInfo(name = "attendanceLessonTopic") + var lessonTopic: String? = null + @ColumnInfo(name = "attendanceLessonNumber") + var lessonNumber: Int? = null + @ColumnInfo(name = "attendanceIsCounted") + var isCounted: Boolean = true + + @Ignore + var showAsUnseen: Boolean? = null + + @delegate:Ignore + val typeObject by lazy { + AttendanceType(profileId, baseType.toLong(), baseType, typeName, typeShort, typeSymbol, typeColor).also { it.isCounted = isCounted } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/AttendanceType.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/AttendanceType.kt index 0e3e86f9..c5fccc4b 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/AttendanceType.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/AttendanceType.kt @@ -5,19 +5,55 @@ package pl.szczodrzynski.edziennik.data.db.entity import androidx.room.Entity +import androidx.room.Ignore @Entity(tableName = "attendanceTypes", primaryKeys = ["profileId", "id"]) data class AttendanceType ( - val profileId: Int, - val id: Long, + /** Base type ID used to count attendance stats */ + val baseType: Int, + /** A full type name coming from the e-register */ + val typeName: String, + /** A short name to display by default, might be different for non-standard types */ + val typeShort: String, + /** A short name that the e-register would display */ + val typeSymbol: String, + /** A color that the e-register would display, null falls back to app's default */ + val typeColor: Int? +) : Comparable { - val name: String, + @Ignore + var isCounted: Boolean = true - val type: Int, - - val color: Int - -) + // attendance bar order: + // day_free, present, present_custom, unknown, belated_excused, belated, released, absent_excused, absent, + override fun compareTo(other: AttendanceType): Int { + val type1 = when (baseType) { + Attendance.TYPE_DAY_FREE -> 0 + Attendance.TYPE_PRESENT -> 1 + Attendance.TYPE_PRESENT_CUSTOM -> 2 + Attendance.TYPE_UNKNOWN -> 3 + Attendance.TYPE_BELATED_EXCUSED -> 4 + Attendance.TYPE_BELATED -> 5 + Attendance.TYPE_RELEASED -> 6 + Attendance.TYPE_ABSENT_EXCUSED -> 7 + Attendance.TYPE_ABSENT -> 8 + else -> 9 + } + val type2 = when (other.baseType) { + Attendance.TYPE_DAY_FREE -> 0 + Attendance.TYPE_PRESENT -> 1 + Attendance.TYPE_PRESENT_CUSTOM -> 2 + Attendance.TYPE_UNKNOWN -> 3 + Attendance.TYPE_BELATED_EXCUSED -> 4 + Attendance.TYPE_BELATED -> 5 + Attendance.TYPE_RELEASED -> 6 + Attendance.TYPE_ABSENT_EXCUSED -> 7 + Attendance.TYPE_ABSENT -> 8 + else -> 9 + } + return type1 - type2 + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Event.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Event.java deleted file mode 100644 index bed95bdf..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Event.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.entity; - -import androidx.annotation.Nullable; -import androidx.room.ColumnInfo; -import androidx.room.Entity; -import androidx.room.Ignore; -import androidx.room.Index; - -import java.util.Calendar; - -import pl.szczodrzynski.edziennik.data.db.full.EventFull; -import pl.szczodrzynski.edziennik.utils.models.Date; -import pl.szczodrzynski.edziennik.utils.models.Time; - -@Entity(tableName = "events", - primaryKeys = {"profileId", "eventId"}, - indices = {@Index(value = {"profileId", "eventDate", "eventStartTime"}), @Index(value = {"profileId", "eventType"})}) -public class Event { - public int profileId; - - @ColumnInfo(name = "eventId") - public long id; - - @ColumnInfo(name = "eventDate") - public Date eventDate; - @ColumnInfo(name = "eventStartTime") - @Nullable - public Time startTime; // null for allDay - @ColumnInfo(name = "eventTopic") - public String topic; - @ColumnInfo(name = "eventColor") - public int color = -1; - public static final long TYPE_UNDEFINED = -2; - public static final long TYPE_HOMEWORK = -1; - public static final long TYPE_DEFAULT = 0; - public static final long TYPE_EXAM = 1; - public static final long TYPE_SHORT_QUIZ = 2; - public static final long TYPE_ESSAY = 3; - public static final long TYPE_PROJECT = 4; - public static final long TYPE_PT_MEETING = 5; - public static final long TYPE_EXCURSION = 6; - public static final long TYPE_READING = 7; - public static final long TYPE_CLASS_EVENT = 8; - public static final long TYPE_INFORMATION = 9; - public static final long TYPE_TEACHER_ABSENCE = 10; - public static final int COLOR_HOMEWORK = 0xff795548; - public static final int COLOR_DEFAULT = 0xffffc107; - public static final int COLOR_EXAM = 0xfff44336; - public static final int COLOR_SHORT_QUIZ = 0xff76ff03; - public static final int COLOR_ESSAY = 0xFF4050B5; - public static final int COLOR_PROJECT = 0xFF673AB7; - public static final int COLOR_PT_MEETING = 0xff90caf9; - public static final int COLOR_EXCURSION = 0xFF4CAF50; - public static final int COLOR_READING = 0xFFFFEB3B; - public static final int COLOR_CLASS_EVENT = 0xff388e3c; - public static final int COLOR_INFORMATION = 0xff039be5; - public static final int COLOR_TEACHER_ABSENCE = 0xff039be5; - @ColumnInfo(name = "eventType") - public long type = TYPE_DEFAULT; - @ColumnInfo(name = "eventAddedManually") - public boolean addedManually; - @ColumnInfo(name = "eventSharedBy") - public String sharedBy = null; - @ColumnInfo(name = "eventSharedByName") - public String sharedByName = null; - @ColumnInfo(name = "eventBlacklisted") - public boolean blacklisted = false; - - - public long teacherId; - public long subjectId; - public long teamId; - - @Ignore - public Event() {} - - public Event(int profileId, long id, Date eventDate, @Nullable Time startTime, String topic, int color, long type, boolean addedManually, long teacherId, long subjectId, long teamId) - { - this.profileId = profileId; - this.id = id; - this.eventDate = eventDate; - this.startTime = startTime; - this.topic = topic; - this.color = color; - this.type = type; - this.addedManually = addedManually; - this.teacherId = teacherId; - this.subjectId = subjectId; - this.teamId = teamId; - } - - @Ignore - public EventFull withMetadata(Metadata metadata) { - return new EventFull(this, metadata); - } - - @Ignore - public Calendar getStartTimeCalendar() { - Calendar c = Calendar.getInstance(); - c.set( - eventDate.year, - eventDate.month - 1, - eventDate.day, - (startTime == null) ? 0 : startTime.hour, - (startTime == null) ? 0 : startTime.minute, - (startTime == null) ? 0 : startTime.second - ); - return c; - } - - @Ignore - public Calendar getEndTimeCalendar() { - Calendar c = Calendar.getInstance(); - c.setTimeInMillis(getStartTimeCalendar().getTimeInMillis() + (45 * 60 * 1000)); - return c; - } - - @Override - public Event clone() { - Event event = new Event( - profileId, - id, - eventDate.clone(), - startTime == null ? null : startTime.clone(), - topic, - color, - type, - addedManually, - subjectId, - teacherId, - teamId - ); - event.sharedBy = sharedBy; - event.sharedByName = sharedByName; - event.blacklisted = blacklisted; - return event; - } - - @Override - public String toString() { - return "Event{" + - "profileId=" + profileId + - ", id=" + id + - ", eventDate=" + eventDate + - ", startTime=" + startTime + - ", topic='" + topic + '\'' + - ", color=" + color + - ", type=" + type + - ", addedManually=" + addedManually + - ", sharedBy='" + sharedBy + '\'' + - ", sharedByName='" + sharedByName + '\'' + - ", teacherId=" + teacherId + - ", subjectId=" + subjectId + - ", teamId=" + teamId + - '}'; - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Event.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Event.kt new file mode 100644 index 00000000..795bad85 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Event.kt @@ -0,0 +1,142 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-1-6 + */ +package pl.szczodrzynski.edziennik.data.db.entity + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.Ignore +import androidx.room.Index +import com.google.gson.annotations.SerializedName +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.ext.MINUTE +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time +import java.util.* + +@Entity(tableName = "events", + primaryKeys = ["profileId", "eventId"], + indices = [ + Index(value = ["profileId", "eventDate", "eventTime"]), + Index(value = ["profileId", "eventType"]) + ]) +open class Event( + /* This needs to be mutable: see SzkolnyApi.getEvents() */ + var profileId: Int, + @ColumnInfo(name = "eventId") + var id: Long, + @ColumnInfo(name = "eventDate") + @SerializedName("eventDate") + var date: Date, + @ColumnInfo(name = "eventTime") + @SerializedName("startTime") + var time: Time?, + + @ColumnInfo(name = "eventTopic") + var topic: String, + @ColumnInfo(name = "eventColor") + var color: Int?, + @ColumnInfo(name = "eventType") + var type: Long, + + var teacherId: Long, + var subjectId: Long, + var teamId: Long, + var addedDate: Long = System.currentTimeMillis() +) : Keepable() { + companion object { + const val TYPE_ELEARNING = -5L + const val TYPE_UNDEFINED = -2L + const val TYPE_HOMEWORK = -1L + const val TYPE_DEFAULT = 0L + const val TYPE_EXAM = 1L + const val TYPE_SHORT_QUIZ = 2L + const val TYPE_ESSAY = 3L + const val TYPE_PROJECT = 4L + const val TYPE_PT_MEETING = 5L + const val TYPE_EXCURSION = 6L + const val TYPE_READING = 7L + const val TYPE_CLASS_EVENT = 8L + const val TYPE_INFORMATION = 9L + const val COLOR_ELEARNING = 0xfff57f17.toInt() + const val COLOR_HOMEWORK = 0xff795548.toInt() + const val COLOR_DEFAULT = 0xffffc107.toInt() + const val COLOR_EXAM = 0xfff44336.toInt() + const val COLOR_SHORT_QUIZ = 0xff76ff03.toInt() + const val COLOR_ESSAY = 0xFF4050B5.toInt() + const val COLOR_PROJECT = 0xFF673AB7.toInt() + const val COLOR_PT_MEETING = 0xff90caf9.toInt() + const val COLOR_EXCURSION = 0xFF4CAF50.toInt() + const val COLOR_READING = 0xFFFFEB3B.toInt() + const val COLOR_CLASS_EVENT = 0xff388e3c.toInt() + const val COLOR_INFORMATION = 0xff039be5.toInt() + } + + @ColumnInfo(name = "eventAddedManually") + var addedManually: Boolean = false + get() = field || sharedBy == "self" + @ColumnInfo(name = "eventSharedBy") + var sharedBy: String? = null + @ColumnInfo(name = "eventSharedByName") + var sharedByName: String? = null + @ColumnInfo(name = "eventBlacklisted") + var blacklisted: Boolean = false + @ColumnInfo(name = "eventIsDone") + var isDone: Boolean = false + + /** + * Whether the full contents of the event are already stored locally. + * There may be a need to download the full topic or body. + */ + @ColumnInfo(name = "eventIsDownloaded") + var isDownloaded: Boolean = true + + /** + * Body/text of the event, if this is a [TYPE_HOMEWORK]. + * May be null if the body is not downloaded yet, or the type is not [TYPE_HOMEWORK]. + * May be empty or blank if the homework has no specific body attached, + * or the topic contains the body already. + */ + var homeworkBody: String? = null + val hasAttachments + get() = attachmentIds.isNotNullNorEmpty() + var attachmentIds: MutableList? = null + var attachmentNames: MutableList? = null + + /** + * Add an attachment + * @param id attachment ID + * @param name file name incl. extension + * @return a Event to which the attachment has been added + */ + fun addAttachment(id: Long, name: String): Event { + if (attachmentIds == null) attachmentIds = mutableListOf() + if (attachmentNames == null) attachmentNames = mutableListOf() + attachmentIds?.add(id) + attachmentNames?.add(name) + return this + } + + fun clearAttachments() { + attachmentIds = null + attachmentNames = null + } + + @Ignore + var showAsUnseen: Boolean? = null + + val startTimeCalendar: Calendar + get() = date.getAsCalendar(time) + + val endTimeCalendar: Calendar + get() = startTimeCalendar.also { + it.timeInMillis += 45 * MINUTE * 1000 + } + + val isHomework + get() = type == TYPE_HOMEWORK + + @Ignore + fun withMetadata(metadata: Metadata) = EventFull(this, metadata) +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/EventType.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/EventType.java deleted file mode 100644 index bf981e84..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/EventType.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.entity; - -import android.graphics.Color; - -import androidx.room.ColumnInfo; -import androidx.room.Entity; - -@Entity(tableName = "eventTypes", - primaryKeys = {"profileId", "eventType"}) -public class EventType { - public int profileId; - - @ColumnInfo(name = "eventType") - public long id; - - @ColumnInfo(name = "eventTypeName") - public String name; - @ColumnInfo(name = "eventTypeColor") - public int color; - - public EventType(int profileId, long id, String name, int color) { - this.profileId = profileId; - this.id = id; - this.name = name; - this.color = color; - } - - public EventType(int profileId, int id, String name, String color) { - this(profileId, id, name, Color.parseColor(color)); - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/EventType.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/EventType.kt new file mode 100644 index 00000000..7753b38a --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/EventType.kt @@ -0,0 +1,89 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-4-19. + */ +package pl.szczodrzynski.edziennik.data.db.entity + +import androidx.room.ColumnInfo +import androidx.room.Entity +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.COLOR_CLASS_EVENT +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.COLOR_DEFAULT +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.COLOR_ELEARNING +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.COLOR_ESSAY +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.COLOR_EXAM +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.COLOR_EXCURSION +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.COLOR_HOMEWORK +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.COLOR_INFORMATION +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.COLOR_PROJECT +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.COLOR_PT_MEETING +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.COLOR_READING +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.COLOR_SHORT_QUIZ +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.TYPE_CLASS_EVENT +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.TYPE_DEFAULT +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.TYPE_ELEARNING +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.TYPE_ESSAY +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.TYPE_EXAM +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.TYPE_EXCURSION +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.TYPE_HOMEWORK +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.TYPE_INFORMATION +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.TYPE_PROJECT +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.TYPE_PT_MEETING +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.TYPE_READING +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.TYPE_SHORT_QUIZ + +@Entity( + tableName = "eventTypes", + primaryKeys = ["profileId", "eventType"] +) +class EventType( + val profileId: Int, + + @ColumnInfo(name = "eventType") + val id: Long, + + @ColumnInfo(name = "eventTypeName") + val name: String, + @ColumnInfo(name = "eventTypeColor") + val color: Int, + @ColumnInfo(name = "eventTypeOrder") + var order: Int = id.toInt(), + @ColumnInfo(name = "eventTypeSource") + val source: Int = SOURCE_REGISTER +) { + companion object { + const val SOURCE_DEFAULT = 0 + const val SOURCE_REGISTER = 1 + const val SOURCE_CUSTOM = 2 + const val SOURCE_SHARED = 3 + + fun getTypeColorMap() = mapOf( + TYPE_ELEARNING to COLOR_ELEARNING, + TYPE_HOMEWORK to COLOR_HOMEWORK, + TYPE_DEFAULT to COLOR_DEFAULT, + TYPE_EXAM to COLOR_EXAM, + TYPE_SHORT_QUIZ to COLOR_SHORT_QUIZ, + TYPE_ESSAY to COLOR_ESSAY, + TYPE_PROJECT to COLOR_PROJECT, + TYPE_PT_MEETING to COLOR_PT_MEETING, + TYPE_EXCURSION to COLOR_EXCURSION, + TYPE_READING to COLOR_READING, + TYPE_CLASS_EVENT to COLOR_CLASS_EVENT, + TYPE_INFORMATION to COLOR_INFORMATION + ) + + fun getTypeNameMap() = mapOf( + TYPE_ELEARNING to R.string.event_type_elearning, + TYPE_HOMEWORK to R.string.event_type_homework, + TYPE_DEFAULT to R.string.event_other, + TYPE_EXAM to R.string.event_exam, + TYPE_SHORT_QUIZ to R.string.event_short_quiz, + TYPE_ESSAY to R.string.event_essay, + TYPE_PROJECT to R.string.event_project, + TYPE_PT_MEETING to R.string.event_pt_meeting, + TYPE_EXCURSION to R.string.event_excursion, + TYPE_READING to R.string.event_reading, + TYPE_CLASS_EVENT to R.string.event_class_event, + TYPE_INFORMATION to R.string.event_information + ) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Grade.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Grade.kt index 393ab332..5bf3bd86 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Grade.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Grade.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 + * Copyright (c) Kuba Szczodrzyński 2020-4-24. */ package pl.szczodrzynski.edziennik.data.db.entity @@ -8,23 +8,11 @@ import androidx.room.Entity import androidx.room.Ignore import androidx.room.Index -/*public Grade(int profileId, long id, String category, int color, String description, String name, float value, float weight, int semester, long teacherId, long subjectId) { - this.profileId = profileId; - this.id = id; - this.category = category; - this.color = color; - this.description = description; - this.name = name; - this.value = value; - this.weight = weight; - this.semester = semester; - this.teacherId = teacherId; - this.subjectId = subjectId; - }*/ - @Entity(tableName = "grades", primaryKeys = ["profileId", "gradeId"], - indices = [Index(value = ["profileId"])]) + indices = [ + Index(value = ["profileId"]) + ]) open class Grade( val profileId: Int, @ColumnInfo(name = "gradeId") @@ -40,6 +28,7 @@ open class Grade( var weight: Float, @ColumnInfo(name = "gradeColor") var color: Int, + @ColumnInfo(name = "gradeCategory") var category: String?, @ColumnInfo(name = "gradeDescription") @@ -50,8 +39,9 @@ open class Grade( @ColumnInfo(name = "gradeSemester") val semester: Int, val teacherId: Long, - val subjectId: Long -) { + val subjectId: Long, + var addedDate: Long = System.currentTimeMillis() +) : Keepable() { companion object { const val TYPE_NORMAL = 0 const val TYPE_SEMESTER1_PROPOSED = 1 diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Keepable.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Keepable.kt new file mode 100644 index 00000000..eb0da986 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Keepable.kt @@ -0,0 +1,9 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-3-30. + */ + +package pl.szczodrzynski.edziennik.data.db.entity + +abstract class Keepable { + var keep: Boolean = true +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Lesson.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Lesson.kt index ceb6cf9c..37b7f6f3 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Lesson.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Lesson.kt @@ -1,7 +1,6 @@ /* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 + * Copyright (c) Kuba Szczodrzyński 2020-4-25. */ - package pl.szczodrzynski.edziennik.data.db.entity import androidx.room.Entity @@ -11,12 +10,15 @@ import pl.szczodrzynski.edziennik.utils.models.Date import pl.szczodrzynski.edziennik.utils.models.Time @Entity(tableName = "timetable", + primaryKeys = ["profileId", "id"], indices = [ Index(value = ["profileId", "type", "date"]), Index(value = ["profileId", "type", "oldDate"]) - ], - primaryKeys = ["profileId", "id"]) -open class Lesson(val profileId: Int, var id: Long) { + ]) +open class Lesson( + val profileId: Int, + var id: Long +) : Keepable() { companion object { const val TYPE_NO_LESSONS = -1 const val TYPE_NORMAL = 0 @@ -46,6 +48,8 @@ open class Lesson(val profileId: Int, var id: Long) { var oldTeamId: Long? = null var oldClassroom: String? = null + var isExtra: Boolean = false + val displayDate: Date? get() { if (type == TYPE_SHIFTED_SOURCE) @@ -70,6 +74,8 @@ open class Lesson(val profileId: Int, var id: Long) { @Ignore var showAsUnseen = false + var color: Int? = null + override fun toString(): String { return "Lesson(profileId=$profileId, " + "id=$id, " + @@ -119,11 +125,13 @@ open class Lesson(val profileId: Int, var id: Long) { return true } - override fun hashCode(): Int { // intentionally ignoring ID and display* here + override fun hashCode(): Int { // intentionally ignoring ID, display* and isExtra here var result = profileId result = 31 * result + type result = 31 * result + (date?.hashCode() ?: 0) - result = 31 * result + (lessonNumber ?: 0) + // this creates problems in Mobidziennik with extra lessons + // ... and is not generally useful anyway + // result = 31 * result + (lessonNumber ?: 0) result = 31 * result + (startTime?.hashCode() ?: 0) result = 31 * result + (endTime?.hashCode() ?: 0) result = 31 * result + (subjectId?.hashCode() ?: 0) @@ -131,7 +139,7 @@ open class Lesson(val profileId: Int, var id: Long) { result = 31 * result + (teamId?.hashCode() ?: 0) result = 31 * result + (classroom?.hashCode() ?: 0) result = 31 * result + (oldDate?.hashCode() ?: 0) - result = 31 * result + (oldLessonNumber ?: 0) + // result = 31 * result + (oldLessonNumber ?: 0) result = 31 * result + (oldStartTime?.hashCode() ?: 0) result = 31 * result + (oldEndTime?.hashCode() ?: 0) result = 31 * result + (oldSubjectId?.hashCode() ?: 0) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/LoginStore.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/LoginStore.kt index 1ec410b5..32c0d7e7 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/LoginStore.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/LoginStore.kt @@ -8,7 +8,7 @@ import android.os.Bundle import androidx.room.ColumnInfo import androidx.room.Entity import com.google.gson.JsonObject -import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.ext.* @Entity(tableName = "loginStores", primaryKeys = ["loginStoreId"]) class LoginStore( @@ -59,6 +59,7 @@ class LoginStore( is Long -> putLoginData(key, o) is Float -> putLoginData(key, o) is Boolean -> putLoginData(key, o) + is Bundle -> putLoginData(key, o.toJsonObject()) } } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/LuckyNumber.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/LuckyNumber.java deleted file mode 100644 index bca49ec5..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/LuckyNumber.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.entity; - -import androidx.annotation.NonNull; -import androidx.room.ColumnInfo; -import androidx.room.Entity; -import androidx.room.Ignore; - -import pl.szczodrzynski.edziennik.utils.models.Date; - -@Entity(tableName = "luckyNumbers", - primaryKeys = {"profileId", "luckyNumberDate"}) -public class LuckyNumber { - public int profileId; - - @NonNull - @ColumnInfo(name = "luckyNumberDate", typeAffinity = 3) - public Date date; - @ColumnInfo(name = "luckyNumber") - public int number; - - public LuckyNumber(int profileId, @NonNull Date date, int number) { - this.profileId = profileId; - this.date = date; - this.number = number; - } - - @Ignore - public LuckyNumber() { - this.date = Date.getToday(); - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/LuckyNumber.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/LuckyNumber.kt new file mode 100644 index 00000000..6fb943c9 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/LuckyNumber.kt @@ -0,0 +1,22 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-24. + */ +package pl.szczodrzynski.edziennik.data.db.entity + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.Ignore +import pl.szczodrzynski.edziennik.utils.models.Date + +@Entity(tableName = "luckyNumbers", + primaryKeys = ["profileId", "luckyNumberDate"]) +open class LuckyNumber( + val profileId: Int, + @ColumnInfo(name = "luckyNumberDate", typeAffinity = ColumnInfo.INTEGER) + var date: Date, + @ColumnInfo(name = "luckyNumber") + var number: Int +) : Keepable() { + @Ignore + var showAsUnseen = false +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Message.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Message.java deleted file mode 100644 index f1b6453b..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Message.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.entity; - -import androidx.annotation.Nullable; -import androidx.room.ColumnInfo; -import androidx.room.Entity; -import androidx.room.Ignore; -import androidx.room.Index; - -import java.util.ArrayList; -import java.util.List; - -@Entity(tableName = "messages", - primaryKeys = {"profileId", "messageId"}, - indices = {@Index(value = {"profileId"})}) -public class Message { - public int profileId; - - @ColumnInfo(name = "messageId") - public long id; - - @ColumnInfo(name = "messageSubject") - public String subject; - @Nullable - @ColumnInfo(name = "messageBody") - public String body = null; - - public static final int TYPE_RECEIVED = 0; - public static final int TYPE_SENT = 1; - public static final int TYPE_DELETED = 2; - public static final int TYPE_DRAFT = 3; - @ColumnInfo(name = "messageType") - public int type = TYPE_RECEIVED; - - public long senderId = -1; // -1 for sent messages - public long senderReplyId = -1; - public boolean overrideHasAttachments = false; // if the attachments are not yet downloaded but we already know there are some - public List attachmentIds = null; - public List attachmentNames = null; - public List attachmentSizes = null; - - @Ignore - public Message() {} - - public Message(int profileId, long id, String subject, @Nullable String body, int type, long senderId, long senderReplyId) { - this.profileId = profileId; - this.id = id; - this.subject = subject; - this.body = body; - this.type = type; - this.senderId = senderId; - this.senderReplyId = senderReplyId; - } - - /** - * Add an attachment - * @param id attachment ID - * @param name file name incl. extension - * @param size file size or -1 if unknown - * @return a Message to which the attachment has been added - */ - public Message addAttachment(long id, String name, long size) { - if (attachmentIds == null) - attachmentIds = new ArrayList<>(); - if (attachmentNames == null) - attachmentNames = new ArrayList<>(); - if (attachmentSizes == null) - attachmentSizes = new ArrayList<>(); - attachmentIds.add(id); - attachmentNames.add(name); - attachmentSizes.add(size); - return this; - } - - public void clearAttachments() { - attachmentIds = null; - attachmentNames = null; - attachmentSizes = null; - } - - public Message setHasAttachments() { - overrideHasAttachments = true; - return this; - } - - public boolean hasAttachments() { - return overrideHasAttachments || (attachmentIds != null && attachmentIds.size() > 0); - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Message.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Message.kt new file mode 100644 index 00000000..18a87df7 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Message.kt @@ -0,0 +1,86 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-25. + */ +package pl.szczodrzynski.edziennik.data.db.entity + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.Ignore +import androidx.room.Index +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty + +@Entity(tableName = "messages", + primaryKeys = ["profileId", "messageId"], + indices = [ + Index(value = ["profileId", "messageType"]) + ]) +open class Message( + val profileId: Int, + @ColumnInfo(name = "messageId") + val id: Long, + @ColumnInfo(name = "messageType") + var type: Int, + + @ColumnInfo(name = "messageSubject") + var subject: String, + @ColumnInfo(name = "messageBody") + var body: String?, + + /** + * Keep in mind that this being null does NOT + * necessarily mean the message is sent. + */ + var senderId: Long?, + var addedDate: Long = System.currentTimeMillis() +) : Keepable() { + companion object { + const val TYPE_RECEIVED = 0 + const val TYPE_SENT = 1 + const val TYPE_DELETED = 2 + const val TYPE_DRAFT = 3 + } + + @ColumnInfo(name = "messageIsPinned") + var isStarred: Boolean = false + + val isReceived + get() = type == TYPE_RECEIVED + val isSent + get() = type == TYPE_SENT + val isDeleted + get() = type == TYPE_DELETED + val isDraft + get() = type == TYPE_DRAFT + + var hasAttachments = false // if the attachments are not yet downloaded but we already know there are some + get() = field || attachmentIds.isNotNullNorEmpty() + var attachmentIds: MutableList? = null + var attachmentNames: MutableList? = null + var attachmentSizes: MutableList? = null + + @Ignore + var showAsUnseen: Boolean? = null + + /** + * Add an attachment + * @param id attachment ID + * @param name file name incl. extension + * @param size file size or -1 if unknown + * @return a Message to which the attachment has been added + */ + fun addAttachment(id: Long, name: String, size: Long): Message { + if (attachmentIds == null) attachmentIds = mutableListOf() + if (attachmentNames == null) attachmentNames = mutableListOf() + if (attachmentSizes == null) attachmentSizes = mutableListOf() + attachmentIds?.add(id) + attachmentNames?.add(name) + attachmentSizes?.add(size) + return this + } + + fun clearAttachments() { + attachmentIds = null + attachmentNames = null + attachmentSizes = null + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Metadata.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Metadata.java index 6ea94f4e..7374d915 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Metadata.java +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Metadata.java @@ -36,7 +36,6 @@ public class Metadata { public boolean seen; public boolean notified; - public long addedDate; @Ignore public Metadata() { @@ -45,13 +44,12 @@ public class Metadata { this.notified = false; } - public Metadata(int profileId, int thingType, long thingId, boolean seen, boolean notified, long addedDate) { + public Metadata(int profileId, int thingType, long thingId, boolean seen, boolean notified) { this.profileId = profileId; this.thingType = thingType; this.thingId = thingId; this.seen = seen; this.notified = notified; - this.addedDate = addedDate; } public String thingType() { @@ -86,7 +84,6 @@ public class Metadata { ", thingId=" + thingId + ", seen=" + seen + ", notified=" + notified + - ", addedDate=" + addedDate + '}'; } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Note.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Note.kt new file mode 100644 index 00000000..9b6ad908 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Note.kt @@ -0,0 +1,149 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-16. + */ + +package pl.szczodrzynski.edziennik.data.db.entity + +import androidx.room.* +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.ui.search.Searchable +import pl.szczodrzynski.edziennik.utils.html.BetterHtml + +@Entity( + tableName = "notes", + indices = [ + Index(value = ["profileId", "noteOwnerType", "noteOwnerId"]), + ], +) +data class Note( + var profileId: Int, + + @PrimaryKey + @ColumnInfo(name = "noteId") + val id: Long, + + @ColumnInfo(name = "noteOwnerType") + val ownerType: OwnerType?, + @ColumnInfo(name = "noteOwnerId") + val ownerId: Long?, + @ColumnInfo(name = "noteReplacesOriginal") + val replacesOriginal: Boolean = false, + + @ColumnInfo(name = "noteTopic") + val topic: String?, + @ColumnInfo(name = "noteBody") + val body: String, + @ColumnInfo(name = "noteColor") + val color: Long?, + + @ColumnInfo(name = "noteSharedBy") + var sharedBy: String? = null, + @ColumnInfo(name = "noteSharedByName") + val sharedByName: String? = null, + + val addedDate: Long = System.currentTimeMillis(), +) : Searchable { + enum class OwnerType( + val isShareable: Boolean, + val canReplace: Boolean, + ) { + /** + * The [NONE] type is only for usage in the UI and should not be saved. + */ + NONE(isShareable = true, canReplace = false), + EVENT(isShareable = true, canReplace = true), + DAY(isShareable = true, canReplace = false), + LESSON(isShareable = true, canReplace = true), + MESSAGE(isShareable = true, canReplace = false), + EVENT_SUBJECT(isShareable = true, canReplace = false), + LESSON_SUBJECT(isShareable = true, canReplace = false), + GRADE(isShareable = false, canReplace = true), + ATTENDANCE(isShareable = false, canReplace = true), + BEHAVIOR(isShareable = false, canReplace = false), + ANNOUNCEMENT(isShareable = true, canReplace = false), + } + + enum class Color(val value: Long?, val stringRes: Int) { + NONE(null, R.string.color_none), + RED(0xffff1744, R.string.color_red), + ORANGE(0xffff9100, R.string.color_orange), + YELLOW(0xffffea00, R.string.color_yellow), + GREEN(0xff00c853, R.string.color_green), + TEAL(0xff00bfa5, R.string.color_teal), + BLUE(0xff0091ea, R.string.color_blue), + DARK_BLUE(0xff304ffe, R.string.color_dark_blue), + PURPLE(0xff6200ea, R.string.color_purple), + PINK(0xffd500f9, R.string.color_pink), + BROWN(0xff795548, R.string.color_brown), + GREY(0xff9e9e9e, R.string.color_grey), + BLACK(0xff000000, R.string.color_black), + } + + val isShared + get() = sharedBy != null && sharedByName != null + val canEdit + get() = !isShared || sharedBy == "self" + + // used when receiving notes + @Ignore + var teamCode: String? = null + + @delegate:Ignore + @delegate:Transient + val topicHtml by lazy { + topic?.let { + BetterHtml.fromHtml(context = null, it, nl2br = true) + } + } + + @delegate:Ignore + @delegate:Transient + val bodyHtml by lazy { + BetterHtml.fromHtml(context = null, body, nl2br = true) + } + + @Ignore + @Transient + var isCategoryItem = false + + @Ignore + @Transient + override var searchPriority = 0 + + @Ignore + @Transient + override var searchHighlightText: String? = null + + @delegate:Ignore + @delegate:Transient + override val searchKeywords by lazy { + if (isCategoryItem) + return@lazy emptyList() + listOf( + listOf(topicHtml?.toString(), bodyHtml.toString()), + listOf(sharedByName), + ) + } + + override fun compareTo(other: Searchable<*>): Int { + if (other !is Note) + return 0 + val order = ownerType?.ordinal ?: -1 + val otherOrder = other.ownerType?.ordinal ?: -1 + return when { + // custom ascending sorting + order > otherOrder -> 1 + order < otherOrder -> -1 + // all category elements stay at their original position + isCategoryItem -> 0 + other.isCategoryItem -> 0 + // ascending sorting + searchPriority > other.searchPriority -> 1 + searchPriority < other.searchPriority -> -1 + // descending sorting + addedDate > other.addedDate -> -1 + addedDate < other.addedDate -> 1 + else -> 0 + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Noteable.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Noteable.kt new file mode 100644 index 00000000..052596b3 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Noteable.kt @@ -0,0 +1,34 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-17. + */ + +package pl.szczodrzynski.edziennik.data.db.entity + +interface Noteable { + + fun getNoteType(): Note.OwnerType + fun getNoteOwnerProfileId(): Int + fun getNoteOwnerId(): Long + + var notes: MutableList + + fun filterNotes() { + val type = getNoteType() + val profileId = getNoteOwnerProfileId() + notes.removeAll { + it.profileId != profileId || it.ownerType != type + } + } + + fun hasNotes() = notes.isNotEmpty() + fun hasReplacingNotes() = notes.any { it.replacesOriginal } + + fun getNoteSubstituteText(showNotes: Boolean): CharSequence? { + if (!showNotes) + return null + val note = notes.firstOrNull { + it.replacesOriginal + } + return note?.topicHtml ?: note?.bodyHtml + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Notice.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Notice.java deleted file mode 100644 index 306e6f92..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Notice.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.entity; - -import androidx.room.ColumnInfo; -import androidx.room.Entity; -import androidx.room.Ignore; -import androidx.room.Index; - -@Entity(tableName = "notices", - primaryKeys = {"profileId", "noticeId"}, - indices = {@Index(value = {"profileId"})}) -public class Notice { - public int profileId; - - @ColumnInfo(name = "noticeId") - public long id; - - @ColumnInfo(name = "noticeText") - public String text; - @ColumnInfo(name = "noticeSemester") - public int semester; - public static final int TYPE_NEUTRAL = 0; - public static final int TYPE_POSITIVE = 1; - public static final int TYPE_NEGATIVE = 2; - @ColumnInfo(name = "noticeType") - public int type = TYPE_NEUTRAL; - - public float points = 0; - public String category = null; - - public long teacherId; - - @Ignore - public Notice() {} - - public Notice(int profileId, long id, String text, int semester, int type, long teacherId) { - this.profileId = profileId; - this.id = id; - this.text = text; - this.semester = semester; - this.type = type; - this.teacherId = teacherId; - } -} - - diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Notice.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Notice.kt new file mode 100644 index 00000000..0e1f21fe --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Notice.kt @@ -0,0 +1,43 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-25. + */ +package pl.szczodrzynski.edziennik.data.db.entity + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.Ignore +import androidx.room.Index + +@Entity(tableName = "notices", + primaryKeys = ["profileId", "noticeId"], + indices = [ + Index(value = ["profileId"]) + ]) +open class Notice( + val profileId: Int, + @ColumnInfo(name = "noticeId") + var id: Long, + @ColumnInfo(name = "noticeType") + var type: Int, + @ColumnInfo(name = "noticeSemester") + var semester: Int, + + @ColumnInfo(name = "noticeText") + var text: String, + @ColumnInfo(name = "noticeCategory") + var category: String?, + @ColumnInfo(name = "noticePoints") + var points: Float?, + + var teacherId: Long, + var addedDate: Long = System.currentTimeMillis() +) : Keepable() { + companion object { + const val TYPE_NEUTRAL = 0 + const val TYPE_POSITIVE = 1 + const val TYPE_NEGATIVE = 2 + } + + @Ignore + var showAsUnseen = false +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Notification.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Notification.kt index 242d5999..35208927 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Notification.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Notification.kt @@ -10,7 +10,10 @@ import android.content.Intent import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.JsonObject +import com.mikepenz.iconics.typeface.IIcon +import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial import pl.szczodrzynski.edziennik.MainActivity +import pl.szczodrzynski.edziennik.ext.pendingIntentFlag @Entity(tableName = "notifications") data class Notification( @@ -19,6 +22,7 @@ data class Notification( val title: String, val text: String, + val textLong: String? = null, val type: Int, @@ -52,6 +56,8 @@ data class Notification( const val TYPE_NEW_ANNOUNCEMENT = 15 const val TYPE_FEEDBACK_MESSAGE = 16 const val TYPE_AUTO_ARCHIVING = 17 + const val TYPE_TEACHER_ABSENCE = 19 + const val TYPE_NEW_SHARED_NOTE = 20 fun buildId(profileId: Int, type: Int, itemId: Long): Long { return 1000000000000 + profileId*10000000000 + type*100000000 + itemId; @@ -93,6 +99,22 @@ data class Notification( fun getPendingIntent(context: Context): PendingIntent { val intent = Intent(context, MainActivity::class.java) fillIntent(intent) - return PendingIntent.getActivity(context, id.toInt(), intent, PendingIntent.FLAG_ONE_SHOT) + return PendingIntent.getActivity(context, id.toInt(), intent, PendingIntent.FLAG_ONE_SHOT or pendingIntentFlag()) + } + + fun getLargeIcon(): IIcon = when (type) { + TYPE_TIMETABLE_LESSON_CHANGE -> CommunityMaterial.Icon3.cmd_timetable + TYPE_NEW_GRADE -> CommunityMaterial.Icon3.cmd_numeric_5_box_outline + TYPE_NEW_EVENT -> CommunityMaterial.Icon.cmd_calendar_outline + TYPE_NEW_HOMEWORK -> CommunityMaterial.Icon3.cmd_notebook_outline + TYPE_NEW_SHARED_EVENT -> CommunityMaterial.Icon.cmd_calendar_outline + TYPE_NEW_SHARED_HOMEWORK -> CommunityMaterial.Icon3.cmd_notebook_outline + TYPE_NEW_MESSAGE -> CommunityMaterial.Icon.cmd_email_outline + TYPE_NEW_NOTICE -> CommunityMaterial.Icon.cmd_emoticon_outline + TYPE_NEW_ATTENDANCE -> CommunityMaterial.Icon.cmd_calendar_remove_outline + TYPE_LUCKY_NUMBER -> CommunityMaterial.Icon.cmd_emoticon_excited_outline + TYPE_NEW_ANNOUNCEMENT -> CommunityMaterial.Icon.cmd_bullhorn_outline + TYPE_NEW_SHARED_NOTE -> CommunityMaterial.Icon3.cmd_playlist_edit + else -> CommunityMaterial.Icon.cmd_bell_ring_outline } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Profile.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Profile.kt index 61777a8d..b1615fbc 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Profile.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Profile.kt @@ -15,8 +15,11 @@ import androidx.room.Entity import androidx.room.Ignore import com.google.gson.JsonObject import pl.droidsonroids.gif.GifDrawable -import pl.szczodrzynski.edziennik.* -import pl.szczodrzynski.edziennik.data.api.LOGIN_TYPE_EDUDZIENNIK +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.MainActivity +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.ProfileImageHolder import pl.szczodrzynski.edziennik.utils.models.Date import pl.szczodrzynski.navlib.ImageHolder import pl.szczodrzynski.navlib.R @@ -26,7 +29,7 @@ import pl.szczodrzynski.navlib.getDrawableFromRes @Entity(tableName = "profiles", primaryKeys = ["profileId"]) open class Profile( @ColumnInfo(name = "profileId") - override val id: Int, + override var id: Int, /* needs to be var for ProfileArchiver */ val loginStoreId: Int, val loginStoreType: Int, @@ -62,6 +65,12 @@ open class Profile( var empty = true var archived = false + /** + * A unique ID matching [archived] profiles with current ones + * and vice-versa. + */ + var archiveId: Int? = null + var syncEnabled = true var enableSharedEvents = true var registration = REGISTRATION_UNSPECIFIED @@ -79,10 +88,29 @@ open class Profile( var dateYearEnd = Date(studentSchoolYearStart + 1, 6, 30) fun getSemesterStart(semester: Int) = if (semester == 1) dateSemester1Start else dateSemester2Start fun getSemesterEnd(semester: Int) = if (semester == 1) dateSemester2Start.clone().stepForward(0, 0, -1) else dateYearEnd - fun dateToSemester(date: Date) = if (date.value >= getSemesterStart(2).value) 2 else 1 + fun dateToSemester(date: Date) = if (date >= dateSemester2Start) 2 else 1 @delegate:Ignore val currentSemester by lazy { dateToSemester(Date.getToday()) } + fun shouldArchive(): Boolean { + // vulcan hotfix + if (dateYearEnd.month > 6) { + dateYearEnd.month = 6 + dateYearEnd.day = 30 + } + // fix for when versions <4.3 synced 2020/2021 year dates to older profiles during 2020 Jun-Aug + if (dateSemester1Start.year > studentSchoolYearStart) { + val diff = dateSemester1Start.year - studentSchoolYearStart + dateSemester1Start.year -= diff + dateSemester2Start.year -= diff + dateYearEnd.year -= diff + } + return App.config.archiverEnabled + && Date.getToday() >= dateYearEnd + && Date.getToday().year > studentSchoolYearStart + } + fun isBeforeYear() = false && Date.getToday() < dateSemester1Start + var disabledNotifications: List? = null var lastReceiversSync: Long = 0 @@ -103,15 +131,36 @@ open class Profile( val isParent get() = accountName != null + val accountOwnerName + get() = accountName ?: studentNameLong + + val registerName + get() = when (loginStoreType) { + LOGIN_TYPE_LIBRUS -> "librus" + LOGIN_TYPE_VULCAN -> "vulcan" + LOGIN_TYPE_IDZIENNIK -> "idziennik" + LOGIN_TYPE_MOBIDZIENNIK -> "mobidziennik" + LOGIN_TYPE_PODLASIE -> "podlasie" + LOGIN_TYPE_EDUDZIENNIK -> "edudziennik" + else -> "unknown" + } + + val canShare + get() = registration == REGISTRATION_ENABLED && !archived + override fun getImageDrawable(context: Context): Drawable { + if (archived) { + return context.getDrawableFromRes(pl.szczodrzynski.edziennik.R.drawable.profile_archived).also { + it.colorFilter = PorterDuffColorFilter(colorFromName(name), PorterDuff.Mode.DST_OVER) + } + } if (!image.isNullOrEmpty()) { try { - if (image?.endsWith(".gif", true) == true) { - return GifDrawable(image ?: "") - } - else { - return RoundedBitmapDrawableFactory.create(context.resources, image ?: "") + return if (image?.endsWith(".gif", true) == true) { + GifDrawable(image ?: "") + } else { + RoundedBitmapDrawableFactory.create(context.resources, image ?: "") //return Drawable.createFromPath(image ?: "") ?: throw Exception() } } @@ -123,12 +172,16 @@ open class Profile( return context.getDrawableFromRes(R.drawable.profile).also { it.colorFilter = PorterDuffColorFilter(colorFromName(name), PorterDuff.Mode.DST_OVER) } - } + override fun getImageHolder(context: Context): ImageHolder { + if (archived) { + return ImageHolder(pl.szczodrzynski.edziennik.R.drawable.profile_archived, colorFromName(name)) + } + return if (!image.isNullOrEmpty()) { try { - ImageHolder(image ?: "") + ProfileImageHolder(image ?: "") } catch (_: Exception) { ImageHolder(R.drawable.profile, colorFromName(name)) } @@ -174,6 +227,16 @@ open class Profile( MainActivity.DRAWER_ITEM_ATTENDANCE, MainActivity.DRAWER_ITEM_ANNOUNCEMENTS ) + LOGIN_TYPE_PODLASIE -> listOf( + MainActivity.DRAWER_ITEM_TIMETABLE, + MainActivity.DRAWER_ITEM_AGENDA, + MainActivity.DRAWER_ITEM_GRADES, + MainActivity.DRAWER_ITEM_HOMEWORK + ) + LOGIN_TYPE_USOS -> listOf( + MainActivity.DRAWER_ITEM_TIMETABLE, + MainActivity.DRAWER_ITEM_AGENDA + ) else -> listOf( MainActivity.DRAWER_ITEM_TIMETABLE, MainActivity.DRAWER_ITEM_AGENDA, diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Subject.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Subject.java index a034c785..1a4c46e4 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Subject.java +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Subject.java @@ -9,7 +9,7 @@ import androidx.room.Entity; import java.util.List; -import pl.szczodrzynski.edziennik.ExtensionsKt; +import pl.szczodrzynski.edziennik.ext.GraphicsExtensionsKt; @Entity(tableName = "subjects", primaryKeys = {"profileId", "subjectId"}) @@ -31,7 +31,7 @@ public class Subject { this.id = id; this.longName = longName; this.shortName = shortName; - this.color = ExtensionsKt.colorFromName(longName); + this.color = GraphicsExtensionsKt.colorFromName(longName); } @Override diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Teacher.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Teacher.kt index 27431a4f..b192bc1d 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Teacher.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/Teacher.kt @@ -10,12 +10,14 @@ import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Ignore import pl.szczodrzynski.edziennik.R -import pl.szczodrzynski.edziennik.fixName -import pl.szczodrzynski.edziennik.join +import pl.szczodrzynski.edziennik.ext.fixName +import pl.szczodrzynski.edziennik.ext.getNameInitials +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty +import pl.szczodrzynski.edziennik.ext.join import java.util.* @Entity(tableName = "teachers", - primaryKeys = ["profileId", "teacherId"]) + primaryKeys = ["profileId", "teacherId"]) open class Teacher { companion object { const val TYPE_TEACHER = 0 // 1 @@ -25,6 +27,7 @@ open class Teacher { const val TYPE_SECRETARIAT = 4 // 16 const val TYPE_PRINCIPAL = 5 // 32 const val TYPE_SCHOOL_ADMIN = 6 // 64 + // not teachers const val TYPE_SPECIALIST = 7 // 128 const val TYPE_SUPER_ADMIN = 10 // 1024 @@ -35,7 +38,8 @@ open class Teacher { const val TYPE_OTHER = 24 // 16777216 const val IS_TEACHER_MASK = 127 - val types: List by lazy { listOf( + val types: List by lazy { + listOf( TYPE_TEACHER, TYPE_EDUCATOR, TYPE_PEDAGOGUE, @@ -50,7 +54,8 @@ open class Teacher { TYPE_PARENTS_COUNCIL, TYPE_SCHOOL_PARENTS_COUNCIL, TYPE_OTHER - ) } + ) + } fun typeName(c: Context, type: Int, typeDescription: String? = null): String { val suffix = typeDescription?.let { " ($typeDescription)" } ?: "" @@ -93,6 +98,9 @@ open class Teacher { @ColumnInfo(name = "teacherTypeDescription") var typeDescription: String? = null + @ColumnInfo(name = "teacherSubjects") + var subjects = mutableListOf() + fun isType(checkingType: Int): Boolean { return type and (1 shl checkingType) >= 1 } @@ -104,19 +112,29 @@ open class Teacher { type = type or (1 shl i) } + fun addSubject(subjectId: Long) = subjects.add(subjectId) + fun unsetTeacherType(i: Int) { type = type and (1 shl i).inv() } - fun getTypeText(c: Context): String { - val list = mutableListOf() + fun getTypeText(c: Context, subjectList: List? = null): String { + val roles = mutableListOf() types.forEach { if (isType(it)) - list += typeName(c, it, typeDescription) + roles += typeName(c, it, typeDescription) } - return list.join(", ") - } + if (subjectList != null && subjects.isNotEmpty()) { + return subjects.joinToString( + prefix = if (roles.isNotEmpty()) roles.joinToString(postfix = ": ") else "", + transform = { subjectId -> + subjectList.firstOrNull { it.id == subjectId }?.longName ?: "" + }, + ) + } + return roles.joinToString() + } @Ignore var image: Bitmap? = null @@ -127,6 +145,7 @@ open class Teacher { */ @Ignore var recipientDisplayName: CharSequence? = null + /** * Used in Message composing - determining the priority * of search result, based on the search phrase match @@ -141,8 +160,6 @@ open class Teacher { this.id = id } - - @Ignore constructor(profileId: Int, id: Long, name: String, surname: String) { this.profileId = profileId @@ -169,6 +186,7 @@ open class Teacher { this.surname = it.surname this.type = it.type this.typeDescription = it.typeDescription + this.subjects = it.subjects this.image = it.image this.recipientDisplayName = it.recipientDisplayName } @@ -180,6 +198,9 @@ open class Teacher { @delegate:Ignore val fullNameLastFirst by lazy { "$surname $name".fixName() } + @delegate:Ignore + val initialsLastFirst by lazy { fullNameLastFirst.getNameInitials() } + val shortName: String get() = (if (name == null || name?.length == 0) "" else name!![0].toString()) + "." + surname @@ -191,6 +212,7 @@ open class Teacher { ", name='" + name + '\'' + ", surname='" + surname + '\'' + ", type=" + dumpType() + + ", subjects=" + subjects.joinToString() + ", typeDescription='" + typeDescription + '\'' + '}' } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/TeacherAbsence.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/TeacherAbsence.kt index af037851..9ec5f828 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/TeacherAbsence.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/entity/TeacherAbsence.kt @@ -1,37 +1,41 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-25. + */ package pl.szczodrzynski.edziennik.data.db.entity import androidx.room.ColumnInfo import androidx.room.Entity +import androidx.room.Ignore +import androidx.room.Index import pl.szczodrzynski.edziennik.utils.models.Date import pl.szczodrzynski.edziennik.utils.models.Time @Entity(tableName = "teacherAbsence", - primaryKeys = ["profileId", "teacherAbsenceId"]) -open class TeacherAbsence ( + primaryKeys = ["profileId", "teacherAbsenceId"], + indices = [ + Index(value = ["profileId"]) + ]) +open class TeacherAbsence( + val profileId: Int, + @ColumnInfo(name = "teacherAbsenceId") + val id: Long, + @ColumnInfo(name = "teacherAbsenceType") + val type: Long, + @ColumnInfo(name = "teacherAbsenceName") + val name: String?, - val profileId: Int, + @ColumnInfo(name = "teacherAbsenceDateFrom") + val dateFrom: Date, + @ColumnInfo(name = "teacherAbsenceDateTo") + val dateTo: Date, + @ColumnInfo(name = "teacherAbsenceTimeFrom") + val timeFrom: Time?, + @ColumnInfo(name = "teacherAbsenceTimeTo") + val timeTo: Time?, - @ColumnInfo(name = "teacherAbsenceId") - val id: Long, - - val teacherId: Long, - - @ColumnInfo(name = "teacherAbsenceType") - val type: Long, - - @ColumnInfo(name = "teacherAbsenceName") - val name: String?, - - @ColumnInfo(name = "teacherAbsenceDateFrom") - val dateFrom: Date, - - @ColumnInfo(name = "teacherAbsenceDateTo") - val dateTo: Date, - - @ColumnInfo(name = "teacherAbsenceTimeFrom") - val timeFrom: Time?, - - @ColumnInfo(name = "teacherAbsenceTimeTo") - val timeTo: Time? - -) + val teacherId: Long, + var addedDate: Long = System.currentTimeMillis() +) : Keepable() { + @Ignore + var showAsUnseen = false +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/AnnouncementFull.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/AnnouncementFull.java deleted file mode 100644 index 2811a0c7..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/AnnouncementFull.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.full; - -import pl.szczodrzynski.edziennik.data.db.entity.Announcement; - -public class AnnouncementFull extends Announcement { - public String teacherFullName = ""; - - // metadata - public boolean seen; - public boolean notified; - public long addedDate; -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/AnnouncementFull.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/AnnouncementFull.kt new file mode 100644 index 00000000..f82213dd --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/AnnouncementFull.kt @@ -0,0 +1,34 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-25. + */ +package pl.szczodrzynski.edziennik.data.db.full + +import androidx.room.Relation +import pl.szczodrzynski.edziennik.data.db.entity.Announcement +import pl.szczodrzynski.edziennik.data.db.entity.Note +import pl.szczodrzynski.edziennik.data.db.entity.Noteable +import pl.szczodrzynski.edziennik.utils.models.Date + +class AnnouncementFull( + profileId: Int, id: Long, + subject: String, text: String?, + startDate: Date?, endDate: Date?, + teacherId: Long, addedDate: Long = System.currentTimeMillis() +) : Announcement( + profileId, id, + subject, text, + startDate, endDate, + teacherId, addedDate +), Noteable { + var teacherName: String? = null + + // metadata + var seen = false + var notified = false + + @Relation(parentColumn = "announcementId", entityColumn = "noteOwnerId", entity = Note::class) + override lateinit var notes: MutableList + override fun getNoteType() = Note.OwnerType.ANNOUNCEMENT + override fun getNoteOwnerProfileId() = profileId + override fun getNoteOwnerId() = id +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/AttendanceFull.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/AttendanceFull.java deleted file mode 100644 index 605d06b2..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/AttendanceFull.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.full; - -import pl.szczodrzynski.edziennik.data.db.entity.Attendance; - -public class AttendanceFull extends Attendance { - public String teacherFullName = ""; - - public String subjectLongName = ""; - public String subjectShortName = ""; - - // metadata - public boolean seen; - public boolean notified; - public long addedDate; -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/AttendanceFull.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/AttendanceFull.kt new file mode 100644 index 00000000..c1440ab5 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/AttendanceFull.kt @@ -0,0 +1,38 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-24. + */ +package pl.szczodrzynski.edziennik.data.db.full + +import androidx.room.Relation +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.data.db.entity.Note +import pl.szczodrzynski.edziennik.data.db.entity.Noteable +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time + +class AttendanceFull( + profileId: Int, id: Long, + baseType: Int, typeName: String, typeShort: String, typeSymbol: String, typeColor: Int?, + date: Date, startTime: Time, semester: Int, + teacherId: Long, subjectId: Long, addedDate: Long = System.currentTimeMillis() +) : Attendance( + profileId, id, + baseType, typeName, typeShort, typeSymbol, typeColor, + date, startTime, semester, + teacherId, subjectId, addedDate +), Noteable { + var teacherName: String? = null + var subjectLongName: String? = null + var subjectShortName: String? = null + + // metadata + var seen = false + get() = field || baseType == TYPE_PRESENT + var notified = false + + @Relation(parentColumn = "attendanceId", entityColumn = "noteOwnerId", entity = Note::class) + override lateinit var notes: MutableList + override fun getNoteType() = Note.OwnerType.ATTENDANCE + override fun getNoteOwnerProfileId() = profileId + override fun getNoteOwnerId() = id +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/EventFull.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/EventFull.java deleted file mode 100644 index beaf794e..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/EventFull.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.full; - -import pl.szczodrzynski.edziennik.data.db.entity.Event; -import pl.szczodrzynski.edziennik.data.db.entity.Metadata; - -public class EventFull extends Event { - public String typeName = ""; - public int typeColor = -1; - - public String teacherFullName = ""; - - public String subjectLongName = ""; - public String subjectShortName = ""; - - public String teamName = ""; - public String teamCode = null; - - // metadata - public boolean seen; - public boolean notified; - public long addedDate; - - public EventFull() {} - - public EventFull(Event event) { - super( - event.profileId, - event.id, - event.eventDate.clone(), - event.startTime == null ? null : event.startTime.clone(), - event.topic, - event.color, - event.type, - event.addedManually, - event.teacherId, - event.subjectId, - event.teamId - ); - - this.sharedBy = event.sharedBy; - this.sharedByName = event.sharedByName; - this.blacklisted = event.blacklisted; - } - public EventFull(EventFull event) { - super( - event.profileId, - event.id, - event.eventDate.clone(), - event.startTime == null ? null : event.startTime.clone(), - event.topic, - event.color, - event.type, - event.addedManually, - event.teacherId, - event.subjectId, - event.teamId - ); - - this.sharedBy = event.sharedBy; - this.sharedByName = event.sharedByName; - this.blacklisted = event.blacklisted; - this.typeName = event.typeName; - this.typeColor = event.typeColor; - this.teacherFullName = event.teacherFullName; - this.subjectLongName = event.subjectLongName; - this.subjectShortName = event.subjectShortName; - this.teamName = event.teamName; - this.teamCode = event.teamCode; - this.seen = event.seen; - this.notified = event.notified; - this.addedDate = event.addedDate; - } - - public EventFull(Event event, Metadata metadata) { - this(event); - - this.seen = metadata.seen; - this.notified = metadata.notified; - this.addedDate = metadata.addedDate; - } - - public int getColor() { - return color == -1 ? typeColor : color; - } - - @Override - public String toString() { - return "EventFull{" + - "profileId=" + profileId + - ", id=" + id + - ", eventDate=" + eventDate + - ", startTime=" + startTime + - ", topic='" + topic + '\'' + - ", color=" + color + - ", type=" + type + - ", addedManually=" + addedManually + - ", sharedBy='" + sharedBy + '\'' + - ", sharedByName='" + sharedByName + '\'' + - ", blacklisted=" + blacklisted + - ", teacherId=" + teacherId + - ", subjectId=" + subjectId + - ", teamId=" + teamId + - ", typeName='" + typeName + '\'' + - ", teacherFullName='" + teacherFullName + '\'' + - ", subjectLongName='" + subjectLongName + '\'' + - ", subjectShortName='" + subjectShortName + '\'' + - ", teamName='" + teamName + '\'' + - ", seen=" + seen + - ", notified=" + notified + - ", addedDate=" + addedDate + - '}'; - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/EventFull.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/EventFull.kt new file mode 100644 index 00000000..3eb681f2 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/EventFull.kt @@ -0,0 +1,121 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-25. + */ +package pl.szczodrzynski.edziennik.data.db.full + +import androidx.room.Ignore +import androidx.room.Relation +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.Note +import pl.szczodrzynski.edziennik.data.db.entity.Noteable +import pl.szczodrzynski.edziennik.ui.search.Searchable +import pl.szczodrzynski.edziennik.utils.html.BetterHtml +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time + +class EventFull( + profileId: Int, id: Long, date: Date, time: Time?, + topic: String, color: Int?, type: Long, + teacherId: Long, subjectId: Long, teamId: Long, addedDate: Long = System.currentTimeMillis() +) : Event( + profileId, id, date, time, + topic, color, type, + teacherId, subjectId, teamId, addedDate +), Searchable, Noteable { + constructor(event: Event, metadata: Metadata? = null) : this( + event.profileId, event.id, event.date, event.time, + event.topic, event.color, event.type, + event.teacherId, event.subjectId, event.teamId, event.addedDate) { + event.let { + addedManually = it.addedManually + sharedBy = it.sharedBy + sharedByName = it.sharedByName + blacklisted = it.blacklisted + isDownloaded = it.isDownloaded + homeworkBody = it.homeworkBody + attachmentIds = it.attachmentIds + attachmentNames = it.attachmentNames + } + metadata?.let { + seen = it.seen + notified = it.notified + } + } + + var typeName: String? = null + var typeColor: Int? = null + + var teacherName: String? = null + var subjectLongName: String? = null + var subjectShortName: String? = null + var teamName: String? = null + var teamCode: String? = null + + @delegate:Ignore + @delegate:Transient + val topicHtml by lazy { + BetterHtml.fromHtml(context = null, topic, nl2br = true) + } + + @delegate:Ignore + @delegate:Transient + val bodyHtml by lazy { + homeworkBody?.let { + BetterHtml.fromHtml(context = null, it, nl2br = true) + } + } + + @Ignore + @Transient + override var searchPriority = 0 + + @Ignore + @Transient + override var searchHighlightText: String? = null + + @delegate:Ignore + @delegate:Transient + override val searchKeywords by lazy { + listOf( + listOf(topicHtml.toString(), bodyHtml?.toString()), + attachmentNames, + listOf(subjectLongName), + listOf(teacherName), + listOf(sharedByName), + ) + } + + override fun compareTo(other: Searchable<*>): Int { + if (other !is EventFull) + return 0 + return when { + // ascending sorting + searchPriority > other.searchPriority -> 1 + searchPriority < other.searchPriority -> -1 + // ascending sorting + date > other.date -> 1 + date < other.date -> -1 + // ascending sorting + (time?.value ?: 0) > (other.time?.value ?: 0) -> 1 + (time?.value ?: 0) < (other.time?.value ?: 0) -> -1 + // ascending sorting + addedDate > other.addedDate -> 1 + addedDate < other.addedDate -> -1 + else -> 0 + } + } + + // metadata + var seen = false + var notified = false + + val eventColor + get() = color ?: typeColor ?: 0xff2196f3.toInt() + + @Relation(parentColumn = "eventId", entityColumn = "noteOwnerId", entity = Note::class) + override lateinit var notes: MutableList + override fun getNoteType() = Note.OwnerType.EVENT + override fun getNoteOwnerProfileId() = profileId + override fun getNoteOwnerId() = id +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/GradeFull.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/GradeFull.kt index 8cc80974..fc6e7f19 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/GradeFull.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/GradeFull.kt @@ -1,26 +1,35 @@ /* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 + * Copyright (c) Kuba Szczodrzyński 2020-4-24. */ package pl.szczodrzynski.edziennik.data.db.full +import androidx.room.Relation import pl.szczodrzynski.edziennik.data.db.entity.Grade +import pl.szczodrzynski.edziennik.data.db.entity.Note +import pl.szczodrzynski.edziennik.data.db.entity.Noteable class GradeFull( profileId: Int, id: Long, name: String, type: Int, value: Float, weight: Float, color: Int, category: String?, description: String?, comment: String?, - semester: Int, teacherId: Long, subjectId: Long + semester: Int, teacherId: Long, subjectId: Long, addedDate: Long = System.currentTimeMillis() ) : Grade( profileId, id, name, type, value, weight, color, category, description, comment, - semester, teacherId, subjectId -) { + semester, teacherId, subjectId, addedDate +), Noteable { + var teacherName: String? = null var subjectLongName: String? = null var subjectShortName: String? = null - var teacherFullName: String? = null + // metadata var seen = false var notified = false - var addedDate: Long = 0 + + @Relation(parentColumn = "gradeId", entityColumn = "noteOwnerId", entity = Note::class) + override lateinit var notes: MutableList + override fun getNoteType() = Note.OwnerType.GRADE + override fun getNoteOwnerProfileId() = profileId + override fun getNoteOwnerId() = id } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/LessonFull.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/LessonFull.kt index 5661a614..a2982a30 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/LessonFull.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/LessonFull.kt @@ -1,11 +1,21 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-25. + */ package pl.szczodrzynski.edziennik.data.db.full import android.content.Context +import androidx.room.Relation import pl.szczodrzynski.edziennik.R import pl.szczodrzynski.edziennik.data.db.entity.Lesson +import pl.szczodrzynski.edziennik.data.db.entity.Note +import pl.szczodrzynski.edziennik.data.db.entity.Noteable import pl.szczodrzynski.edziennik.utils.models.Time -class LessonFull(profileId: Int, id: Long) : Lesson(profileId, id) { +class LessonFull( + profileId: Int, id: Long +) : Lesson( + profileId, id +), Noteable { var subjectName: String? = null var teacherName: String? = null var teamName: String? = null @@ -126,5 +136,10 @@ class LessonFull(profileId: Int, id: Long) : Lesson(profileId, id) { // metadata var seen: Boolean = false var notified: Boolean = false - var addedDate: Long = 0 + + @Relation(parentColumn = "id", entityColumn = "noteOwnerId", entity = Note::class) + override lateinit var notes: MutableList + override fun getNoteType() = Note.OwnerType.LESSON + override fun getNoteOwnerProfileId() = profileId + override fun getNoteOwnerId() = id } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/LuckyNumberFull.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/LuckyNumberFull.java deleted file mode 100644 index d73cb95f..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/LuckyNumberFull.java +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.full; - -import pl.szczodrzynski.edziennik.data.db.entity.LuckyNumber; - -public class LuckyNumberFull extends LuckyNumber { - // metadata - public boolean seen; - public boolean notified; - public long addedDate; -} - diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/LuckyNumberFull.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/LuckyNumberFull.kt new file mode 100644 index 00000000..bb24724a --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/LuckyNumberFull.kt @@ -0,0 +1,19 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-25. + */ +package pl.szczodrzynski.edziennik.data.db.full + +import pl.szczodrzynski.edziennik.data.db.entity.LuckyNumber +import pl.szczodrzynski.edziennik.utils.models.Date + +class LuckyNumberFull( + profileId: Int, date: Date, + number: Int +) : LuckyNumber( + profileId, date, + number +) { + // metadata + var seen = false + var notified = false +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/MessageFull.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/MessageFull.java deleted file mode 100644 index be7ba692..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/MessageFull.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.full; - -import androidx.annotation.Nullable; -import androidx.room.Ignore; - -import java.util.ArrayList; -import java.util.List; - -import pl.szczodrzynski.edziennik.data.db.entity.Message; - -public class MessageFull extends Message { - public String senderFullName = null; - @Ignore - @Nullable - public List recipients = null; - - public MessageFull addRecipient(MessageRecipientFull recipient) { - if (recipients == null) - recipients = new ArrayList<>(); - recipients.add(recipient); - return this; - } - - // metadata - public boolean seen; - public boolean notified; - public long addedDate; -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/MessageFull.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/MessageFull.kt new file mode 100644 index 00000000..232095d8 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/MessageFull.kt @@ -0,0 +1,94 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-25. + */ +package pl.szczodrzynski.edziennik.data.db.full + +import androidx.room.Ignore +import androidx.room.Relation +import pl.szczodrzynski.edziennik.data.db.entity.Message +import pl.szczodrzynski.edziennik.data.db.entity.MessageRecipient +import pl.szczodrzynski.edziennik.data.db.entity.Note +import pl.szczodrzynski.edziennik.data.db.entity.Noteable +import pl.szczodrzynski.edziennik.ui.search.Searchable +import pl.szczodrzynski.edziennik.utils.html.BetterHtml + +class MessageFull( + profileId: Int, id: Long, type: Int, + subject: String, body: String?, senderId: Long?, + addedDate: Long = System.currentTimeMillis() +) : Message( + profileId, id, type, + subject, body, senderId, + addedDate +), Searchable, Noteable { + var senderName: String? = null + @Relation(parentColumn = "messageId", entityColumn = "messageId", entity = MessageRecipient::class) + var recipients: MutableList? = null + + fun addRecipient(recipient: MessageRecipientFull): MessageFull { + if (recipients == null) recipients = mutableListOf() + recipients?.add(recipient) + return this + } + + @delegate:Ignore + @delegate:Transient + val bodyHtml by lazy { + body?.let { + BetterHtml.fromHtml(context = null, it) + } + } + + @Ignore + @Transient + override var searchPriority = 0 + + @Ignore + @Transient + override var searchHighlightText: String? = null + + @delegate:Ignore + @delegate:Transient + override val searchKeywords by lazy { + listOf( + when { + isSent -> recipients?.map { it.fullName } + else -> listOf(senderName) + }, + listOf(subject), + listOf(bodyHtml?.toString()), + attachmentNames, + ) + } + + override fun compareTo(other: Searchable<*>): Int { + if (other !is MessageFull) + return 0 + return when { + // ascending sorting + searchPriority > other.searchPriority -> 1 + searchPriority < other.searchPriority -> -1 + // descending sorting (1. true, 2. false) + isStarred && !other.isStarred -> -1 + !isStarred && other.isStarred -> 1 + // descending sorting + addedDate > other.addedDate -> -1 + addedDate < other.addedDate -> 1 + else -> 0 + } + } + + @Ignore + @Transient + var readByEveryone = true + + // metadata + var seen = false + var notified = false + + @Relation(parentColumn = "messageId", entityColumn = "noteOwnerId", entity = Note::class) + override lateinit var notes: MutableList + override fun getNoteType() = Note.OwnerType.MESSAGE + override fun getNoteOwnerProfileId() = profileId + override fun getNoteOwnerId() = id +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/MessageRecipientFull.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/MessageRecipientFull.kt index 7f72245e..2126f872 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/MessageRecipientFull.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/MessageRecipientFull.kt @@ -2,17 +2,13 @@ package pl.szczodrzynski.edziennik.data.db.full import androidx.room.Ignore import pl.szczodrzynski.edziennik.data.db.entity.MessageRecipient -import pl.szczodrzynski.edziennik.fixName - -class MessageRecipientFull : MessageRecipient { - var fullName: String? = "" - get() { - return field?.fixName() ?: "" - } +class MessageRecipientFull( + profileId: Int, + id: Long, + messageId: Long, + readDate: Long = -1L +) : MessageRecipient(profileId, id, -1, readDate, messageId) { @Ignore - constructor(profileId: Int, id: Long, replyId: Long, readDate: Long, messageId: Long) : super(profileId, id, replyId, readDate, messageId) {} - @Ignore - constructor(profileId: Int, id: Long, messageId: Long) : super(profileId, id, messageId) {} - constructor() : super() {} + var fullName: String? = null } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/NoticeFull.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/NoticeFull.java deleted file mode 100644 index 372650fd..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/NoticeFull.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) Kacper Ziubryniewicz 2020-1-6 - */ - -package pl.szczodrzynski.edziennik.data.db.full; - -import pl.szczodrzynski.edziennik.data.db.entity.Notice; - -public class NoticeFull extends Notice { - public String teacherFullName = ""; - - // metadata - public boolean seen; - public boolean notified; - public long addedDate; -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/NoticeFull.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/NoticeFull.kt new file mode 100644 index 00000000..6f8d6fb0 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/NoticeFull.kt @@ -0,0 +1,31 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-25. + */ +package pl.szczodrzynski.edziennik.data.db.full + +import androidx.room.Relation +import pl.szczodrzynski.edziennik.data.db.entity.Note +import pl.szczodrzynski.edziennik.data.db.entity.Noteable +import pl.szczodrzynski.edziennik.data.db.entity.Notice + +class NoticeFull( + profileId: Int, id: Long, type: Int, semester: Int, + text: String, category: String?, points: Float?, + teacherId: Long, addedDate: Long = System.currentTimeMillis() +) : Notice( + profileId, id, type, semester, + text, category, points, + teacherId, addedDate +), Noteable { + var teacherName: String? = null + + // metadata + var seen = false + var notified = false + + @Relation(parentColumn = "noticeId", entityColumn = "noteOwnerId", entity = Note::class) + override lateinit var notes: MutableList + override fun getNoteType() = Note.OwnerType.BEHAVIOR + override fun getNoteOwnerProfileId() = profileId + override fun getNoteOwnerId() = id +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/TeacherAbsenceFull.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/TeacherAbsenceFull.kt index e9d53a59..39a88e0f 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/TeacherAbsenceFull.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/full/TeacherAbsenceFull.kt @@ -1,17 +1,24 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-25. + */ package pl.szczodrzynski.edziennik.data.db.full import pl.szczodrzynski.edziennik.data.db.entity.TeacherAbsence import pl.szczodrzynski.edziennik.utils.models.Date import pl.szczodrzynski.edziennik.utils.models.Time -class TeacherAbsenceFull(profileId: Int, id: Long, teacherId: Long, type: Long, name: String?, - dateFrom: Date, dateTo: Date, timeFrom: Time?, timeTo: Time?) - : TeacherAbsence(profileId, id, teacherId, type, name, dateFrom, dateTo, timeFrom, timeTo) { - - var teacherFullName = "" +class TeacherAbsenceFull( + profileId: Int, id: Long, type: Long, name: String?, + dateFrom: Date, dateTo: Date, timeFrom: Time?, timeTo: Time?, + teacherId: Long, addedDate: Long = System.currentTimeMillis() +) : TeacherAbsence( + profileId, id, type, name, + dateFrom, dateTo, timeFrom, timeTo, + teacherId, addedDate +) { + var teacherName: String? = null // metadata var seen: Boolean = false var notified: Boolean = false - var addedDate: Long = 0 } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration72.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration72.kt index 88567b47..65f9c4ce 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration72.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration72.kt @@ -6,7 +6,7 @@ package pl.szczodrzynski.edziennik.data.db.migration import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase -import pl.szczodrzynski.edziennik.crc32 +import pl.szczodrzynski.edziennik.ext.crc32 class Migration72 : Migration(71, 72) { override fun migrate(database: SupportSQLiteDatabase) { diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration80.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration80.kt new file mode 100644 index 00000000..86394792 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration80.kt @@ -0,0 +1,48 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-3-27. + */ + +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +class Migration80 : Migration(79, 80) { + override fun migrate(database: SupportSQLiteDatabase) { + // The Homework Update + database.execSQL("ALTER TABLE events RENAME TO _events;") + database.execSQL("""CREATE TABLE events ( + 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, + eventAddedManually INTEGER NOT NULL DEFAULT 0, + eventSharedBy TEXT DEFAULT NULL, + eventSharedByName TEXT DEFAULT NULL, + eventBlacklisted INTEGER NOT NULL DEFAULT 0, + homeworkBody TEXT DEFAULT NULL, + attachmentIds TEXT DEFAULT NULL, + attachmentNames TEXT DEFAULT NULL, + PRIMARY KEY(profileId, eventId) + )""") + database.execSQL("DROP INDEX IF EXISTS index_events_profileId_eventDate_eventStartTime") + database.execSQL("DROP INDEX IF EXISTS index_events_profileId_eventType") + database.execSQL("CREATE INDEX index_events_profileId_eventDate_eventTime ON events (profileId, eventDate, eventTime)") + database.execSQL("CREATE INDEX index_events_profileId_eventType ON events (profileId, eventType)") + database.execSQL(""" + INSERT INTO events (profileId, eventId, eventDate, eventTime, eventTopic, eventColor, eventType, teacherId, subjectId, teamId, eventAddedManually, eventSharedBy, eventSharedByName, eventBlacklisted) + SELECT profileId, eventId, eventDate, eventStartTime, eventTopic, + CASE eventColor WHEN -1 THEN NULL ELSE eventColor END, + eventType, teacherId, subjectId, teamId, + eventAddedManually, eventSharedBy, eventSharedByName, eventBlacklisted + FROM _events + """) + database.execSQL("DROP TABLE _events") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration81.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration81.kt new file mode 100644 index 00000000..bf547244 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration81.kt @@ -0,0 +1,11 @@ +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase +import pl.szczodrzynski.edziennik.data.db.entity.Metadata + +class Migration81 : Migration(80, 81) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("UPDATE metadata SET seen = 1, notified = 1 WHERE thingType = ${Metadata.TYPE_TEACHER_ABSENCE}") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration82.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration82.kt new file mode 100644 index 00000000..b0e1c769 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration82.kt @@ -0,0 +1,10 @@ +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +class Migration82 : Migration(81, 82) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("ALTER TABLE events ADD COLUMN eventIsDone INTEGER DEFAULT 0 NOT NULL") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration83.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration83.kt new file mode 100644 index 00000000..340d5768 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration83.kt @@ -0,0 +1,14 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-3-30. + */ + +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +class Migration83 : Migration(82, 83) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("ALTER TABLE events ADD COLUMN keep INTEGER NOT NULL DEFAULT 1") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration84.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration84.kt new file mode 100644 index 00000000..67ae8dbc --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration84.kt @@ -0,0 +1,40 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-4. + */ + +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +class Migration84 : Migration(83, 84) { + override fun migrate(database: SupportSQLiteDatabase) { + // The Message Update + database.execSQL("ALTER TABLE messages RENAME TO _messages;") + database.execSQL("""CREATE TABLE messages ( + profileId INTEGER NOT NULL, + messageId INTEGER NOT NULL, + messageType INTEGER NOT NULL, + messageSubject TEXT NOT NULL, + messageBody TEXT, + senderId INTEGER, + messageIsPinned INTEGER NOT NULL DEFAULT 0, + hasAttachments INTEGER NOT NULL DEFAULT 0, + attachmentIds TEXT DEFAULT NULL, + attachmentNames TEXT DEFAULT NULL, + attachmentSizes TEXT DEFAULT NULL, + keep INTEGER NOT NULL DEFAULT 1, + PRIMARY KEY(profileId, messageId) + )""") + database.execSQL("DROP INDEX IF EXISTS index_messages_profileId") + database.execSQL("CREATE INDEX index_messages_profileId_messageType ON messages (profileId, messageType)") + database.execSQL(""" + INSERT INTO messages (profileId, messageId, messageType, messageSubject, messageBody, senderId, hasAttachments, attachmentIds, attachmentNames, attachmentSizes) + SELECT profileId, messageId, messageType, messageSubject, messageBody, + CASE senderId WHEN -1 THEN NULL ELSE senderId END, + overrideHasAttachments, attachmentIds, attachmentNames, attachmentSizes + FROM _messages + """) + database.execSQL("DROP TABLE _messages") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration85.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration85.kt new file mode 100644 index 00000000..6f1c79c0 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration85.kt @@ -0,0 +1,12 @@ +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase +import pl.szczodrzynski.edziennik.data.api.LOGIN_TYPE_EDUDZIENNIK +import pl.szczodrzynski.edziennik.data.db.entity.Event + +class Migration85 : Migration(84, 85) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("DELETE FROM events WHERE eventAddedManually = 0 AND eventType = ${Event.TYPE_HOMEWORK} AND profileId IN (SELECT profileId FROM (SELECT profileId FROM profiles WHERE loginStoreType = $LOGIN_TYPE_EDUDZIENNIK) x)") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration86.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration86.kt new file mode 100644 index 00000000..add43d71 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration86.kt @@ -0,0 +1,178 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-29. + */ + +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +class Migration86 : Migration(85, 86) { + override fun migrate(database: SupportSQLiteDatabase) { + // Migrating some models, moving addedDate from metadata to entities + + // Announcements + database.execSQL("""ALTER TABLE announcements RENAME TO _announcements""") + database.execSQL("""CREATE TABLE `announcements` ( + `announcementIdString` TEXT, + `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, + `keep` INTEGER NOT NULL, + PRIMARY KEY(`profileId`, `announcementId`) + )""") + database.execSQL("""DROP INDEX IF EXISTS index_announcements_profileId""") + database.execSQL("""CREATE INDEX `index_announcements_profileId` ON `announcements` (`profileId`)""") + database.execSQL("""REPLACE INTO announcements ( + announcementIdString, profileId, announcementId, announcementSubject, announcementText, announcementStartDate, announcementEndDate, teacherId, addedDate, keep + ) SELECT + announcementIdString, profileId, announcementId, IFNULL(announcementSubject, ""), announcementText, announcementStartDate, announcementEndDate, teacherId, 0, 1 + FROM _announcements""") + database.execSQL("""DROP TABLE _announcements""") + + // Attendance Types + database.execSQL("""ALTER TABLE attendanceTypes RENAME TO _attendanceTypes""") + database.execSQL("""CREATE TABLE `attendanceTypes` ( + `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`) + )""") + database.execSQL("""REPLACE INTO attendanceTypes ( + profileId, id, + baseType, + typeName, + typeShort, + typeSymbol, + typeColor + ) SELECT + profileId, id, + CASE WHEN id > 100 AND type = 0 THEN 10 ELSE type END, + name, + CASE type WHEN 0 THEN "ob" WHEN 1 THEN "nb" WHEN 2 THEN "u" WHEN 3 THEN "zw" WHEN 4 THEN "sp" WHEN 5 THEN "su" WHEN 6 THEN "w" ELSE "?" END, + CASE type WHEN 0 THEN "ob" WHEN 1 THEN "nb" WHEN 2 THEN "u" WHEN 3 THEN "zw" WHEN 4 THEN "sp" WHEN 5 THEN "su" WHEN 6 THEN "w" ELSE "?" END, + CASE color WHEN -1 THEN NULL ELSE color END + FROM _attendanceTypes""") + database.execSQL("""DROP TABLE _attendanceTypes""") + + // Attendance + database.execSQL("""ALTER TABLE attendances RENAME TO _attendances""") + database.execSQL("""CREATE TABLE `attendances` ( + `attendanceLessonTopic` TEXT, + `attendanceLessonNumber` INTEGER, + `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, + `keep` INTEGER NOT NULL, + PRIMARY KEY(`profileId`, `attendanceId`) + )""") + database.execSQL("""DROP INDEX IF EXISTS index_attendances_profileId""") + database.execSQL("""CREATE INDEX `index_attendances_profileId` ON `attendances` (`profileId`)""") + database.execSQL("""REPLACE INTO attendances ( + attendanceLessonTopic, attendanceLessonNumber, profileId, attendanceId, + attendanceBaseType, + attendanceTypeName, + attendanceTypeShort, + attendanceTypeSymbol, + attendanceTypeColor, attendanceDate, attendanceTime, attendanceSemester, teacherId, subjectId, addedDate, keep + ) SELECT + attendanceLessonTopic, NULL, profileId, attendanceId, + attendanceType, + CASE attendanceType WHEN 0 THEN "ob" WHEN 1 THEN "nb" WHEN 2 THEN "u" WHEN 3 THEN "zw" WHEN 4 THEN "sp" WHEN 5 THEN "su" WHEN 6 THEN "w" ELSE "?" END, + CASE attendanceType WHEN 0 THEN "ob" WHEN 1 THEN "nb" WHEN 2 THEN "u" WHEN 3 THEN "zw" WHEN 4 THEN "sp" WHEN 5 THEN "su" WHEN 6 THEN "w" ELSE "?" END, + CASE attendanceType WHEN 0 THEN "ob" WHEN 1 THEN "nb" WHEN 2 THEN "u" WHEN 3 THEN "zw" WHEN 4 THEN "sp" WHEN 5 THEN "su" WHEN 6 THEN "w" ELSE "?" END, + NULL, attendanceLessonDate, attendanceStartTime, attendanceSemester, teacherId, subjectId, 0, 1 + FROM _attendances""") + database.execSQL("""DROP TABLE _attendances""") + + // Events + database.execSQL("""ALTER TABLE events ADD COLUMN addedDate INTEGER NOT NULL DEFAULT 0""") + + // Grades + database.execSQL("""ALTER TABLE grades ADD COLUMN addedDate INTEGER NOT NULL DEFAULT 0""") + database.execSQL("""ALTER TABLE grades ADD COLUMN keep INTEGER NOT NULL DEFAULT 1""") + + // Lucky Numbers + database.execSQL("""ALTER TABLE luckyNumbers ADD COLUMN keep INTEGER NOT NULL DEFAULT 1""") + + // Messages + database.execSQL("""ALTER TABLE messages ADD COLUMN addedDate INTEGER NOT NULL DEFAULT 0""") + + // Notices + database.execSQL("""ALTER TABLE notices RENAME TO _notices""") + database.execSQL("""CREATE TABLE `notices` ( + `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`) + )""") + database.execSQL("""DROP INDEX IF EXISTS index_notices_profileId""") + database.execSQL("""CREATE INDEX `index_notices_profileId` ON `notices` (`profileId`)""") + database.execSQL("""REPLACE INTO notices ( + profileId, noticeId, noticeType, noticeSemester, + noticeText, + noticeCategory, + noticePoints, + teacherId, addedDate, keep + ) SELECT + profileId, noticeId, noticeType, noticeSemester, + CASE noticeText WHEN NULL THEN "" ELSE noticeText END, + category, + CASE points WHEN 0 THEN NULL ELSE points END, + teacherId, 0, 1 + FROM _notices""") + database.execSQL("""DROP TABLE _notices""") + + // Teacher Absence + database.execSQL("""ALTER TABLE teacherAbsence ADD COLUMN addedDate INTEGER NOT NULL DEFAULT 0""") + database.execSQL("""ALTER TABLE teacherAbsence ADD COLUMN keep INTEGER NOT NULL DEFAULT 1""") + database.execSQL("""CREATE INDEX IF NOT EXISTS `index_teacherAbsence_profileId` ON `teacherAbsence` (`profileId`)""") + + // Timetable + database.execSQL("""ALTER TABLE timetable ADD COLUMN keep INTEGER NOT NULL DEFAULT 1""") + + // Metadata - copy AddedDate to entities + database.execSQL("""UPDATE grades SET addedDate = IFNULL((SELECT metadata.addedDate FROM metadata WHERE metadata.profileId = grades.profileId AND metadata.thingId = grades.gradeId AND metadata.thingType = 1), 0)""") + database.execSQL("""UPDATE notices SET addedDate = IFNULL((SELECT metadata.addedDate FROM metadata WHERE metadata.profileId = notices.profileId AND metadata.thingId = notices.noticeId AND metadata.thingType = 2), 0)""") + database.execSQL("""UPDATE attendances SET addedDate = IFNULL((SELECT metadata.addedDate FROM metadata WHERE metadata.profileId = attendances.profileId AND metadata.thingId = attendances.attendanceId AND metadata.thingType = 3), 0)""") + database.execSQL("""UPDATE events SET addedDate = IFNULL((SELECT metadata.addedDate FROM metadata WHERE metadata.profileId = events.profileId AND metadata.thingId = events.eventId AND (metadata.thingType = 4 OR metadata.thingType = 5)), 0)""") + database.execSQL("""UPDATE announcements SET addedDate = IFNULL((SELECT metadata.addedDate FROM metadata WHERE metadata.profileId = announcements.profileId AND metadata.thingId = announcements.announcementId AND metadata.thingType = 7), 0)""") + database.execSQL("""UPDATE messages SET addedDate = IFNULL((SELECT metadata.addedDate FROM metadata WHERE metadata.profileId = messages.profileId AND metadata.thingId = messages.messageId AND metadata.thingType = 8), 0)""") + + // Metadata - drop AddedDate column + database.execSQL("""ALTER TABLE metadata RENAME TO _metadata""") + database.execSQL("""CREATE TABLE metadata (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)""") + database.execSQL("""DROP INDEX IF EXISTS index_metadata_profileId_thingType_thingId""") + database.execSQL("""CREATE UNIQUE INDEX index_metadata_profileId_thingType_thingId ON "metadata" (profileId, thingType, thingId)""") + database.execSQL("""INSERT INTO metadata (profileId, metadataId, thingType, thingId, seen, notified) SELECT profileId, metadataId, thingType, thingId, seen, notified FROM _metadata""") + database.execSQL("""DROP TABLE _metadata""") + + database.execSQL("""DELETE FROM endpointTimers WHERE endpointId IN (1080, 1081, 2050, 1090, 1010, 1014);""") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration87.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration87.kt new file mode 100644 index 00000000..524cb559 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration87.kt @@ -0,0 +1,14 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-5-8. + */ + +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +class Migration87 : Migration(86, 87) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("ALTER TABLE attendances ADD COLUMN attendanceIsCounted INTEGER NOT NULL DEFAULT 1") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration88.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration88.kt new file mode 100644 index 00000000..0dcd2f8c --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration88.kt @@ -0,0 +1,15 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-5-9. + */ + +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +class Migration88 : Migration(87, 88) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("UPDATE endpointTimers SET endpointLastSync = 0 WHERE endpointId IN (1030, 1040, 1050, 1060, 1070, 1080);") + database.execSQL("UPDATE profiles SET empty = 1 WHERE loginStoreType = 4") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration89.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration89.kt new file mode 100644 index 00000000..ce665d1f --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration89.kt @@ -0,0 +1,10 @@ +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +class Migration89 : Migration(88, 89) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("ALTER TABLE profiles ADD COLUMN archiveId INTEGER DEFAULT NULL;") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration90.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration90.kt new file mode 100644 index 00000000..7b500525 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration90.kt @@ -0,0 +1,30 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-26. + */ + +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +class Migration90 : Migration(89, 90) { + override fun migrate(database: SupportSQLiteDatabase) { + // get all profiles using Vulcan/Hebe + database.execSQL("CREATE TABLE _90_ids (id INTEGER NOT NULL);") + database.execSQL("INSERT INTO _90_ids SELECT profileId FROM profiles JOIN loginStores USING(loginStoreId) WHERE loginStores.loginStoreType = 4 AND loginStores.loginStoreMode != 0;") + + // force full sync when updating from <4.6 + database.execSQL("DELETE FROM endpointTimers WHERE profileId IN (SELECT id FROM _90_ids);") + database.execSQL("UPDATE profiles SET empty = 1 WHERE profileId IN (SELECT id FROM _90_ids);") + // remove messages and events to re-download attachments and remove older than current school year + database.execSQL("DELETE FROM messages WHERE profileId IN (SELECT id FROM _90_ids);") + database.execSQL("DELETE FROM events WHERE profileId IN (SELECT id FROM _90_ids) AND eventAddedManually = 0;") + // remove older data + database.execSQL("DELETE FROM notices WHERE profileId IN (SELECT id FROM _90_ids);") + + // fix for v4.5 users who logged in using Vulcan/Web + database.execSQL("UPDATE loginStores SET loginStoreMode = 2 WHERE loginStoreType = 4 AND loginStoreMode = 1;") + + database.execSQL("DROP TABLE _90_ids;") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration91.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration91.kt new file mode 100644 index 00000000..ffb8b093 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration91.kt @@ -0,0 +1,25 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-2-26. + */ + +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +class Migration91 : Migration(90, 91) { + override fun migrate(database: SupportSQLiteDatabase) { + // get all profiles using Vulcan/Hebe + database.execSQL("CREATE TABLE _91_ids (id INTEGER NOT NULL);") + database.execSQL("INSERT INTO _91_ids SELECT profileId FROM profiles JOIN loginStores USING(loginStoreId) WHERE loginStores.loginStoreType = 1;") + + // force attendance sync - mobidziennik + // after enabling counting the e-attendance to statistics + database.execSQL("DELETE FROM endpointTimers WHERE profileId IN (SELECT id FROM _91_ids) AND endpointId = 2050;") + database.execSQL("UPDATE attendances SET attendanceIsCounted = 1 WHERE profileId IN (SELECT id FROM _91_ids);") + database.execSQL("UPDATE attendances SET attendanceBaseType = 2 WHERE profileId IN (SELECT id FROM _91_ids) AND attendanceTypeSymbol = ?;", + arrayOf("+ₑ")) + + database.execSQL("DROP TABLE _91_ids;") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration92.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration92.kt new file mode 100644 index 00000000..3010a371 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration92.kt @@ -0,0 +1,60 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-4-15. + */ + +package pl.szczodrzynski.edziennik.data.db.migration + +import android.content.ContentValues +import android.database.sqlite.SQLiteDatabase +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.COLOR_ELEARNING +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.TYPE_ELEARNING +import pl.szczodrzynski.edziennik.data.db.entity.Event.Companion.TYPE_INFORMATION +import pl.szczodrzynski.edziennik.data.db.entity.EventType.Companion.SOURCE_DEFAULT +import pl.szczodrzynski.edziennik.data.db.entity.EventType.Companion.SOURCE_REGISTER +import pl.szczodrzynski.edziennik.ext.getInt + +class Migration92 : Migration(91, 92) { + override fun migrate(database: SupportSQLiteDatabase) { + // make eventTypeName not nullable + database.execSQL("ALTER TABLE eventTypes RENAME TO _eventTypes;") + database.execSQL("CREATE TABLE eventTypes (" + + "profileId INTEGER NOT NULL, " + + "eventType INTEGER NOT NULL, " + + "eventTypeName TEXT NOT NULL, " + + "eventTypeColor INTEGER NOT NULL, " + + "PRIMARY KEY(profileId,eventType)" + + ");") + database.execSQL("INSERT INTO eventTypes " + + "(profileId, eventType, eventTypeName, eventTypeColor) " + + "SELECT profileId, eventType, eventTypeName, eventTypeColor " + + "FROM _eventTypes;") + database.execSQL("DROP TABLE _eventTypes;") + + // add columns for order and source + database.execSQL("ALTER TABLE eventTypes ADD COLUMN eventTypeOrder INTEGER NOT NULL DEFAULT 0;") + database.execSQL("ALTER TABLE eventTypes ADD COLUMN eventTypeSource INTEGER NOT NULL DEFAULT 0;") + + // migrate existing types to show correct order and source + database.execSQL("UPDATE eventTypes SET eventTypeOrder = eventType + 102;") + database.execSQL("UPDATE eventTypes SET eventTypeSource = $SOURCE_REGISTER WHERE eventType > $TYPE_INFORMATION;") + + // add new e-learning type + val cursor = database.query("SELECT profileId FROM profiles;") + cursor.use { + while (it.moveToNext()) { + val values = ContentValues().apply { + put("profileId", it.getInt("profileId")) + put("eventType", TYPE_ELEARNING) + put("eventTypeName", "lekcja online") + put("eventTypeColor", COLOR_ELEARNING) + put("eventTypeOrder", 100) + put("eventTypeSource", SOURCE_DEFAULT) + } + + database.insert("eventTypes", SQLiteDatabase.CONFLICT_REPLACE, values) + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration93.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration93.kt new file mode 100644 index 00000000..9d5df5b3 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration93.kt @@ -0,0 +1,15 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-5-26. + */ + +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +class Migration93 : Migration(92, 93) { + override fun migrate(database: SupportSQLiteDatabase) { + // notifications - long text + database.execSQL("ALTER TABLE notifications ADD COLUMN textLong TEXT DEFAULT NULL;") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration94.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration94.kt new file mode 100644 index 00000000..84df9c59 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration94.kt @@ -0,0 +1,26 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-1. + */ + +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase +import pl.szczodrzynski.edziennik.data.db.entity.Event +import pl.szczodrzynski.edziennik.data.db.entity.LoginStore + +class Migration94 : Migration(93, 94) { + override fun migrate(database: SupportSQLiteDatabase) { + // events - is downloaded flag + + // get all profiles using Mobidziennik + database.execSQL("CREATE TABLE _94_ids (id INTEGER NOT NULL);") + database.execSQL("INSERT INTO _94_ids SELECT profileId FROM profiles JOIN loginStores USING(loginStoreId) WHERE loginStores.loginStoreType = ${LoginStore.LOGIN_TYPE_MOBIDZIENNIK};") + + database.execSQL("ALTER TABLE events ADD COLUMN eventIsDownloaded INT NOT NULL DEFAULT 1;") + // set isDownloaded = 0 for information events in Mobidziennik + database.execSQL("UPDATE events SET eventIsDownloaded = 0 WHERE profileId IN (SELECT id FROM _94_ids) AND eventType = ${Event.TYPE_INFORMATION};") + + database.execSQL("DROP TABLE _94_ids;") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration95.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration95.kt new file mode 100644 index 00000000..0281de6b --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration95.kt @@ -0,0 +1,15 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-1. + */ + +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +class Migration95 : Migration(94, 95) { + override fun migrate(database: SupportSQLiteDatabase) { + // timetable - is extra flag + database.execSQL("ALTER TABLE timetable ADD COLUMN isExtra INT NOT NULL DEFAULT 0;") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration96.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration96.kt new file mode 100644 index 00000000..e8315aa3 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration96.kt @@ -0,0 +1,15 @@ +/* + * Copyright (c) Antoni Czaplicki 2021-10-17. + */ + +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +class Migration96 : Migration(95, 96) { + override fun migrate(database: SupportSQLiteDatabase) { + // teachers - associated subjects list + database.execSQL("ALTER TABLE teachers ADD COLUMN teacherSubjects TEXT NOT NULL DEFAULT '[]';") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration97.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration97.kt new file mode 100644 index 00000000..13014ecb --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration97.kt @@ -0,0 +1,29 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-16. + */ + +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +class Migration97 : Migration(96, 97) { + override fun migrate(database: SupportSQLiteDatabase) { + // notes + database.execSQL("""CREATE TABLE notes ( + 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) + );""") + database.execSQL("CREATE INDEX IF NOT EXISTS index_notes_profileId_noteOwnerType_noteOwnerId ON notes (profileId, noteOwnerType, noteOwnerId);") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration98.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration98.kt new file mode 100644 index 00000000..91003fd9 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/db/migration/Migration98.kt @@ -0,0 +1,15 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2022-10-16. + */ + +package pl.szczodrzynski.edziennik.data.db.migration + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +class Migration98 : Migration(97, 98) { + override fun migrate(database: SupportSQLiteDatabase) { + // timetable colors - override color in lesson object + database.execSQL("ALTER TABLE timetable ADD COLUMN color INT DEFAULT NULL;") + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/FirebaseBroadcastReceiver.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/FirebaseBroadcastReceiver.kt deleted file mode 100644 index 25c2de48..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/FirebaseBroadcastReceiver.kt +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2020-1-11. - */ - -package pl.szczodrzynski.edziennik.data.firebase - -import android.content.Context -import android.content.Intent -import android.util.Log -import androidx.legacy.content.WakefulBroadcastReceiver -import com.google.gson.JsonObject - -class FirebaseBroadcastReceiver : WakefulBroadcastReceiver() { - companion object { - private const val TAG = "FirebaseBroadcast" - } - - override fun onReceive(context: Context, intent: Intent) { - val extras = intent.extras - val json = JsonObject() - extras?.keySet()?.forEach { key -> - extras.get(key)?.let { - when (it) { - is String -> json.addProperty(key, it) - is Int -> json.addProperty(key, it) - is Long -> json.addProperty(key, it) - is Float -> json.addProperty(key, it) - is Boolean -> json.addProperty(key, it) - else -> json.addProperty(key, it.toString()) - } - } - } - Log.d(TAG, "Intent(action=${intent?.action}, extras=$json)") - } -} \ No newline at end of file diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/FirebaseService.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/FirebaseService.kt index 6396a87c..80dcd4ea 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/FirebaseService.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/FirebaseService.kt @@ -13,7 +13,7 @@ import com.google.firebase.iid.zzad import com.google.firebase.iid.zzaz import com.google.firebase.messaging.zzc import com.google.gson.JsonObject -import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.ext.* import java.util.* import com.google.firebase.messaging.zzo.zza as logNotificationOpen import com.google.firebase.messaging.zzo.zza as logNotificationReceived diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/MyFirebaseMessagingService.java b/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/MyFirebaseMessagingService.java deleted file mode 100644 index 34e341ed..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/MyFirebaseMessagingService.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2020-1-11. - */ - -package pl.szczodrzynski.edziennik.data.firebase; - -import android.content.Context; -import android.content.SharedPreferences; -import android.os.AsyncTask; - -import com.google.firebase.messaging.FirebaseMessagingService; -import com.google.firebase.messaging.RemoteMessage; - -import java.util.List; - -import pl.szczodrzynski.edziennik.App; -import pl.szczodrzynski.edziennik.data.api.edziennik.EdziennikTask; -import pl.szczodrzynski.edziennik.data.db.entity.LoginStore; -import pl.szczodrzynski.edziennik.data.db.entity.Profile; - -import static pl.szczodrzynski.edziennik.utils.Utils.d; -import static pl.szczodrzynski.edziennik.utils.Utils.strToInt; - -public class MyFirebaseMessagingService extends FirebaseMessagingService { - private static final String TAG = "FirebaseMessaging"; - - @Override - public void onNewToken(String s) { - super.onNewToken(s); - - /* Log.d(TAG, "New token: "+s); - App app = (App)getApplicationContext(); - if (app.config.getSync().getTokenApp() == null || !app.config.getSync().getTokenApp().equals(s)) { - app.config.getSync().setTokenApp(s); - }*/ - } - - @Override - public void onMessageReceived(RemoteMessage remoteMessage) { - /*App app = ((App) getApplicationContext()); - // Not getting messages here? See why this may be: https://goo.gl/39bRNJ - - String from = remoteMessage.getFrom(); - if (from != null) { - switch (from) { - case "640759989760": - app.debugLog("Firebase got push from App "+remoteMessage.getData().toString()); - //processAppPush - processAppPush(app, remoteMessage); - break; - case "747285019373": - app.debugLog("Firebase got push from Mobidziennik "+remoteMessage.getData().toString()); - processMobidziennikPush(app, remoteMessage); - break; - case "513056078587": - app.debugLog("Firebase got push from Librus "+remoteMessage.getData().toString()); - processLibrusPush(app, remoteMessage); - break; - case "987828170337": - app.debugLog("Firebase got push from Vulcan "+remoteMessage.getData().toString()); - processVulcanPush(app, remoteMessage); - break; - } - }*/ - } - - private void processMobidziennikPush(App app, RemoteMessage remoteMessage) { - SharedPreferences sharedPreferences = getSharedPreferences("pushtest_mobidziennik", Context.MODE_PRIVATE); - sharedPreferences.edit().putString(Long.toString(System.currentTimeMillis()), remoteMessage.getData().toString()+"\n"+remoteMessage.toString()+"\n"+remoteMessage.getMessageType()).apply(); - String studentIdStr = remoteMessage.getData().get("id_ucznia"); - if (studentIdStr != null) { - int studentId = strToInt(studentIdStr); - AsyncTask.execute(() -> { - List profileList = app.db.profileDao().getAllNow(); - - Profile profile = null; - - for (Profile profileFull: profileList) { - if (profileFull.getLoginStoreType() == LoginStore.LOGIN_TYPE_MOBIDZIENNIK - && studentId == profileFull.getStudentData("studentId", -1)) { - profile = profileFull; - break; - } - } - - if (profile != null) { - if (remoteMessage.getData().get("id_wiadomosci") != null) { - - d(TAG, "Syncing profile " + profile.getId()); - EdziennikTask.Companion.syncProfile(profile.getId(), null, null, null).enqueue(app); - } else { - /*app.notifier.add(new Notification(app.getContext(), remoteMessage.getData().get("message")) - .withProfileData(profile.id, profile.name) - .withTitle(remoteMessage.getData().get("title")) - .withType(Notification.TYPE_SERVER_MESSAGE) - .withFragmentRedirect(MainActivity.DRAWER_ITEM_HOME) - ); - app.notifier.postAll(profile); - app.saveConfig("notifications");*/ - d(TAG, "Syncing profile " + profile.getId()); - EdziennikTask.Companion.syncProfile(profile.getId(), null, null, null).enqueue(app); - } - } - }); - } - } - - private void processLibrusPush(App app, RemoteMessage remoteMessage) { - SharedPreferences sharedPreferences = getSharedPreferences("pushtest_librus", Context.MODE_PRIVATE); - sharedPreferences.edit().putString(Long.toString(System.currentTimeMillis()), remoteMessage.getData().toString()+"\n"+remoteMessage.toString()+"\n"+remoteMessage.getMessageType()).apply(); - } - - private void processVulcanPush(App app, RemoteMessage remoteMessage) { - SharedPreferences sharedPreferences = getSharedPreferences("pushtest_vulcan", Context.MODE_PRIVATE); - sharedPreferences.edit().putString(Long.toString(System.currentTimeMillis()), remoteMessage.getData().toString()+"\n"+remoteMessage.toString()+"\n"+remoteMessage.getMessageType()).apply(); - } - - private void processAppPush(App app, RemoteMessage remoteMessage) { - // Check if message contains a data payload. - /*String type = remoteMessage.getData().get("type"); - if (remoteMessage.getData().size() > 0 - && type != null) { - //Log.d(TAG, "Message data payload: " + remoteMessage.sync()); - switch (type) { - case "app_update": - int versionCode = Integer.parseInt(remoteMessage.getData().get("update_version_code")); - if (BuildConfig.VERSION_CODE < versionCode) { - String updateVersion = remoteMessage.getData().get("update_version"); - String updateUrl = remoteMessage.getData().get("update_url"); - String updateFilename = remoteMessage.getData().get("update_filename"); - boolean updateMandatory = Boolean.parseBoolean(remoteMessage.getData().get("update_mandatory")); - boolean updateDirect = Boolean.parseBoolean(remoteMessage.getData().get("update_direct")); - - if (app.appConfig.updateVersion == null || !app.appConfig.updateVersion.equals(updateVersion)) { - app.appConfig.updateVersion = updateVersion; - app.appConfig.updateUrl = updateUrl; - app.appConfig.updateFilename = updateFilename; - app.appConfig.updateMandatory = updateMandatory; - app.appConfig.updateDirect = updateDirect; - app.saveConfig("updateVersion", "updateUrl", "updateFilename", "updateMandatory"); - } - if (!remoteMessage.getData().containsKey("update_silent")) { - app.notifier.notificationUpdatesShow( - updateVersion, - updateUrl, - updateFilename, - updateDirect); - } - } else { - if (app.appConfig.updateVersion == null || !app.appConfig.updateVersion.equals("")) { - app.appConfig.updateVersion = ""; - app.appConfig.updateMandatory = false; - app.saveConfig("updateVersion", "updateMandatory"); - } - app.notifier.notificationUpdatesHide(); - } - break; - case "message": - app.notifier.add(new Notification(app.getContext(), remoteMessage.getData().get("message")) - .withTitle(remoteMessage.getData().get("title")) - .withType(pl.szczodrzynski.edziennik.data.db.entity.Notification.TYPE_SERVER_MESSAGE) - .withFragmentRedirect(MainActivity.DRAWER_ITEM_NOTIFICATIONS) - ); - app.notifier.postAll(); - app.saveConfig("notifications"); - break; - case "feedback_message_from_dev": - AsyncTask.execute(() -> { - FeedbackMessage feedbackMessage = new FeedbackMessage(true, remoteMessage.getData().get("message")); - if (feedbackMessage.text.startsWith("test")) { - // todo - } - else { - feedbackMessage.sentTime = Long.parseLong(remoteMessage.getData().get("sent_time")); - if (feedbackMessage.text.startsWith("devmode")) { - app.config.setDevModePassword(feedbackMessage.text.replace("devmode", "")); - app.checkDevModePassword(); - feedbackMessage.text = "devmode "+(App.devMode ? "allowed" : "disallowed"); - } - Intent intent = new Intent("pl.szczodrzynski.edziennik.ui.modules.base.FeedbackActivity"); - intent.putExtra("type", "user_chat"); - intent.putExtra("message", app.gson.toJson(feedbackMessage)); - app.sendBroadcast(intent); - app.db.feedbackMessageDao().add(feedbackMessage); - - app.notifier.add(new Notification(app.getContext(), feedbackMessage.text) - .withTitle(remoteMessage.getData().get("title")) - .withType(pl.szczodrzynski.edziennik.data.db.entity.Notification.TYPE_FEEDBACK_MESSAGE) - .withFragmentRedirect(MainActivity.TARGET_FEEDBACK) - ); - app.notifier.postAll(); - app.saveConfig("notifications"); - } - }); - break; - case "feedback_message_from_user": - AsyncTask.execute(() -> { - FeedbackMessage feedbackMessage = new FeedbackMessage(true, remoteMessage.getData().get("message")); - feedbackMessage.fromUser = remoteMessage.getData().get("from_user"); - feedbackMessage.fromUserName = remoteMessage.getData().get("from_user_name"); - feedbackMessage.sentTime = Long.parseLong(remoteMessage.getData().get("sent_time")); - Intent intent = new Intent("pl.szczodrzynski.edziennik.ui.modules.base.FeedbackActivity"); - intent.putExtra("type", "user_chat"); - intent.putExtra("message", app.gson.toJson(feedbackMessage)); - app.sendBroadcast(intent); - app.db.feedbackMessageDao().add(feedbackMessage); - }); - app.notifier.add(new Notification(app.getContext(), remoteMessage.getData().get("message")) - .withTitle(remoteMessage.getData().get("title")) - .withType(pl.szczodrzynski.edziennik.data.db.entity.Notification.TYPE_FEEDBACK_MESSAGE) - .withFragmentRedirect(MainActivity.TARGET_FEEDBACK) - ); - app.notifier.postAll(); - app.saveConfig("notifications"); - break; - case "ping": - // just a ping - break - } - }*/ - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/SzkolnyAppFirebase.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/SzkolnyAppFirebase.kt index 78d03873..4f90ac67 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/SzkolnyAppFirebase.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/SzkolnyAppFirebase.kt @@ -5,13 +5,20 @@ package pl.szczodrzynski.edziennik.data.firebase import com.google.gson.JsonParser +import com.google.gson.reflect.TypeToken import kotlinx.coroutines.* import org.greenrobot.eventbus.EventBus import pl.szczodrzynski.edziennik.* import pl.szczodrzynski.edziennik.data.api.events.FeedbackMessageEvent +import pl.szczodrzynski.edziennik.data.api.events.RegisterAvailabilityEvent +import pl.szczodrzynski.edziennik.data.api.szkolny.response.RegisterAvailabilityStatus import pl.szczodrzynski.edziennik.data.api.szkolny.response.Update import pl.szczodrzynski.edziennik.data.api.task.PostNotifications import pl.szczodrzynski.edziennik.data.db.entity.* +import pl.szczodrzynski.edziennik.ext.getInt +import pl.szczodrzynski.edziennik.ext.getLong +import pl.szczodrzynski.edziennik.ext.getNotificationTitle +import pl.szczodrzynski.edziennik.ext.getString import pl.szczodrzynski.edziennik.sync.UpdateWorker import pl.szczodrzynski.edziennik.utils.models.Date import pl.szczodrzynski.edziennik.utils.models.Time @@ -40,6 +47,15 @@ class SzkolnyAppFirebase(val app: App, val profiles: List, val message: message.data.getLong("eventId") ?: return@run, message.data.getString("message") ?: return@run ) + "sharedNote" -> sharedNote( + message.data.getString("shareTeamCode") ?: return@run, + message.data.getString("note") ?: return@run, + message.data.getString("message") ?: return@run, + ) + "unsharedNote" -> unsharedNote( + message.data.getString("unshareTeamCode") ?: return@run, + message.data.getLong("noteId") ?: return@run, + ) "serverMessage", "unpairedBrowser" -> serverMessage( message.data.getString("title") ?: "", @@ -50,6 +66,16 @@ class SzkolnyAppFirebase(val app: App, val profiles: List, val message: val message = app.gson.fromJson(message.data.getString("message"), FeedbackMessage::class.java) ?: return@launch feedbackMessage(message) } + "registerAvailability" -> launch { + val data = app.gson.fromJson>( + message.data.getString("registerAvailability"), + object: TypeToken>(){}.type + ) ?: return@launch + app.config.sync.registerAvailability = data + if (EventBus.getDefault().hasSubscriberForEvent(RegisterAvailabilityEvent::class.java)) { + EventBus.getDefault().postSticky(RegisterAvailabilityEvent()) + } + } } } } @@ -91,7 +117,7 @@ class SzkolnyAppFirebase(val app: App, val profiles: List, val message: } private fun sharedEvent(teamCode: String, jsonStr: String, message: String) { - val json = JsonParser().parse(jsonStr).asJsonObject + val json = JsonParser.parseString(jsonStr).asJsonObject val teams = app.db.teamDao().allNow // not used, as the server provides a sharing message //val eventTypes = app.db.eventTypeDao().allNow @@ -102,39 +128,43 @@ class SzkolnyAppFirebase(val app: App, val profiles: List, val message: teams.filter { it.code == teamCode }.distinctBy { it.profileId }.forEach { team -> val profile = profiles.firstOrNull { it.id == team.profileId } ?: return@forEach - if (profile.registration != Profile.REGISTRATION_ENABLED) + if (!profile.canShare) return@forEach val event = Event( - team.profileId, - json.getLong("id") ?: return, - json.getInt("eventDate")?.let { Date.fromValue(it) } ?: return, - json.getInt("startTime")?.let { Time.fromValue(it) }, - json.getString("topic") ?: "", - json.getInt("color") ?: -1, - json.getLong("type") ?: 0, - true, - json.getLong("teacherId") ?: -1, - json.getLong("subjectId") ?: -1, - team.id + profileId = team.profileId, + id = json.getLong("id") ?: return, + date = json.getInt("eventDate")?.let { Date.fromValue(it) } ?: return, + time = json.getInt("startTime")?.let { Time.fromValue(it) }, + topic = json.getString("topicHtml") ?: json.getString("topic") ?: "", + color = json.getInt("color"), + type = json.getLong("type") ?: 0, + teacherId = json.getLong("teacherId") ?: -1, + subjectId = json.getLong("subjectId") ?: -1, + teamId = team.id, + addedDate = json.getLong("addedDate") ?: System.currentTimeMillis() ) + if (event.color == -1) + event.color = null event.sharedBy = json.getString("sharedBy") event.sharedByName = json.getString("sharedByName") - if (profile.userCode == event.sharedBy) event.sharedBy = "self" + if (profile.userCode == event.sharedBy) { + event.sharedBy = "self" + event.addedManually = true + } val metadata = Metadata( event.profileId, - if (event.type == Event.TYPE_HOMEWORK) Metadata.TYPE_HOMEWORK else Metadata.TYPE_EVENT, + if (event.isHomework) Metadata.TYPE_HOMEWORK else Metadata.TYPE_EVENT, event.id, false, - true, - json.getLong("addedDate") ?: System.currentTimeMillis() + true ) - val type = if (event.type == Event.TYPE_HOMEWORK) Notification.TYPE_NEW_SHARED_HOMEWORK else Notification.TYPE_NEW_SHARED_EVENT + val type = if (event.isHomework) Notification.TYPE_NEW_SHARED_HOMEWORK else Notification.TYPE_NEW_SHARED_EVENT val notificationFilter = app.config.getFor(event.profileId).sync.notificationFilter - if (!notificationFilter.contains(type)) { + if (!notificationFilter.contains(type) && event.sharedBy != "self" && event.date >= Date.getToday()) { val notification = Notification( id = Notification.buildId(event.profileId, type, event.id), title = app.getNotificationTitle(type), @@ -142,16 +172,16 @@ class SzkolnyAppFirebase(val app: App, val profiles: List, val message: type = type, profileId = profile.id, profileName = profile.name, - viewId = if (event.type == Event.TYPE_HOMEWORK) MainActivity.DRAWER_ITEM_HOMEWORK else MainActivity.DRAWER_ITEM_AGENDA, - addedDate = metadata.addedDate - ).addExtra("eventId", event.id).addExtra("eventDate", event.eventDate.value.toLong()) + viewId = if (event.isHomework) MainActivity.DRAWER_ITEM_HOMEWORK else MainActivity.DRAWER_ITEM_AGENDA, + addedDate = event.addedDate + ).addExtra("eventId", event.id).addExtra("eventDate", event.date.value.toLong()) notificationList += notification } events += event metadataList += metadata } - app.db.eventDao().addAll(events) + app.db.eventDao().upsertAll(events) app.db.metadataDao().addAllReplace(metadataList) if (notificationList.isNotEmpty()) { app.db.notificationDao().addAll(notificationList) @@ -165,14 +195,13 @@ class SzkolnyAppFirebase(val app: App, val profiles: List, val message: teams.filter { it.code == teamCode }.distinctBy { it.profileId }.forEach { team -> val profile = profiles.firstOrNull { it.id == team.profileId } ?: return@forEach - if (profile.registration != Profile.REGISTRATION_ENABLED) + if (!profile.canShare) return@forEach val notificationFilter = app.config.getFor(team.profileId).sync.notificationFilter if (!notificationFilter.contains(Notification.TYPE_REMOVED_SHARED_EVENT)) { val notification = Notification( - id = Notification.buildId(profile.id - ?: 0, Notification.TYPE_REMOVED_SHARED_EVENT, eventId), + id = Notification.buildId(profile.id, Notification.TYPE_REMOVED_SHARED_EVENT, eventId), title = app.getNotificationTitle(Notification.TYPE_REMOVED_SHARED_EVENT), text = message, type = Notification.TYPE_REMOVED_SHARED_EVENT, @@ -189,4 +218,71 @@ class SzkolnyAppFirebase(val app: App, val profiles: List, val message: PostNotifications(app, notificationList) } } + + private fun sharedNote(teamCode: String, jsonStr: String, message: String) { + val note = app.gson.fromJson(jsonStr, Note::class.java) + val noteSharedBy = note.sharedBy + val teams = app.db.teamDao().allNow + // not used, as the server provides a sharing message + //val eventTypes = app.db.eventTypeDao().allNow + + val notes = mutableListOf() + val notificationList = mutableListOf() + + teams.filter { it.code == teamCode }.distinctBy { it.profileId }.forEach { team -> + val profile = profiles.firstOrNull { it.id == team.profileId } ?: return@forEach + 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)) + return@forEach + + notes += note + + val hadNote = app.db.noteDao().getNow(note.profileId, note.id) != null + // skip creating notifications + if (hadNote) + return@forEach + + val type = Notification.TYPE_NEW_SHARED_NOTE + val notificationFilter = app.config.getFor(note.profileId).sync.notificationFilter + + if (!notificationFilter.contains(type) && note.sharedBy != "self") { + val notification = Notification( + id = Notification.buildId(note.profileId, type, note.id), + title = app.getNotificationTitle(type), + text = message, + type = type, + profileId = profile.id, + profileName = profile.name, + viewId = MainActivity.DRAWER_ITEM_HOME, + addedDate = note.addedDate + ).addExtra("noteId", note.id) + notificationList += notification + } + } + app.db.noteDao().addAll(notes) + if (notificationList.isNotEmpty()) { + app.db.notificationDao().addAll(notificationList) + PostNotifications(app, notificationList) + } + } + + private fun unsharedNote(teamCode: String, noteId: Long) { + val teams = app.db.teamDao().allNow + + teams.filter { it.code == teamCode }.distinctBy { it.profileId }.forEach { team -> + val profile = profiles.firstOrNull { it.id == team.profileId } ?: return@forEach + if (!profile.canShare) + return@forEach + + app.db.noteDao().remove(team.profileId, noteId) + } + } } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/SzkolnyLibrusFirebase.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/SzkolnyLibrusFirebase.kt index cc59faf4..a9a183e5 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/SzkolnyLibrusFirebase.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/SzkolnyLibrusFirebase.kt @@ -11,7 +11,7 @@ import pl.szczodrzynski.edziennik.data.api.edziennik.EdziennikTask import pl.szczodrzynski.edziennik.data.api.edziennik.librus.* import pl.szczodrzynski.edziennik.data.api.task.IApiTask import pl.szczodrzynski.edziennik.data.db.entity.Profile -import pl.szczodrzynski.edziennik.getString +import pl.szczodrzynski.edziennik.ext.getString class SzkolnyLibrusFirebase(val app: App, val profiles: List, val message: FirebaseService.Message) { /*{ diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/SzkolnyMobidziennikFirebase.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/SzkolnyMobidziennikFirebase.kt index f102fc2a..d5b6c077 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/SzkolnyMobidziennikFirebase.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/SzkolnyMobidziennikFirebase.kt @@ -12,10 +12,10 @@ import pl.szczodrzynski.edziennik.MainActivity.Companion.DRAWER_ITEM_MESSAGES import pl.szczodrzynski.edziennik.data.api.LOGIN_TYPE_MOBIDZIENNIK import pl.szczodrzynski.edziennik.data.api.edziennik.EdziennikTask import pl.szczodrzynski.edziennik.data.api.task.IApiTask -import pl.szczodrzynski.edziennik.data.db.entity.Message.TYPE_RECEIVED +import pl.szczodrzynski.edziennik.data.db.entity.Message.Companion.TYPE_RECEIVED import pl.szczodrzynski.edziennik.data.db.entity.Profile -import pl.szczodrzynski.edziennik.getLong -import pl.szczodrzynski.edziennik.getString +import pl.szczodrzynski.edziennik.ext.getLong +import pl.szczodrzynski.edziennik.ext.getString class SzkolnyMobidziennikFirebase(val app: App, val profiles: List, val message: FirebaseService.Message) { /*{ diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/SzkolnyVulcanFirebase.kt b/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/SzkolnyVulcanFirebase.kt index b7d3af9e..74ccdd85 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/SzkolnyVulcanFirebase.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/data/firebase/SzkolnyVulcanFirebase.kt @@ -10,6 +10,9 @@ import pl.szczodrzynski.edziennik.data.api.edziennik.EdziennikTask import pl.szczodrzynski.edziennik.data.api.task.IApiTask import pl.szczodrzynski.edziennik.data.db.entity.Message import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.getInt +import pl.szczodrzynski.edziennik.ext.getString +import pl.szczodrzynski.edziennik.ext.toJsonObject import java.util.* class SzkolnyVulcanFirebase(val app: App, val profiles: List, val message: FirebaseService.Message) { @@ -29,9 +32,10 @@ class SzkolnyVulcanFirebase(val app: App, val profiles: List, val messa val data = message.data.getString("data")?.toJsonObject() ?: return@run val type = data.getString("table") ?: return@run val studentId = data.getInt("pupilid") + val loginId = data.getInt("loginid") /* pl.vulcan.uonetmobile.auxilary.enums.CDCPushEnum */ - val viewIdPair = when (type.toLowerCase(Locale.ROOT)) { + val viewIdPair = when (type.lowercase()) { "wiadomosc" -> MainActivity.DRAWER_ITEM_MESSAGES to Message.TYPE_RECEIVED "ocena" -> MainActivity.DRAWER_ITEM_GRADES to 0 "uwaga" -> MainActivity.DRAWER_ITEM_BEHAVIOUR to 0 @@ -42,8 +46,9 @@ class SzkolnyVulcanFirebase(val app: App, val profiles: List, val messa } val tasks = profiles.filter { - it.loginStoreType == LOGIN_TYPE_VULCAN && - it.getStudentData("studentId", 0) == studentId + it.loginStoreType == LOGIN_TYPE_VULCAN + && (it.getStudentData("studentId", 0) == studentId + || it.getStudentData("studentLoginId", 0) == loginId) }.map { EdziennikTask.syncProfile(it.id, listOf(viewIdPair)) } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ext/ArrayExtensions.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ext/ArrayExtensions.kt new file mode 100644 index 00000000..e263627c --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ext/ArrayExtensions.kt @@ -0,0 +1,203 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-17. + */ + +package pl.szczodrzynski.edziennik.ext + +import android.text.SpannableStringBuilder +import android.text.Spanned +import android.text.SpannedString +import android.util.LongSparseArray +import android.util.SparseArray +import android.util.SparseIntArray +import androidx.core.util.forEach +import java.util.* + +fun Collection?.isNotNullNorEmpty(): Boolean { + return this != null && this.isNotEmpty() +} + +fun List.join(delimiter: String): String { + return concat(delimiter).toString() +} + +fun LongSparseArray.values(): List { + val result = mutableListOf() + forEach { _, value -> + result += value + } + return result +} + +fun SparseArray<*>.keys(): List { + val result = mutableListOf() + forEach { key, _ -> + result += key + } + return result +} +fun SparseArray.values(): List { + val result = mutableListOf() + forEach { _, value -> + result += value + } + return result +} + +fun SparseIntArray.keys(): List { + val result = mutableListOf() + forEach { key, _ -> + result += key + } + return result +} +fun SparseIntArray.values(): List { + val result = mutableListOf() + forEach { _, value -> + result += value + } + return result +} + +fun List>.keys() = map { it.first } +fun List>.values() = map { it.second } + +fun List.toSparseArray(destination: SparseArray, key: (T) -> Int) { + forEach { + destination.put(key(it), it) + } +} +fun List.toSparseArray(destination: LongSparseArray, key: (T) -> Long) { + forEach { + destination.put(key(it), it) + } +} + +fun List.toSparseArray(key: (T) -> Int): SparseArray { + val result = SparseArray() + toSparseArray(result, key) + return result +} +fun List.toSparseArray(key: (T) -> Long): LongSparseArray { + val result = LongSparseArray() + toSparseArray(result, key) + return result +} + +fun SparseArray.singleOrNull(predicate: (T) -> Boolean): T? { + forEach { _, value -> + if (predicate(value)) + return value + } + return null +} +fun LongSparseArray.singleOrNull(predicate: (T) -> Boolean): T? { + forEach { _, value -> + if (predicate(value)) + return value + } + return null +} + +/** + * Returns a new read-only list only of those given elements, that are not empty. + * Applies for CharSequence and descendants. + */ +fun listOfNotEmpty(vararg elements: T): List = elements.filterNot { it.isEmpty() } + +fun List.concat(delimiter: CharSequence? = null): CharSequence { + if (this.isEmpty()) { + return "" + } + + if (this.size == 1) { + return this[0] ?: "" + } + + var spanned = delimiter is Spanned + if (!spanned) { + for (piece in this) { + if (piece is Spanned) { + spanned = true + break + } + } + } + + var first = true + if (spanned) { + val ssb = SpannableStringBuilder() + for (piece in this) { + if (piece == null) + continue + if (!first && delimiter != null) + ssb.append(delimiter) + first = false + ssb.append(piece) + } + return SpannedString(ssb) + } else { + val sb = StringBuilder() + for (piece in this) { + if (piece == null) + continue + if (!first && delimiter != null) + sb.append(delimiter) + first = false + sb.append(piece) + } + return sb.toString() + } +} + +inline fun List.ifNotEmpty(block: (List) -> Unit) { + if (!isEmpty()) + block(this) +} + +inline fun LongSparseArray.filter(predicate: (T) -> Boolean): List { + val destination = ArrayList() + this.forEach { _, element -> if (predicate(element)) destination.add(element) } + return destination +} + +fun CharSequence.containsAll(list: List, ignoreCase: Boolean = false): Boolean { + for (i in list) { + if (!contains(i, ignoreCase)) + return false + } + return true +} + +fun MutableList.after(what: E, insert: E) { + val index = indexOf(what) + if (index != -1) + add(index + 1, insert) +} + +fun MutableList.before(what: E, insert: E) { + val index = indexOf(what) + if (index != -1) + add(index, insert) +} + +fun MutableList.after(what: E, insert: Collection) { + val index = indexOf(what) + if (index != -1) + addAll(index + 1, insert) +} + +fun MutableList.before(what: E, insert: Collection) { + val index = indexOf(what) + if (index != -1) + addAll(index, insert) +} + +operator fun Iterable>.get(key: K): V? { + return firstOrNull { it.first == key }?.second +} + +@kotlin.jvm.JvmName("averageOrNullOfInt") +fun Iterable.averageOrNull() = this.average().let { if (it.isNaN()) null else it } +@kotlin.jvm.JvmName("averageOrNullOfFloat") +fun Iterable.averageOrNull() = this.average().let { if (it.isNaN()) null else it } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ext/BundleExtensions.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ext/BundleExtensions.kt new file mode 100644 index 00000000..037d78f5 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ext/BundleExtensions.kt @@ -0,0 +1,92 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-17. + */ + +package pl.szczodrzynski.edziennik.ext + +import android.content.Context +import android.content.Intent +import android.os.Bundle +import android.os.Parcelable +import com.google.gson.JsonObject + +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 +} +inline fun > Bundle?.getEnum(key: String): E? { + return this?.getString(key)?.let { + try { + enumValueOf(it) + } catch (e: Exception) { + null + } + } +} + +fun Bundle?.getIntOrNull(key: String): Int? { + return this?.get(key) as? Int +} + +@Suppress("UNCHECKED_CAST") +fun Bundle?.get(key: String): T? { + return this?.get(key) as? T? +} + +@Suppress("UNCHECKED_CAST") +fun Bundle(vararg properties: Pair): Bundle { + return Bundle().apply { + for (property in properties) { + when (property.second) { + is String -> putString(property.first, property.second as String?) + is Char -> putChar(property.first, property.second as Char) + is Int -> putInt(property.first, property.second as Int) + is Long -> putLong(property.first, property.second as Long) + is Float -> putFloat(property.first, property.second as Float) + is Short -> putShort(property.first, property.second as Short) + is Double -> putDouble(property.first, property.second as Double) + is Boolean -> putBoolean(property.first, property.second as Boolean) + is Bundle -> putBundle(property.first, property.second as Bundle) + is Parcelable -> putParcelable(property.first, property.second as Parcelable) + is Array<*> -> putParcelableArray(property.first, property.second as Array) + is Enum<*> -> putString(property.first, (property.second as Enum<*>).name) + } + } + } +} +fun Intent(action: String? = null, vararg properties: Pair): Intent { + return Intent(action).putExtras(Bundle(*properties)) +} +fun Intent(packageContext: Context, cls: Class<*>, vararg properties: Pair): Intent { + return Intent(packageContext, cls).putExtras(Bundle(*properties)) +} + +fun Bundle.toJsonObject(): JsonObject { + val json = JsonObject() + keySet()?.forEach { key -> + get(key)?.let { + when (it) { + is String -> json.addProperty(key, it) + is Char -> json.addProperty(key, it) + is Int -> json.addProperty(key, it) + is Long -> json.addProperty(key, it) + is Float -> json.addProperty(key, it) + is Short -> json.addProperty(key, it) + is Double -> json.addProperty(key, it) + is Boolean -> json.addProperty(key, it) + is Bundle -> json.add(key, it.toJsonObject()) + else -> json.addProperty(key, it.toString()) + } + } + } + return json +} +fun Intent.toJsonObject() = extras?.toJsonObject() diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ext/ContextExtensions.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ext/ContextExtensions.kt new file mode 100644 index 00000000..395b0102 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ext/ContextExtensions.kt @@ -0,0 +1,20 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-17. + */ + +package pl.szczodrzynski.edziennik.ext + +import android.content.Context +import android.os.Build +import java.util.* + +fun Context.setLanguage(language: String) { + val locale = Locale(language.lowercase()) + 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) +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ext/CryptoExtensions.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ext/CryptoExtensions.kt new file mode 100644 index 00000000..f1a67e37 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ext/CryptoExtensions.kt @@ -0,0 +1,73 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-17. + */ + +package pl.szczodrzynski.edziennik.ext + +import android.util.Base64 +import java.math.BigInteger +import java.nio.charset.Charset +import java.security.MessageDigest +import java.util.zip.CRC32 +import javax.crypto.Mac +import javax.crypto.spec.SecretKeySpec + +fun String.crc16(): Int { + var crc = 0xFFFF + for (aBuffer in this) { + crc = crc.ushr(8) or (crc shl 8) and 0xffff + crc = crc xor (aBuffer.code and 0xff) // byte to int, trunc sign + crc = crc xor (crc and 0xff shr 4) + crc = crc xor (crc shl 12 and 0xffff) + crc = crc xor (crc and 0xFF shl 5 and 0xffff) + } + crc = crc and 0xffff + return crc + 32768 +} + +fun String.crc32(): Long { + val crc = CRC32() + crc.update(toByteArray()) + return crc.value +} + +fun String.hmacSHA1(password: String): String { + val key = SecretKeySpec(password.toByteArray(), "HmacSHA1") + + val mac = Mac.getInstance("HmacSHA1").apply { + init(key) + update(this@hmacSHA1.toByteArray()) + } + + return Base64.encodeToString(mac.doFinal(), Base64.NO_WRAP) +} + +fun String.md5(): String { + val md = MessageDigest.getInstance("MD5") + return BigInteger(1, md.digest(toByteArray())).toString(16).padStart(32, '0') +} + +fun String.sha1Hex(): String { + val md = MessageDigest.getInstance("SHA-1") + md.update(toByteArray()) + return md.digest().joinToString("") { "%02x".format(it) } +} + +fun String.sha256(): ByteArray { + val md = MessageDigest.getInstance("SHA-256") + md.update(toByteArray()) + return md.digest() +} + +fun String.base64Encode(): String { + return Base64.encodeToString(toByteArray(), Base64.NO_WRAP) +} +fun ByteArray.base64Encode(): String { + return Base64.encodeToString(this, Base64.NO_WRAP) +} +fun String.base64Decode(): ByteArray { + return Base64.decode(this, Base64.DEFAULT) +} +fun String.base64DecodeToString(): String { + return Base64.decode(this, Base64.DEFAULT).toString(Charset.defaultCharset()) +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ext/DataExtensions.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ext/DataExtensions.kt new file mode 100644 index 00000000..b1e99c43 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ext/DataExtensions.kt @@ -0,0 +1,76 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-17. + */ + +package pl.szczodrzynski.edziennik.ext + +import android.content.Context +import android.util.LongSparseArray +import androidx.core.util.forEach +import com.google.android.material.datepicker.CalendarConstraints +import com.google.gson.JsonElement +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.db.entity.Notification +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.data.db.entity.Teacher +import pl.szczodrzynski.edziennik.data.db.entity.Team + +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 List.filterOutArchived() = this.filter { !it.archived } + +fun List.getById(id: Long): Team? { + return singleOrNull { it.id == id } +} + +fun LongSparseArray.getById(id: Long): Team? { + forEach { _, value -> + if (value.id == id) + return value + } + return null +} + +operator fun Profile.set(key: String, value: JsonElement) = this.studentData.add(key, value) +operator fun Profile.set(key: String, value: Boolean) = this.studentData.addProperty(key, value) +operator fun Profile.set(key: String, value: String?) = this.studentData.addProperty(key, value) +operator fun Profile.set(key: String, value: Number) = this.studentData.addProperty(key, value) +operator fun Profile.set(key: String, value: Char) = this.studentData.addProperty(key, value) + +fun Context.getNotificationTitle(type: Int): String { + return getString(when (type) { + Notification.TYPE_UPDATE -> R.string.notification_type_update + Notification.TYPE_ERROR -> R.string.notification_type_error + Notification.TYPE_TIMETABLE_CHANGED -> R.string.notification_type_timetable_change + Notification.TYPE_TIMETABLE_LESSON_CHANGE -> R.string.notification_type_timetable_lesson_change + Notification.TYPE_NEW_GRADE -> R.string.notification_type_new_grade + Notification.TYPE_NEW_EVENT -> R.string.notification_type_new_event + Notification.TYPE_NEW_HOMEWORK -> R.string.notification_type_new_homework + Notification.TYPE_NEW_SHARED_EVENT -> R.string.notification_type_new_shared_event + Notification.TYPE_NEW_SHARED_HOMEWORK -> R.string.notification_type_new_shared_homework + Notification.TYPE_REMOVED_SHARED_EVENT -> R.string.notification_type_removed_shared_event + Notification.TYPE_NEW_MESSAGE -> R.string.notification_type_new_message + Notification.TYPE_NEW_NOTICE -> R.string.notification_type_notice + Notification.TYPE_NEW_ATTENDANCE -> R.string.notification_type_attendance + Notification.TYPE_SERVER_MESSAGE -> R.string.notification_type_server_message + Notification.TYPE_LUCKY_NUMBER -> R.string.notification_type_lucky_number + Notification.TYPE_FEEDBACK_MESSAGE -> R.string.notification_type_feedback_message + Notification.TYPE_NEW_ANNOUNCEMENT -> R.string.notification_type_new_announcement + Notification.TYPE_AUTO_ARCHIVING -> R.string.notification_type_auto_archiving + Notification.TYPE_TEACHER_ABSENCE -> R.string.notification_type_new_teacher_absence + Notification.TYPE_GENERAL -> R.string.notification_type_general + Notification.TYPE_NEW_SHARED_NOTE -> R.string.notification_type_new_shared_note + else -> R.string.notification_type_general + }) +} + +fun Profile.getSchoolYearConstrains(): CalendarConstraints { + return CalendarConstraints.Builder() + .setStart(dateSemester1Start.inMillisUtc) + .setEnd(dateYearEnd.inMillisUtc) + .build() +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ext/DialogExtensions.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ext/DialogExtensions.kt new file mode 100644 index 00000000..61de4f77 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ext/DialogExtensions.kt @@ -0,0 +1,104 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-3-30. + */ + +package pl.szczodrzynski.edziennik.ext + +import android.annotation.SuppressLint +import android.content.res.ColorStateList +import android.text.InputType +import android.view.LayoutInflater +import androidx.annotation.StringRes +import androidx.appcompat.app.AlertDialog +import androidx.core.graphics.ColorUtils +import androidx.core.view.ViewCompat +import androidx.core.view.isVisible +import androidx.core.widget.addTextChangedListener +import com.google.android.material.color.MaterialColors +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import com.google.android.material.dialog.MaterialDialogs +import com.google.android.material.shape.MaterialShapeDrawable +import com.google.android.material.textfield.TextInputEditText +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.databinding.DialogEditTextBinding + +fun MaterialAlertDialogBuilder.input( + message: CharSequence? = null, + type: Int = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE, + hint: CharSequence? = null, + value: CharSequence? = null, + changeListener: ((editText: TextInputEditText, input: String) -> Boolean)? = null, + positiveButton: Int? = null, + positiveListener: ((editText: TextInputEditText, input: String) -> Boolean)? = null, +): MaterialAlertDialogBuilder { + val b = DialogEditTextBinding.inflate(LayoutInflater.from(context), null, false) + b.title.text = message + b.title.isVisible = message.isNotNullNorBlank() + b.text1.hint = hint + b.text1.inputType = type + b.text1.setText(value) + b.text1.addTextChangedListener { text -> + if (changeListener?.invoke(b.text1, text?.toString() ?: "") != false) + b.text1.error = null + } + if (positiveButton != null) { + setPositiveButton(positiveButton) { dialog, _ -> + if (positiveListener?.invoke(b.text1, b.text1.text?.toString() ?: "") != false) + dialog.dismiss() + } + } + setView(b.root) + + return this +} + +fun MaterialAlertDialogBuilder.setTitle( + @StringRes resId: Int, + vararg formatArgs: Any, +): MaterialAlertDialogBuilder { + setTitle(context.getString(resId, *formatArgs)) + return this +} + +fun MaterialAlertDialogBuilder.setMessage( + @StringRes resId: Int, + vararg formatArgs: Any, +): MaterialAlertDialogBuilder { + setMessage(context.getString(resId, *formatArgs)) + return this +} + +@SuppressLint("RestrictedApi") +fun AlertDialog.overlayBackgroundColor(color: Int, alpha: Int) { + // this is absolutely horrible + val colorSurface16dp = ColorUtils.compositeColors( + R.color.colorSurface_16dp.resolveColor(context), + MaterialColors.getColor( + context, + R.attr.colorSurface, + javaClass.canonicalName, + ) + ) + val colorDialogBackground = MaterialColors.layer(colorSurface16dp, color, alpha / 255f) + val backgroundInsets = MaterialDialogs.getDialogBackgroundInsets( + context, + R.attr.alertDialogStyle, + R.style.MaterialAlertDialog_MaterialComponents, + ) + val background = MaterialShapeDrawable( + context, + null, + R.attr.alertDialogStyle, + R.style.MaterialAlertDialog_MaterialComponents + ) + with(background) { + initializeElevationOverlay(context) + fillColor = ColorStateList.valueOf(colorDialogBackground) + /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + setCornerSize(android.R.attr.dialogCornerRadius.resolveDimenAttr(context)) + }*/ + elevation = ViewCompat.getElevation(window?.decorView ?: return@with) + } + val insetDrawable = MaterialDialogs.insetDrawable(background, backgroundInsets) + window?.setBackgroundDrawable(insetDrawable) +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ext/GraphicsExtensions.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ext/GraphicsExtensions.kt new file mode 100644 index 00000000..69cbfc33 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ext/GraphicsExtensions.kt @@ -0,0 +1,100 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-17. + */ + +package pl.szczodrzynski.edziennik.ext + +import android.content.Context +import android.content.res.ColorStateList +import android.graphics.PorterDuff +import android.graphics.PorterDuffColorFilter +import android.graphics.drawable.Drawable +import android.util.TypedValue +import androidx.annotation.* +import androidx.core.content.res.ResourcesCompat +import com.mikepenz.iconics.typeface.IIcon +import pl.szczodrzynski.navlib.ImageHolder + +fun colorFromName(name: String?): Int { + val i = (name ?: "").crc32() + return when ((i / 10 % 16 + 1).toInt()) { + 13 -> 0xffF44336 + 4 -> 0xffF50057 + 2 -> 0xffD500F9 + 9 -> 0xff6200EA + 5 -> 0xffFFAB00 + 1 -> 0xff304FFE + 6 -> 0xff40C4FF + 14 -> 0xff26A69A + 15 -> 0xff00C853 + 7 -> 0xffFFD600 + 3 -> 0xffFF3D00 + 8 -> 0xffDD2C00 + 10 -> 0xff795548 + 12 -> 0xff2979FF + 11 -> 0xffFF6D00 + else -> 0xff64DD17 + }.toInt() +} + +fun colorFromCssName(name: String): Int { + return when (name) { + "red" -> 0xffff0000 + "green" -> 0xff008000 + "blue" -> 0xff0000ff + "violet" -> 0xffee82ee + "brown" -> 0xffa52a2a + "orange" -> 0xffffa500 + "black" -> 0xff000000 + "white" -> 0xffffffff + else -> -1L + }.toInt() +} + +@ColorInt +fun @receiver:AttrRes Int.resolveAttr(context: Context?): Int { + val typedValue = TypedValue() + context?.theme?.resolveAttribute(this, typedValue, true) + return typedValue.data +} +@Dimension +fun @receiver:AttrRes Int.resolveDimenAttr(context: Context): Float { + val typedValue = TypedValue() + context.theme?.resolveAttribute(this, typedValue, true) + return typedValue.getDimension(context.resources.displayMetrics) +} +@ColorInt +fun @receiver:ColorRes Int.resolveColor(context: Context): Int { + return ResourcesCompat.getColor(context.resources, this, context.theme) +} +fun @receiver:DrawableRes Int.resolveDrawable(context: Context): Drawable { + return ResourcesCompat.getDrawable(context.resources, this, context.theme)!! +} + +fun Int.toColorStateList(): ColorStateList { + val states = arrayOf( + intArrayOf( android.R.attr.state_enabled ), + intArrayOf(-android.R.attr.state_enabled ), + intArrayOf(-android.R.attr.state_checked ), + intArrayOf( android.R.attr.state_pressed ) + ) + + val colors = intArrayOf( + this, + this, + this, + this + ) + + return ColorStateList(states, colors) +} + +fun Drawable.setTintColor(color: Int): Drawable { + colorFilter = PorterDuffColorFilter( + color, + PorterDuff.Mode.SRC_ATOP + ) + return this +} + +fun IIcon.toImageHolder() = ImageHolder(this) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ext/JsonExtensions.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ext/JsonExtensions.kt new file mode 100644 index 00000000..14d25b48 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ext/JsonExtensions.kt @@ -0,0 +1,109 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-17. + */ + +package pl.szczodrzynski.edziennik.ext + +import android.os.Bundle +import com.google.gson.JsonArray +import com.google.gson.JsonElement +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import com.google.gson.JsonPrimitive +import kotlin.contracts.ExperimentalContracts +import kotlin.contracts.contract + +fun JsonObject?.get(key: String): JsonElement? = this?.get(key) + +fun JsonObject?.getBoolean(key: String): Boolean? = get(key)?.let { if (!it.isJsonPrimitive) null else it.asBoolean } +fun JsonObject?.getString(key: String): String? = get(key)?.let { if (!it.isJsonPrimitive) null else it.asString } +fun JsonObject?.getInt(key: String): Int? = get(key)?.let { if (!it.isJsonPrimitive) null else it.asInt } +fun JsonObject?.getLong(key: String): Long? = get(key)?.let { if (!it.isJsonPrimitive) null else it.asLong } +fun JsonObject?.getFloat(key: String): Float? = get(key)?.let { if(!it.isJsonPrimitive) null else it.asFloat } +fun JsonObject?.getChar(key: String): Char? = get(key)?.let { if(!it.isJsonPrimitive) null else it.asString[0] } +fun JsonObject?.getJsonObject(key: String): JsonObject? = get(key)?.let { if (it.isJsonObject) it.asJsonObject else null } +fun JsonObject?.getJsonArray(key: String): JsonArray? = get(key)?.let { if (it.isJsonArray) it.asJsonArray else null } + +fun JsonObject?.getBoolean(key: String, defaultValue: Boolean): Boolean = get(key)?.let { if (!it.isJsonPrimitive) defaultValue else it.asBoolean } ?: defaultValue +fun JsonObject?.getString(key: String, defaultValue: String): String = get(key)?.let { if (!it.isJsonPrimitive) defaultValue else it.asString } ?: defaultValue +fun JsonObject?.getInt(key: String, defaultValue: Int): Int = get(key)?.let { if (!it.isJsonPrimitive) defaultValue else it.asInt } ?: defaultValue +fun JsonObject?.getLong(key: String, defaultValue: Long): Long = get(key)?.let { if (!it.isJsonPrimitive) defaultValue else it.asLong } ?: defaultValue +fun JsonObject?.getFloat(key: String, defaultValue: Float): Float = get(key)?.let { if(!it.isJsonPrimitive) defaultValue else it.asFloat } ?: defaultValue +fun JsonObject?.getChar(key: String, defaultValue: Char): Char = get(key)?.let { if(!it.isJsonPrimitive) defaultValue else it.asString[0] } ?: defaultValue +fun JsonObject?.getJsonObject(key: String, defaultValue: JsonObject): JsonObject = get(key)?.let { if (it.isJsonObject) it.asJsonObject else defaultValue } ?: defaultValue +fun JsonObject?.getJsonArray(key: String, defaultValue: JsonArray): JsonArray = get(key)?.let { if (it.isJsonArray) it.asJsonArray else defaultValue } ?: defaultValue + +fun JsonArray.getBoolean(key: Int): Boolean? = if (key >= size()) null else get(key)?.let { if (!it.isJsonPrimitive) null else it.asBoolean } +fun JsonArray.getString(key: Int): String? = if (key >= size()) null else get(key)?.let { if (!it.isJsonPrimitive) null else it.asString } +fun JsonArray.getInt(key: Int): Int? = if (key >= size()) null else get(key)?.let { if (!it.isJsonPrimitive) null else it.asInt } +fun JsonArray.getLong(key: Int): Long? = if (key >= size()) null else get(key)?.let { if (!it.isJsonPrimitive) null else it.asLong } +fun JsonArray.getFloat(key: Int): Float? = if (key >= size()) null else get(key)?.let { if(!it.isJsonPrimitive) null else it.asFloat } +fun JsonArray.getChar(key: Int): Char? = if (key >= size()) null else get(key)?.let { if(!it.isJsonPrimitive) null else it.asString[0] } +fun JsonArray.getJsonObject(key: Int): JsonObject? = if (key >= size()) null else get(key)?.let { if (it.isJsonObject) it.asJsonObject else null } +fun JsonArray.getJsonArray(key: Int): JsonArray? = if (key >= size()) null else get(key)?.let { if (it.isJsonArray) it.asJsonArray else null } + +fun String.toJsonObject(): JsonObject? = try { JsonParser.parseString(this).asJsonObject } catch (ignore: Exception) { null } + +operator fun JsonObject.set(key: String, value: JsonElement) = this.add(key, value) +operator fun JsonObject.set(key: String, value: Boolean) = this.addProperty(key, value) +operator fun JsonObject.set(key: String, value: String?) = this.addProperty(key, value) +operator fun JsonObject.set(key: String, value: Number) = this.addProperty(key, value) +operator fun JsonObject.set(key: String, value: Char) = this.addProperty(key, value) + +fun JsonArray.asJsonObjectList() = this.mapNotNull { it.asJsonObject } + +fun JsonObject(vararg properties: Pair): JsonObject { + return JsonObject().apply { + for (property in properties) { + when (property.second) { + is JsonElement -> add(property.first, property.second as JsonElement?) + is String -> addProperty(property.first, property.second as String?) + is Char -> addProperty(property.first, property.second as Char?) + is Number -> addProperty(property.first, property.second as Number?) + is Boolean -> addProperty(property.first, property.second as Boolean?) + } + } + } +} + +fun JsonObject.toBundle(): Bundle { + return Bundle().also { + for ((key, value) in this.entrySet()) { + when (value) { + is JsonObject -> it.putBundle(key, value.toBundle()) + is JsonPrimitive -> when { + value.isString -> it.putString(key, value.asString) + value.isBoolean -> it.putBoolean(key, value.asBoolean) + value.isNumber -> it.putInt(key, value.asInt) + } + } + } + } +} + +fun JsonArray(vararg properties: Any?): JsonArray { + return JsonArray().apply { + for (property in properties) { + when (property) { + is JsonElement -> add(property as JsonElement?) + is String -> add(property as String?) + is Char -> add(property as Char?) + is Number -> add(property as Number?) + is Boolean -> add(property as Boolean?) + } + } + } +} + +@OptIn(ExperimentalContracts::class) +fun JsonArray?.isNullOrEmpty(): Boolean { + contract { + returns(false) implies (this@isNullOrEmpty != null) + } + return this == null || this.isEmpty +} +operator fun JsonArray.plusAssign(o: JsonElement) = this.add(o) +operator fun JsonArray.plusAssign(o: String) = this.add(o) +operator fun JsonArray.plusAssign(o: Char) = this.add(o) +operator fun JsonArray.plusAssign(o: Number) = this.add(o) +operator fun JsonArray.plusAssign(o: Boolean) = this.add(o) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ext/MiscExtensions.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ext/MiscExtensions.kt new file mode 100644 index 00000000..df931fbd --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ext/MiscExtensions.kt @@ -0,0 +1,74 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-17. + */ + +package pl.szczodrzynski.edziennik.ext + +import android.app.PendingIntent +import android.database.Cursor +import android.os.Build +import androidx.core.database.getIntOrNull +import androidx.core.database.getLongOrNull +import androidx.core.database.getStringOrNull +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import java.io.PrintWriter +import java.io.StringWriter + +fun LiveData.observeOnce(lifecycleOwner: LifecycleOwner, observer: Observer) { + observe(lifecycleOwner, object : Observer { + override fun onChanged(t: T?) { + observer.onChanged(t) + removeObserver(this) + } + }) +} + +fun CoroutineScope.startCoroutineTimer(delayMillis: Long = 0, repeatMillis: Long = 0, action: suspend CoroutineScope.() -> Unit) = launch { + delay(delayMillis) + if (repeatMillis > 0) { + while (true) { + action() + delay(repeatMillis) + } + } else { + action() + } +} + +inline fun Any?.instanceOfOrNull(): T? { + return when (this) { + is T -> this + else -> null + } +} + +val Throwable.stackTraceString: String + get() { + val sw = StringWriter() + printStackTrace(PrintWriter(sw)) + return sw.toString() + } + +fun Cursor?.getString(columnName: String) = this?.getStringOrNull(getColumnIndex(columnName)) +fun Cursor?.getInt(columnName: String) = this?.getIntOrNull(getColumnIndex(columnName)) +fun Cursor?.getLong(columnName: String) = this?.getLongOrNull(getColumnIndex(columnName)) + +inline fun ifNotNull(a: A?, b: B?, code: (A, B) -> R): R? { + if (a != null && b != null) { + return code(a, b) + } + return null +} + +infix fun Int.hasSet(what: Int) = this and what == what + +fun pendingIntentFlag(): Int { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) + return PendingIntent.FLAG_IMMUTABLE + return 0 +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ext/NetworkExtensions.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ext/NetworkExtensions.kt new file mode 100644 index 00000000..00c0cf91 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ext/NetworkExtensions.kt @@ -0,0 +1,73 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-17. + */ + +package pl.szczodrzynski.edziennik.ext + +import im.wangchao.mhttp.Response +import okhttp3.RequestBody +import okio.Buffer +import pl.szczodrzynski.edziennik.data.api.* +import pl.szczodrzynski.edziennik.data.api.models.ApiError +import pl.szczodrzynski.edziennik.data.api.szkolny.SzkolnyApiException +import pl.szczodrzynski.edziennik.data.api.szkolny.response.ApiResponse +import java.io.InterruptedIOException +import java.net.ConnectException +import java.net.SocketTimeoutException +import java.net.UnknownHostException +import javax.net.ssl.SSLException + +fun RequestBody.bodyToString(): String { + val buffer = Buffer() + writeTo(buffer) + return buffer.readUtf8() +} + +fun Response.toErrorCode() = when (this.code()) { + 400 -> ERROR_REQUEST_HTTP_400 + 401 -> ERROR_REQUEST_HTTP_401 + 403 -> ERROR_REQUEST_HTTP_403 + 404 -> ERROR_REQUEST_HTTP_404 + 405 -> ERROR_REQUEST_HTTP_405 + 410 -> ERROR_REQUEST_HTTP_410 + 424 -> ERROR_REQUEST_HTTP_424 + 500 -> ERROR_REQUEST_HTTP_500 + 503 -> ERROR_REQUEST_HTTP_503 + else -> null +} + +fun Throwable.toErrorCode() = when (this) { + is UnknownHostException -> ERROR_REQUEST_FAILURE_HOSTNAME_NOT_FOUND + is SSLException -> ERROR_REQUEST_FAILURE_SSL_ERROR + is SocketTimeoutException -> ERROR_REQUEST_FAILURE_TIMEOUT + is InterruptedIOException, is ConnectException -> ERROR_REQUEST_FAILURE_NO_INTERNET + is SzkolnyApiException -> this.error?.toErrorCode() + else -> null +} +fun ApiResponse.Error.toErrorCode() = when (this.code) { + "PdoError" -> ERROR_API_PDO_ERROR + "InvalidClient" -> ERROR_API_INVALID_CLIENT + "InvalidArgument" -> ERROR_API_INVALID_ARGUMENT + "InvalidSignature" -> ERROR_API_INVALID_SIGNATURE + "MissingScopes" -> ERROR_API_MISSING_SCOPES + "ResourceNotFound" -> ERROR_API_RESOURCE_NOT_FOUND + "InternalServerError" -> ERROR_API_INTERNAL_SERVER_ERROR + "PhpError" -> ERROR_API_PHP_E_ERROR + "PhpWarning" -> ERROR_API_PHP_E_WARNING + "PhpParse" -> ERROR_API_PHP_E_PARSE + "PhpNotice" -> ERROR_API_PHP_E_NOTICE + "PhpOther" -> ERROR_API_PHP_E_OTHER + "ApiMaintenance" -> ERROR_API_MAINTENANCE + "MissingArgument" -> ERROR_API_MISSING_ARGUMENT + "MissingPayload" -> ERROR_API_PAYLOAD_EMPTY + "InvalidAction" -> ERROR_API_INVALID_ACTION + "VersionNotFound" -> ERROR_API_UPDATE_NOT_FOUND + "InvalidDeviceIdUserCode" -> ERROR_API_INVALID_DEVICEID_USERCODE + "InvalidPairToken" -> ERROR_API_INVALID_PAIRTOKEN + "InvalidBrowserId" -> ERROR_API_INVALID_BROWSERID + "InvalidDeviceId" -> ERROR_API_INVALID_DEVICEID + "InvalidDeviceIdBrowserId" -> ERROR_API_INVALID_DEVICEID_BROWSERID + "HelpCategoryNotFound" -> ERROR_API_HELP_CATEGORY_NOT_FOUND + else -> ERROR_API_EXCEPTION +} +fun Throwable.toApiError(tag: String) = ApiError.fromThrowable(tag, this) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ext/TextExtensions.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ext/TextExtensions.kt new file mode 100644 index 00000000..adb6fe55 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ext/TextExtensions.kt @@ -0,0 +1,361 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-17. + */ + +package pl.szczodrzynski.edziennik.ext + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.graphics.Typeface +import android.text.Spannable +import android.text.SpannableString +import android.text.SpannableStringBuilder +import android.text.style.CharacterStyle +import android.text.style.ForegroundColorSpan +import android.text.style.StrikethroughSpan +import android.text.style.StyleSpan +import androidx.annotation.PluralsRes +import androidx.annotation.StringRes +import com.mikepenz.materialdrawer.holder.StringHolder +import java.net.URLDecoder +import java.net.URLEncoder + +fun CharSequence?.isNotNullNorEmpty(): Boolean { + return this != null && this.isNotEmpty() +} + +fun CharSequence?.isNotNullNorBlank(): Boolean { + return this != null && this.isNotBlank() +} + +/** + * ` The quick BROWN_fox Jumps OveR THE LAZy-DOG. ` + * + * converts to + * + * `The Quick Brown_fox Jumps Over The Lazy-Dog.` + */ +fun String?.fixName(): String { + return this?.fixWhiteSpaces()?.toProperCase() ?: "" +} + +/** + * `The quick BROWN_fox Jumps OveR THE LAZy-DOG.` + * + * converts to + * + * `The Quick Brown_fox Jumps Over The Lazy-Dog.` + */ +fun String.toProperCase(): String = changeStringCase(this) + +/** + * `John Smith` -> `Smith John` + * + * `JOHN SMith` -> `SMith JOHN` + */ +fun String.swapFirstLastName(): String { + return this.split(" ").let { + if (it.size > 1) + it[1]+" "+it[0] + else + it[0] + } +} + +fun String.splitName(): Pair? { + return this.split(" ").let { + if (it.size >= 2) Pair(it[0], it[1]) + else null + } +} + +fun changeStringCase(s: String): String { + val delimiters = " '-/" + val sb = StringBuilder() + var capNext = true + for (ch in s.toCharArray()) { + var c = ch + c = if (capNext) + Character.toUpperCase(c) + else + Character.toLowerCase(c) + sb.append(c) + capNext = delimiters.indexOf(c) >= 0 + } + return sb.toString() +} + +fun buildFullName(firstName: String?, lastName: String?): String { + return "$firstName $lastName".fixName() +} + +fun String.getShortName(): String { + return split(" ").let { + if (it.size > 1) + "${it[0]} ${it[1][0]}." + else + it[0] + } +} + +/** + * "John Smith" -> "JS" + * + * "JOHN SMith" -> "JS" + * + * "John" -> "J" + * + * "John " -> "J" + * + * "John Smith " -> "JS" + * + * " " -> "" + * + * " " -> "" + */ +fun String?.getNameInitials(): String { + if (this.isNullOrBlank()) return "" + return this.uppercase().fixWhiteSpaces().split(" ").take(2).map { it[0] }.joinToString("") +} + +operator fun MatchResult.get(group: Int): String { + if (group >= groupValues.size) + return "" + return groupValues[group] +} + +fun String.fixWhiteSpaces() = buildString(length) { + var wasWhiteSpace = true + for (c in this@fixWhiteSpaces) { + if (c.isWhitespace()) { + if (!wasWhiteSpace) { + append(c) + wasWhiteSpace = true + } + } else { + append(c) + wasWhiteSpace = false + } + } +}.trimEnd() + +fun CharSequence?.asColoredSpannable(colorInt: Int): Spannable { + val spannable = SpannableString(this) + spannable.setSpan(ForegroundColorSpan(colorInt), 0, spannable.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) + return spannable +} +fun CharSequence?.asStrikethroughSpannable(): Spannable { + val spannable = SpannableString(this) + spannable.setSpan(StrikethroughSpan(), 0, spannable.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) + return spannable +} +fun CharSequence?.asItalicSpannable(): Spannable { + val spannable = SpannableString(this) + spannable.setSpan(StyleSpan(Typeface.ITALIC), 0, spannable.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) + return spannable +} +fun CharSequence?.asBoldSpannable(): Spannable { + val spannable = SpannableString(this) + spannable.setSpan(StyleSpan(Typeface.BOLD), 0, spannable.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) + return spannable +} +fun CharSequence.asSpannable( + vararg spans: CharacterStyle, + substring: CharSequence? = null, + ignoreCase: Boolean = false, + ignoreDiacritics: Boolean = false +): Spannable { + val spannable = SpannableString(this) + substring?.let { substr -> + val string = if (ignoreDiacritics) + this.cleanDiacritics() + else + this + val search = if (ignoreDiacritics) + substr.cleanDiacritics() + else + substr.toString() + + var index = 0 + do { + index = string.indexOf( + string = search, + startIndex = index, + ignoreCase = ignoreCase + ) + + if (index >= 0) { + spans.forEach { + spannable.setSpan( + CharacterStyle.wrap(it), + index, + index + substring.length, + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE + ) + } + index += substring.length.coerceAtLeast(1) + } + } while (index >= 0) + + } ?: spans.forEach { + spannable.setSpan(it, 0, spannable.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) + } + return spannable +} + +fun CharSequence.cleanDiacritics(): String { + val nameClean = StringBuilder() + forEach { + val ch = when (it) { + 'ż' -> 'z' + 'ó' -> 'o' + 'ł' -> 'l' + 'ć' -> 'c' + 'ę' -> 'e' + 'ś' -> 's' + 'ą' -> 'a' + 'ź' -> 'z' + 'ń' -> 'n' + else -> it + } + nameClean.append(ch) + } + return nameClean.toString() +} + +operator fun StringBuilder.plusAssign(str: String?) { + this.append(str) +} + +val String.firstLettersName: String + get() { + var nameShort = "" + this.split(" ").forEach { + if (it.isBlank()) + return@forEach + nameShort += it[0].lowercase() + } + return nameShort + } + +fun CharSequence.replaceSpanned(oldValue: String, newValue: CharSequence, ignoreCase: Boolean = false): CharSequence { + var seq = this + var index = seq.indexOf(oldValue, ignoreCase = ignoreCase) + while (index != -1) { + val sb = SpannableStringBuilder() + sb.appendRange(seq, 0, index) + sb.append(newValue) + sb.appendRange(seq, index + oldValue.length, seq.length) + seq = sb + index = seq.indexOf(oldValue, startIndex = index + 1, ignoreCase = ignoreCase) + } + return seq +} + +fun SpannableStringBuilder.replaceSpan(spanClass: Class<*>, prefix: CharSequence, suffix: CharSequence): SpannableStringBuilder { + getSpans(0, length, spanClass).forEach { + val spanStart = getSpanStart(it) + insert(spanStart, prefix) + val spanEnd = getSpanEnd(it) + insert(spanEnd, suffix) + } + return this +} + +fun SpannableStringBuilder.appendText(text: CharSequence): SpannableStringBuilder { + append(text) + return this +} +fun SpannableStringBuilder.appendSpan(text: CharSequence, what: Any, flags: Int): SpannableStringBuilder { + val start: Int = length + append(text) + setSpan(what, start, length, flags) + return this +} + +fun joinNotNullStrings(delimiter: String = "", vararg parts: String?): String { + var first = true + val sb = StringBuilder() + for (part in parts) { + if (part == null) + continue + if (!first) + sb += delimiter + first = false + sb += part + } + return sb.toString() +} + +fun String.notEmptyOrNull(): String? { + return if (isEmpty()) + null + else + this +} + +fun Context.plural(@PluralsRes resId: Int, value: Int): String = resources.getQuantityString(resId, value, value) + +fun String.copyToClipboard(context: Context) { + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + val clipData = ClipData.newPlainText("Tekst", this) + clipboard.setPrimaryClip(clipData) +} + +fun ByteArray.toHexString() = joinToString("") { "%02x".format(it) } + +fun CharSequence.getWordBounds(position: Int, onlyInWord: Boolean = false): Pair? { + if (length == 0) + return null + + // only if cursor between letters + if (onlyInWord) { + if (position < 1) + return null + if (position == length) + return null + + val charBefore = this[position - 1] + if (!charBefore.isLetterOrDigit()) + return null + val charAfter = this[position] + if (!charAfter.isLetterOrDigit()) + return null + } + + var rangeStart = substring(0 until position).indexOfLast { !it.isLetterOrDigit() } + if (rangeStart == -1) // no whitespace, set to first index + rangeStart = 0 + else // cut the leading whitespace + rangeStart += 1 + + var rangeEnd = substring(position).indexOfFirst { !it.isLetterOrDigit() } + if (rangeEnd == -1) // no whitespace, set to last index + rangeEnd = length + else // append the substring offset + rangeEnd += position + + if (!onlyInWord && rangeStart == rangeEnd) + return null + return rangeStart to rangeEnd +} + +fun Int.toStringHolder() = StringHolder(this) +fun CharSequence.toStringHolder() = StringHolder(this) + +fun @receiver:StringRes Int.resolveString(context: Context) = context.getString(this) + +fun String.urlEncode(): String = URLEncoder.encode(this, "UTF-8").replace("+", "%20") +fun String.urlDecode(): String = URLDecoder.decode(this, "UTF-8") + +fun Map.toQueryString() = this + .map { it.key.urlEncode() to it.value.urlEncode() } + .sortedBy { it.first } + .joinToString("&") { "${it.first}=${it.second}" } + +fun String.fromQueryString() = this + .substringAfter('?') + .split("&") + .map { it.split("=") } + .associate { it[0].urlDecode() to it[1].urlDecode() } diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ext/TimeExtensions.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ext/TimeExtensions.kt new file mode 100644 index 00000000..31bd952c --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ext/TimeExtensions.kt @@ -0,0 +1,126 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-17. + */ + +package pl.szczodrzynski.edziennik.ext + +import android.content.Context +import im.wangchao.mhttp.Response +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time +import java.text.SimpleDateFormat +import java.util.Locale + +const val MINUTE = 60L +const val HOUR = 60L*MINUTE +const val DAY = 24L*HOUR +const val WEEK = 7L*DAY +const val MONTH = 30L*DAY +const val YEAR = 365L*DAY +const val MS = 1000L + +fun currentTimeUnix() = System.currentTimeMillis() / 1000 + +fun Response?.getUnixDate(): Long { + val rfcDate = this?.headers()?.get("date") ?: return currentTimeUnix() + val pattern = "EEE, dd MMM yyyy HH:mm:ss Z" + val format = SimpleDateFormat(pattern, Locale.ENGLISH) + return (format.parse(rfcDate)?.time ?: 0) / 1000 +} + +fun Long.formatDate(format: String = "yyyy-MM-dd HH:mm:ss"): String = SimpleDateFormat(format).format(this) + +operator fun Time?.compareTo(other: Time?): Int { + if (this == null && other == null) + return 0 + if (this == null) + return -1 + if (other == null) + return 1 + return this.compareTo(other) +} + +fun Context.timeTill(time: Int, delimiter: String = " ", countInSeconds: Boolean = false): String { + val parts = mutableListOf>() + + val hours = time / 3600 + val minutes = (time - hours*3600) / 60 + val seconds = time - minutes*60 - hours*3600 + + if (!countInSeconds) { + var prefixAdded = false + if (hours > 0) { + if (!prefixAdded) parts += R.plurals.time_till_text to hours + prefixAdded = true + parts += R.plurals.time_till_hours to hours + } + if (minutes > 0) { + if (!prefixAdded) parts += R.plurals.time_till_text to minutes + prefixAdded = true + parts += R.plurals.time_till_minutes to minutes + } + if (hours == 0 && minutes < 10) { + if (!prefixAdded) parts += R.plurals.time_till_text to seconds + parts += R.plurals.time_till_seconds to seconds + } + } else { + parts += R.plurals.time_till_text to time + parts += R.plurals.time_till_seconds to time + } + + return parts.joinToString(delimiter) { resources.getQuantityString(it.first, it.second, it.second) } +} + +fun Context.timeLeft(time: Int, delimiter: String = " ", countInSeconds: Boolean = false): String { + val parts = mutableListOf>() + + val hours = time / 3600 + val minutes = (time - hours*3600) / 60 + val seconds = time - minutes*60 - hours*3600 + + if (!countInSeconds) { + var prefixAdded = false + if (hours > 0) { + if (!prefixAdded) parts += R.plurals.time_left_text to hours + prefixAdded = true + parts += R.plurals.time_left_hours to hours + } + if (minutes > 0) { + if (!prefixAdded) parts += R.plurals.time_left_text to minutes + prefixAdded = true + parts += R.plurals.time_left_minutes to minutes + } + if (hours == 0 && minutes < 10) { + if (!prefixAdded) parts += R.plurals.time_left_text to seconds + parts += R.plurals.time_left_seconds to seconds + } + } else { + parts += R.plurals.time_left_text to time + parts += R.plurals.time_left_seconds to time + } + + return parts.joinToString(delimiter) { resources.getQuantityString(it.first, it.second, it.second) } +} + +fun Context.getSyncInterval(interval: Int): String { + val hours = interval / 60 / 60 + val minutes = interval / 60 % 60 + val hoursText = if (hours > 0) + plural(R.plurals.time_till_hours, hours) + else + null + val minutesText = if (minutes > 0) + plural(R.plurals.time_till_minutes, minutes) + else + "" + return hoursText?.plus(" $minutesText") ?: minutesText +} + +fun ClosedRange.asSequence(): Sequence = sequence { + val date = this@asSequence.start.clone() + while (date in this@asSequence) { + yield(date.clone()) + date.stepForward(0, 0, 1) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ext/ViewExtensions.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ext/ViewExtensions.kt new file mode 100644 index 00000000..3a0468ef --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ext/ViewExtensions.kt @@ -0,0 +1,163 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-10-17. + */ + +package pl.szczodrzynski.edziennik.ext + +import android.content.Context +import android.content.res.Resources +import android.graphics.Rect +import android.view.View +import android.view.WindowManager +import android.widget.* +import androidx.annotation.StringRes +import androidx.recyclerview.widget.RecyclerView +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout +import androidx.viewpager.widget.ViewPager +import com.google.android.material.button.MaterialButton + +fun TextView.setText(@StringRes resid: Int, vararg formatArgs: Any) { + text = context.getString(resid, *formatArgs) +} + +@Suppress("UNCHECKED_CAST") +inline fun T.onClick(crossinline onClickListener: (v: T) -> Unit) { + setOnClickListener { v: View -> + onClickListener(v as T) + } +} + +@Suppress("UNCHECKED_CAST") +inline fun T.onLongClick(crossinline onLongClickListener: (v: T) -> Boolean) { + setOnLongClickListener { v: View -> + onLongClickListener(v as T) + } +} + +@Suppress("UNCHECKED_CAST") +inline fun T.onChange(crossinline onChangeListener: (v: T, isChecked: Boolean) -> Unit) { + setOnCheckedChangeListener { buttonView, isChecked -> + onChangeListener(buttonView as T, isChecked) + } +} + +@Suppress("UNCHECKED_CAST") +inline fun T.onChange(crossinline onChangeListener: (v: T, isChecked: Boolean) -> Unit) { + clearOnCheckedChangeListeners() + addOnCheckedChangeListener { buttonView, isChecked -> + onChangeListener(buttonView as T, isChecked) + } +} + +fun View.attachToastHint(stringRes: Int) = onLongClick { + Toast.makeText(it.context, stringRes, Toast.LENGTH_SHORT).show() + true +} + +fun View.detachToastHint() = setOnLongClickListener(null) + +/** + * Convert a value in dp to pixels. + */ +val Int.dp: Int + get() = (this * Resources.getSystem().displayMetrics.density).toInt() +/** + * Convert a value in pixels to dp. + */ +val Int.px: Int + get() = (this / Resources.getSystem().displayMetrics.density).toInt() + +fun View.findParentById(targetId: Int): View? { + if (id == targetId) { + return this + } + val viewParent = this.parent ?: return null + if (viewParent is View) { + return viewParent.findParentById(targetId) + } + return null +} + +fun CheckBox.trigger() { isChecked = !isChecked } + +inline fun RadioButton.setOnSelectedListener(crossinline listener: (buttonView: CompoundButton) -> Unit) + = setOnCheckedChangeListener { buttonView, isChecked -> if (isChecked) listener(buttonView) } + +fun TextView.getTextPosition(range: IntRange): Rect { + val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager + + // Initialize global value + var parentTextViewRect = Rect() + + // Initialize values for the computing of clickedText position + //val completeText = parentTextView.text as SpannableString + val textViewLayout = this.layout + + val startOffsetOfClickedText = range.first//completeText.getSpanStart(clickedText) + val endOffsetOfClickedText = range.last//completeText.getSpanEnd(clickedText) + var startXCoordinatesOfClickedText = textViewLayout.getPrimaryHorizontal(startOffsetOfClickedText) + var endXCoordinatesOfClickedText = textViewLayout.getPrimaryHorizontal(endOffsetOfClickedText) + + // Get the rectangle of the clicked text + val currentLineStartOffset = textViewLayout.getLineForOffset(startOffsetOfClickedText) + val currentLineEndOffset = textViewLayout.getLineForOffset(endOffsetOfClickedText) + val keywordIsInMultiLine = currentLineStartOffset != currentLineEndOffset + textViewLayout.getLineBounds(currentLineStartOffset, parentTextViewRect) + + // Update the rectangle position to his real position on screen + val parentTextViewLocation = intArrayOf(0, 0) + this.getLocationOnScreen(parentTextViewLocation) + + val parentTextViewTopAndBottomOffset = (parentTextViewLocation[1] - this.scrollY + this.compoundPaddingTop) + parentTextViewRect.top += parentTextViewTopAndBottomOffset + parentTextViewRect.bottom += parentTextViewTopAndBottomOffset + + // In the case of multi line text, we have to choose what rectangle take + if (keywordIsInMultiLine) { + val screenHeight = windowManager.defaultDisplay.height + val dyTop = parentTextViewRect.top + val dyBottom = screenHeight - parentTextViewRect.bottom + val onTop = dyTop > dyBottom + + if (onTop) { + endXCoordinatesOfClickedText = textViewLayout.getLineRight(currentLineStartOffset); + } else { + parentTextViewRect = Rect() + textViewLayout.getLineBounds(currentLineEndOffset, parentTextViewRect); + parentTextViewRect.top += parentTextViewTopAndBottomOffset; + parentTextViewRect.bottom += parentTextViewTopAndBottomOffset; + startXCoordinatesOfClickedText = textViewLayout.getLineLeft(currentLineEndOffset); + } + } + + parentTextViewRect.left += ( + parentTextViewLocation[0] + + startXCoordinatesOfClickedText + + this.compoundPaddingLeft - + this.scrollX + ).toInt() + parentTextViewRect.right = ( + parentTextViewRect.left + + endXCoordinatesOfClickedText - + startXCoordinatesOfClickedText + ).toInt() + + return parentTextViewRect +} + +inline fun ViewPager.addOnPageSelectedListener(crossinline block: (position: Int) -> Unit) = addOnPageChangeListener(object : ViewPager.OnPageChangeListener { + override fun onPageScrollStateChanged(state: Int) {} + override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} + override fun onPageSelected(position: Int) { block(position) } +}) + +val SwipeRefreshLayout.onScrollListener: RecyclerView.OnScrollListener + get() = object : RecyclerView.OnScrollListener() { + override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { + if (recyclerView.canScrollVertically(-1)) + this@onScrollListener.isEnabled = false + if (!recyclerView.canScrollVertically(-1) && newState == RecyclerView.SCROLL_STATE_IDLE) + this@onScrollListener.isEnabled = true + } + } + diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/network/NetworkUtils.java b/app/src/main/java/pl/szczodrzynski/edziennik/network/NetworkUtils.java deleted file mode 100644 index dac636c6..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/network/NetworkUtils.java +++ /dev/null @@ -1,142 +0,0 @@ -package pl.szczodrzynski.edziennik.network; - -import android.content.Context; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.os.Build; - -import pl.szczodrzynski.edziennik.App; - -import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED; -import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED; -import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED; - -public class NetworkUtils { - private App app; - - public NetworkUtils(App _app) - { - this.app = _app; - } - - public boolean isOnline() { - assert app != null; - ConnectivityManager cm = - (ConnectivityManager) app.getSystemService(Context.CONNECTIVITY_SERVICE); - assert cm != null; - NetworkInfo netInfo = cm.getActiveNetworkInfo(); - return netInfo != null && netInfo.isConnectedOrConnecting(); - } - - public int checkBackgroundDataRestricted() { - - ConnectivityManager connMgr = (ConnectivityManager) app.getSystemService(Context.CONNECTIVITY_SERVICE); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - assert connMgr != null; - switch (connMgr.getRestrictBackgroundStatus()) { - case RESTRICT_BACKGROUND_STATUS_ENABLED: - return 2; - - case RESTRICT_BACKGROUND_STATUS_WHITELISTED: - return 1; - - case RESTRICT_BACKGROUND_STATUS_DISABLED: - return 0; - } - } - else - { - return 0; - } - return 0; - } - - /*public void setSelfSignedSSL(Context mContext, @Nullable String instanceName){ - try { - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - // cert file stored in \app\src\main\assets - Log.d("ION", "certificate: before"); - AssetManager am = mContext.getAssets(); - InputStream caInput = new BufferedInputStream(am.open("certificate.cer")); - Log.d("ION", "certificate: after"); - - Certificate ca = cf.generateCertificate(caInput); - caInput.close(); - - KeyStore keyStore = KeyStore.getInstance("BKS"); - keyStore.load(null, null); - keyStore.setCertificateEntry("ca", ca); - - String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); - tmf.init(keyStore); - - TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(tmf.getTrustManagers()); - - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(null, wrappedTrustManagers, null); - - AsyncSSLSocketMiddleware sslMiddleWare; - if(TextUtils.isEmpty(instanceName)){ - sslMiddleWare = Ion.getDefault(mContext).getHttpClient().getSSLSocketMiddleware(); - }else { - sslMiddleWare = Ion - .getInstance(mContext, instanceName) - .getHttpClient().getSSLSocketMiddleware(); - } - sslMiddleWare.setTrustManagers(wrappedTrustManagers); - sslMiddleWare.setHostnameVerifier(getHostnameVerifier()); - sslMiddleWare.setSSLContext(sslContext); - }catch (Exception e){ - e.printStackTrace(); - } - } - - private HostnameVerifier getHostnameVerifier() { - return new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - // or the following: - // HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier(); - // return hv.verify("www.yourserver.com", session); - } - }; - } - - public TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers) { - final X509TrustManager originalTrustManager = (X509TrustManager) trustManagers[0]; - return new TrustManager[]{ - new X509TrustManager() { - public X509Certificate[] getAcceptedIssuers() { - return originalTrustManager.getAcceptedIssuers(); - } - - public void checkClientTrusted(X509Certificate[] certs, String authType) { - try { - if (certs != null && certs.length > 0){ - certs[0].checkValidity(); - } else { - originalTrustManager.checkClientTrusted(certs, authType); - } - } catch (CertificateException e) { - Log.w("checkClientTrusted", e.toString()); - } - } - - public void checkServerTrusted(X509Certificate[] certs, String authType) { - try { - if (certs != null && certs.length > 0){ - certs[0].checkValidity(); - } else { - originalTrustManager.checkServerTrusted(certs, authType); - } - } catch (CertificateException e) { - Log.w("checkServerTrusted", e.toString()); - } - } - } - }; - }*/ -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/network/TLSSocketFactory.java b/app/src/main/java/pl/szczodrzynski/edziennik/network/TLSSocketFactory.java deleted file mode 100644 index 7cae49a2..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/network/TLSSocketFactory.java +++ /dev/null @@ -1,421 +0,0 @@ -package pl.szczodrzynski.edziennik.network; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.SocketException; -import java.net.UnknownHostException; -import java.nio.channels.SocketChannel; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.net.ssl.HandshakeCompletedListener; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; - -/** - * Enables TLS v1.2 when creating SSLSockets. - *

    - * For some reason, android supports TLS v1.2 from API 16, but enables it by - * default only from API 20. - * @link https://developer.android.com/reference/javax/net/ssl/SSLSocket.html - * @see SSLSocketFactory - */ -public class TLSSocketFactory extends SSLSocketFactory { - private static final String[] TLS_V12 = {"TLSv1.2"}; - private static final String[] TLS_V11_V12 = {"TLSv1.1", "TLSv1.2"}; - private static final String[] TLS_V10_V11_V12 = {"TLSv1", "TLSv1.1", "TLSv1.2"}; - - private final SSLSocketFactory delegate; - - public TLSSocketFactory(SSLSocketFactory base) { - this.delegate = base; - } - - @Override - public String[] getDefaultCipherSuites() { - return delegate.getDefaultCipherSuites(); - } - - @Override - public String[] getSupportedCipherSuites() { - return delegate.getSupportedCipherSuites(); - } - - @Override - public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { - return patch(delegate.createSocket(s, host, port, autoClose)); - } - - @Override - public Socket createSocket(String host, int port) throws IOException, UnknownHostException { - return patch(delegate.createSocket(host, port)); - } - - @Override - public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException { - return patch(delegate.createSocket(host, port, localHost, localPort)); - } - - @Override - public Socket createSocket(InetAddress host, int port) throws IOException { - return patch(delegate.createSocket(host, port)); - } - - @Override - public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { - return patch(delegate.createSocket(address, port, localAddress, localPort)); - } - - private Socket patch(Socket socket) { - if (socket instanceof SSLSocket) { - ((SSLSocket) socket).setEnabledProtocols(TLS_V10_V11_V12); - //socket = new NoSSLv3SSLSocket((SSLSocket) socket); - } - return socket; - } - - - public class DelegateSSLSocket extends SSLSocket { - - protected final SSLSocket delegate; - - DelegateSSLSocket(SSLSocket delegate) { - this.delegate = delegate; - } - - @Override - public String[] getSupportedCipherSuites() { - return delegate.getSupportedCipherSuites(); - } - - @Override - public String[] getEnabledCipherSuites() { - return delegate.getEnabledCipherSuites(); - } - - @Override - public void setEnabledCipherSuites(String[] suites) { - delegate.setEnabledCipherSuites(suites); - } - - @Override - public String[] getSupportedProtocols() { - return delegate.getSupportedProtocols(); - } - - @Override - public String[] getEnabledProtocols() { - return delegate.getEnabledProtocols(); - } - - @Override - public void setEnabledProtocols(String[] protocols) { - delegate.setEnabledProtocols(protocols); - } - - @Override - public SSLSession getSession() { - return delegate.getSession(); - } - - @Override - public void addHandshakeCompletedListener(HandshakeCompletedListener listener) { - delegate.addHandshakeCompletedListener(listener); - } - - @Override - public void removeHandshakeCompletedListener(HandshakeCompletedListener listener) { - delegate.removeHandshakeCompletedListener(listener); - } - - @Override - public void startHandshake() throws IOException { - delegate.startHandshake(); - } - - @Override - public void setUseClientMode(boolean mode) { - delegate.setUseClientMode(mode); - } - - @Override - public boolean getUseClientMode() { - return delegate.getUseClientMode(); - } - - @Override - public void setNeedClientAuth(boolean need) { - delegate.setNeedClientAuth(need); - } - - @Override - public void setWantClientAuth(boolean want) { - delegate.setWantClientAuth(want); - } - - @Override - public boolean getNeedClientAuth() { - return delegate.getNeedClientAuth(); - } - - @Override - public boolean getWantClientAuth() { - return delegate.getWantClientAuth(); - } - - @Override - public void setEnableSessionCreation(boolean flag) { - delegate.setEnableSessionCreation(flag); - } - - @Override - public boolean getEnableSessionCreation() { - return delegate.getEnableSessionCreation(); - } - - @Override - public void bind(SocketAddress localAddr) throws IOException { - delegate.bind(localAddr); - } - - @Override - public synchronized void close() throws IOException { - delegate.close(); - } - - @Override - public void connect(SocketAddress remoteAddr) throws IOException { - delegate.connect(remoteAddr); - } - - @Override - public void connect(SocketAddress remoteAddr, int timeout) throws IOException { - delegate.connect(remoteAddr, timeout); - } - - @Override - public SocketChannel getChannel() { - return delegate.getChannel(); - } - - @Override - public InetAddress getInetAddress() { - return delegate.getInetAddress(); - } - - @Override - public InputStream getInputStream() throws IOException { - return delegate.getInputStream(); - } - - @Override - public boolean getKeepAlive() throws SocketException { - return delegate.getKeepAlive(); - } - - @Override - public InetAddress getLocalAddress() { - return delegate.getLocalAddress(); - } - - @Override - public int getLocalPort() { - return delegate.getLocalPort(); - } - - @Override - public SocketAddress getLocalSocketAddress() { - return delegate.getLocalSocketAddress(); - } - - @Override - public boolean getOOBInline() throws SocketException { - return delegate.getOOBInline(); - } - - @Override - public OutputStream getOutputStream() throws IOException { - return delegate.getOutputStream(); - } - - @Override - public int getPort() { - return delegate.getPort(); - } - - @Override - public synchronized int getReceiveBufferSize() throws SocketException { - return delegate.getReceiveBufferSize(); - } - - @Override - public SocketAddress getRemoteSocketAddress() { - return delegate.getRemoteSocketAddress(); - } - - @Override - public boolean getReuseAddress() throws SocketException { - return delegate.getReuseAddress(); - } - - @Override - public synchronized int getSendBufferSize() throws SocketException { - return delegate.getSendBufferSize(); - } - - @Override - public int getSoLinger() throws SocketException { - return delegate.getSoLinger(); - } - - @Override - public synchronized int getSoTimeout() throws SocketException { - return delegate.getSoTimeout(); - } - - @Override - public boolean getTcpNoDelay() throws SocketException { - return delegate.getTcpNoDelay(); - } - - @Override - public int getTrafficClass() throws SocketException { - return delegate.getTrafficClass(); - } - - @Override - public boolean isBound() { - return delegate.isBound(); - } - - @Override - public boolean isClosed() { - return delegate.isClosed(); - } - - @Override - public boolean isConnected() { - return delegate.isConnected(); - } - - @Override - public boolean isInputShutdown() { - return delegate.isInputShutdown(); - } - - @Override - public boolean isOutputShutdown() { - return delegate.isOutputShutdown(); - } - - @Override - public void sendUrgentData(int value) throws IOException { - delegate.sendUrgentData(value); - } - - @Override - public void setKeepAlive(boolean keepAlive) throws SocketException { - delegate.setKeepAlive(keepAlive); - } - - @Override - public void setOOBInline(boolean oobinline) throws SocketException { - delegate.setOOBInline(oobinline); - } - - @Override - public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) { - delegate.setPerformancePreferences(connectionTime, latency, bandwidth); - } - - @Override - public synchronized void setReceiveBufferSize(int size) throws SocketException { - delegate.setReceiveBufferSize(size); - } - - @Override - public void setReuseAddress(boolean reuse) throws SocketException { - delegate.setReuseAddress(reuse); - } - - @Override - public synchronized void setSendBufferSize(int size) throws SocketException { - delegate.setSendBufferSize(size); - } - - @Override - public void setSoLinger(boolean on, int timeout) throws SocketException { - delegate.setSoLinger(on, timeout); - } - - @Override - public synchronized void setSoTimeout(int timeout) throws SocketException { - delegate.setSoTimeout(timeout); - } - - @Override - public void setTcpNoDelay(boolean on) throws SocketException { - delegate.setTcpNoDelay(on); - } - - @Override - public void setTrafficClass(int value) throws SocketException { - delegate.setTrafficClass(value); - } - - @Override - public void shutdownInput() throws IOException { - delegate.shutdownInput(); - } - - @Override - public void shutdownOutput() throws IOException { - delegate.shutdownOutput(); - } - - @Override - public String toString() { - return delegate.toString(); - } - - @Override - public boolean equals(Object o) { - return delegate.equals(o); - } - } - - private class NoSSLv3SSLSocket extends DelegateSSLSocket { - - private NoSSLv3SSLSocket(SSLSocket delegate) { - super(delegate); - - } - - @Override - public void setEnabledProtocols(String[] protocols) { - if (protocols != null && protocols.length == 1 && "SSLv3".equals(protocols[0])) { - - List enabledProtocols = new ArrayList<>(Arrays.asList(delegate.getEnabledProtocols())); - if (enabledProtocols.size() > 1) { - if (enabledProtocols.remove("SSLv3")) { - System.out.println("Removed SSLv3 from enabled protocols"); - } - else { - System.out.println("SSLv3 was not an enabled protocol"); - } - } else { - System.out.println("SSL stuck with protocol available for " + String.valueOf(enabledProtocols)); - } - protocols = enabledProtocols.toArray(new String[enabledProtocols.size()]); - } - - super.setEnabledProtocols(protocols); - } - } -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/network/cookie/DumbCookieJar.kt b/app/src/main/java/pl/szczodrzynski/edziennik/network/cookie/DumbCookieJar.kt index ca11996f..39cec6eb 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/network/cookie/DumbCookieJar.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/network/cookie/DumbCookieJar.kt @@ -26,7 +26,7 @@ class DumbCookieJar( ) : CookieJar { private val prefs = context.getSharedPreferences("cookies", Context.MODE_PRIVATE) - private val sessionCookies = mutableSetOf() + val sessionCookies = mutableSetOf() private val savedCookies = mutableSetOf() private fun save(dc: DumbCookie) { sessionCookies.remove(dc) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/receivers/SzkolnyReceiver.kt b/app/src/main/java/pl/szczodrzynski/edziennik/receivers/SzkolnyReceiver.kt index f456bae3..f7819c43 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/receivers/SzkolnyReceiver.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/receivers/SzkolnyReceiver.kt @@ -7,6 +7,7 @@ package pl.szczodrzynski.edziennik.receivers import android.content.BroadcastReceiver import android.content.Context import android.content.Intent +import android.os.Bundle import pl.szczodrzynski.edziennik.data.api.ApiService import pl.szczodrzynski.edziennik.data.api.edziennik.EdziennikTask import pl.szczodrzynski.edziennik.data.api.events.requests.ServiceCloseRequest @@ -15,6 +16,11 @@ import pl.szczodrzynski.edziennik.data.api.events.requests.TaskCancelRequest class SzkolnyReceiver : BroadcastReceiver() { companion object { const val ACTION = "pl.szczodrzynski.edziennik.SZKOLNY_MAIN" + fun getIntent(context: Context, extras: Bundle): Intent { + val intent = Intent(context, SzkolnyReceiver::class.java) + intent.putExtras(extras) + return intent + } } override fun onReceive(context: Context?, intent: Intent?) { diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/sync/SyncWorker.kt b/app/src/main/java/pl/szczodrzynski/edziennik/sync/SyncWorker.kt index 05a03fbc..3a2a5f40 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/sync/SyncWorker.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/sync/SyncWorker.kt @@ -5,7 +5,7 @@ import android.content.Context import androidx.work.* import pl.szczodrzynski.edziennik.App import pl.szczodrzynski.edziennik.data.api.edziennik.EdziennikTask -import pl.szczodrzynski.edziennik.formatDate +import pl.szczodrzynski.edziennik.ext.formatDate import pl.szczodrzynski.edziennik.utils.Utils.d import java.util.concurrent.TimeUnit diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/sync/UpdateWorker.kt b/app/src/main/java/pl/szczodrzynski/edziennik/sync/UpdateWorker.kt index 377ab806..0df0bc83 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/sync/UpdateWorker.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/sync/UpdateWorker.kt @@ -9,16 +9,21 @@ import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent -import android.text.Html import android.widget.Toast import androidx.core.app.NotificationCompat import androidx.work.* import kotlinx.coroutines.* +import org.greenrobot.eventbus.EventBus import pl.szczodrzynski.edziennik.* import pl.szczodrzynski.edziennik.R import pl.szczodrzynski.edziennik.data.api.szkolny.SzkolnyApi import pl.szczodrzynski.edziennik.data.api.szkolny.response.Update +import pl.szczodrzynski.edziennik.ext.DAY +import pl.szczodrzynski.edziennik.ext.concat +import pl.szczodrzynski.edziennik.ext.formatDate +import pl.szczodrzynski.edziennik.ext.pendingIntentFlag import pl.szczodrzynski.edziennik.utils.Utils +import pl.szczodrzynski.edziennik.utils.html.BetterHtml import java.util.concurrent.TimeUnit import kotlin.coroutines.CoroutineContext @@ -76,7 +81,7 @@ class UpdateWorker(val context: Context, val params: WorkerParameters) : Worker( try { val update = overrideUpdate ?: run { - val updates = withContext(Dispatchers.Default) { + withContext(Dispatchers.Default) { SzkolnyApi(app).runCatching({ getUpdate("beta") }, { @@ -84,18 +89,28 @@ class UpdateWorker(val context: Context, val params: WorkerParameters) : Worker( }) } ?: return@run null - if (updates.isEmpty()) { + if (app.config.update == null + || app.config.update?.versionCode ?: BuildConfig.VERSION_CODE <= BuildConfig.VERSION_CODE) { app.config.update = null Toast.makeText(app, app.getString(R.string.notification_no_update), Toast.LENGTH_SHORT).show() return@run null } - updates[0] + app.config.update } ?: return - app.config.update = update + if (update.versionCode <= BuildConfig.VERSION_CODE) { + app.config.update = null + return + } + + if (EventBus.getDefault().hasSubscriberForEvent(update::class.java)) { + if (!update.updateMandatory) // mandatory updates are posted by the SzkolnyApi + EventBus.getDefault().postSticky(update) + return + } val notificationIntent = Intent(app, UpdateDownloaderService::class.java) - val pendingIntent = PendingIntent.getService(app, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT) + val pendingIntent = PendingIntent.getService(app, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT or pendingIntentFlag()) val notification = NotificationCompat.Builder(app, app.notificationChannelsManager.updates.key) .setContentTitle(app.getString(R.string.notification_updates_title)) .setContentText(app.getString(R.string.notification_updates_text, update.versionName)) @@ -104,7 +119,7 @@ class UpdateWorker(val context: Context, val params: WorkerParameters) : Worker( .setStyle(NotificationCompat.BigTextStyle() .bigText(listOf( app.getString(R.string.notification_updates_text, update.versionName), - update.releaseNotes?.let { Html.fromHtml(it) } + update.releaseNotes?.let { BetterHtml.fromHtml(context = null, it) } ).concat("\n"))) .setColor(0xff2196f3.toInt()) .setLights(0xFF00FFFF.toInt(), 2000, 2000) diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/sync/WorkerUtils.kt b/app/src/main/java/pl/szczodrzynski/edziennik/sync/WorkerUtils.kt index 0eaa65eb..e8266a64 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/sync/WorkerUtils.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/sync/WorkerUtils.kt @@ -11,8 +11,8 @@ import androidx.work.WorkManager import androidx.work.impl.WorkManagerImpl import org.greenrobot.eventbus.EventBus import pl.szczodrzynski.edziennik.App -import pl.szczodrzynski.edziennik.MINUTE -import pl.szczodrzynski.edziennik.formatDate +import pl.szczodrzynski.edziennik.ext.MINUTE +import pl.szczodrzynski.edziennik.ext.formatDate import pl.szczodrzynski.edziennik.utils.Utils object WorkerUtils { diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/TemplateAdapter.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/TemplateAdapter.kt deleted file mode 100644 index 8366862e..00000000 --- a/app/src/main/java/pl/szczodrzynski/edziennik/ui/TemplateAdapter.kt +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) Kuba Szczodrzyński 2019-12-19. - */ - -package pl.szczodrzynski.edziennik.ui - -import android.content.Context -import android.view.LayoutInflater -import android.view.ViewGroup -import androidx.recyclerview.widget.RecyclerView -import pl.szczodrzynski.edziennik.App -import pl.szczodrzynski.edziennik.databinding.TemplateListItemBinding -import pl.szczodrzynski.edziennik.onClick - -class TemplateAdapter( - val context: Context, - val onItemClick: ((item: TemplateItem) -> Unit)? = null, - val onItemButtonClick: ((item: TemplateItem) -> Unit)? = null -) : RecyclerView.Adapter() { - - private val app by lazy { context.applicationContext as App } - - var items = listOf() - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { - val inflater = LayoutInflater.from(parent.context) - val view = TemplateListItemBinding.inflate(inflater, parent, false) - return ViewHolder(view) - } - - override fun onBindViewHolder(holder: ViewHolder, position: Int) { - val item = items[position] - val b = holder.b - - onItemClick?.let { listener -> - b.root.onClick { listener(item) } - } - - /*b.someButton.visibility = if (buttonVisible) View.VISIBLE else View.GONE - onItemButtonClick?.let { listener -> - b.someButton.onClick { listener(item) } - }*/ - } - - override fun getItemCount() = items.size - - class ViewHolder(val b: TemplateListItemBinding) : RecyclerView.ViewHolder(b.root) - - data class TemplateItem(val text: String) -} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/AgendaFragment.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/AgendaFragment.kt new file mode 100644 index 00000000..83d89e67 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/AgendaFragment.kt @@ -0,0 +1,196 @@ +/* + * Copyright (c) Kacper Ziubryniewicz 2020-1-25 + */ + +package pl.szczodrzynski.edziennik.ui.agenda + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.databinding.ViewDataBinding +import androidx.fragment.app.Fragment +import com.applandeo.materialcalendarview.EventDay +import com.mikepenz.iconics.IconicsDrawable +import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial +import com.mikepenz.iconics.utils.colorInt +import com.mikepenz.iconics.utils.sizeDp +import eu.szkolny.font.SzkolnyFont +import kotlinx.coroutines.* +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.MainActivity +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.db.entity.EventType +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.databinding.FragmentAgendaCalendarBinding +import pl.szczodrzynski.edziennik.databinding.FragmentAgendaDefaultBinding +import pl.szczodrzynski.edziennik.ui.dialogs.settings.AgendaConfigDialog +import pl.szczodrzynski.edziennik.ui.event.EventManualDialog +import pl.szczodrzynski.edziennik.utils.Themes +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.navlib.bottomsheet.items.BottomSheetPrimaryItem +import pl.szczodrzynski.navlib.bottomsheet.items.BottomSheetSeparatorItem +import java.util.* +import kotlin.coroutines.CoroutineContext + +class AgendaFragment : Fragment(), CoroutineScope { + + private lateinit var activity: MainActivity + private lateinit var b: ViewDataBinding + + private val app by lazy { activity.app } + + private var job = Job() + override val coroutineContext: CoroutineContext + get() = job + Dispatchers.Main + + private var type: Int = Profile.AGENDA_DEFAULT + + private var agendaDefault: AgendaFragmentDefault? = null + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + if (getActivity() == null || context == null) return null + activity = getActivity() as MainActivity + context?.theme?.applyStyle(Themes.appTheme, true) + type = app.config.forProfile().ui.agendaViewType + b = when (type) { + Profile.AGENDA_DEFAULT -> FragmentAgendaDefaultBinding.inflate(inflater, container, false) + Profile.AGENDA_CALENDAR -> FragmentAgendaCalendarBinding.inflate(inflater, container, false) + else -> return null + } + return b.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + if (!isAdded) return + + activity.bottomSheet.prependItems( + BottomSheetPrimaryItem(true) + .withTitle(R.string.menu_add_event) + .withDescription(R.string.menu_add_event_desc) + .withIcon(SzkolnyFont.Icon.szf_calendar_plus_outline) + .withOnClickListener { + activity.bottomSheet.close() + EventManualDialog( + activity, + app.profileId, + defaultDate = AgendaFragmentDefault.selectedDate + ).show() + }, + BottomSheetPrimaryItem(true) + .withTitle(R.string.menu_agenda_config) + .withIcon(CommunityMaterial.Icon.cmd_cog_outline) + .withOnClickListener { + activity.bottomSheet.close() + AgendaConfigDialog(activity, true, null, null).show() + }, + BottomSheetPrimaryItem(true) + .withTitle(R.string.menu_agenda_change_view) + .withIcon(if (type == Profile.AGENDA_DEFAULT) CommunityMaterial.Icon.cmd_calendar_outline else CommunityMaterial.Icon2.cmd_format_list_bulleted_square) + .withOnClickListener { + activity.bottomSheet.close() + type = + if (type == Profile.AGENDA_DEFAULT) Profile.AGENDA_CALENDAR else Profile.AGENDA_DEFAULT + app.config.forProfile().ui.agendaViewType = type + activity.reloadTarget() + }, + BottomSheetSeparatorItem(true), + BottomSheetPrimaryItem(true) + .withTitle(R.string.menu_mark_as_read) + .withIcon(CommunityMaterial.Icon.cmd_eye_check_outline) + .withOnClickListener { + launch { + activity.bottomSheet.close() + withContext(Dispatchers.Default) { + App.db.metadataDao() + .setAllSeen(app.profileId, Metadata.TYPE_EVENT, true) + } + Toast.makeText( + activity, + R.string.main_menu_mark_as_read_success, + Toast.LENGTH_SHORT + ).show() + } + } + ) + + activity.navView.bottomBar.fabEnable = true + activity.navView.bottomBar.fabExtendedText = getString(R.string.add) + activity.navView.bottomBar.fabIcon = CommunityMaterial.Icon3.cmd_plus + activity.navView.setFabOnClickListener { + EventManualDialog( + activity, + app.profileId, + defaultDate = AgendaFragmentDefault.selectedDate + ).show() + } + + activity.gainAttention() + activity.gainAttentionFAB() + + when (type) { + Profile.AGENDA_DEFAULT -> createDefaultAgendaView() + Profile.AGENDA_CALENDAR -> createCalendarAgendaView() + } + } + + private suspend fun checkEventTypes() { + withContext(Dispatchers.Default) { + val eventTypes = app.db.eventTypeDao().getAllNow(app.profileId).map { + it.id + } + val defaultEventTypes = EventType.getTypeColorMap().keys + if (!eventTypes.containsAll(defaultEventTypes)) { + app.db.eventTypeDao().addDefaultTypes(activity, app.profileId) + } + } + } + + private fun createDefaultAgendaView() { (b as? FragmentAgendaDefaultBinding)?.let { b -> launch { + if (!isAdded) + return@launch + checkEventTypes() + delay(500) + + agendaDefault = AgendaFragmentDefault(activity, app, b) + agendaDefault?.initView(this@AgendaFragment) + }}} + + private fun createCalendarAgendaView() { (b as? FragmentAgendaCalendarBinding)?.let { b -> launch { + checkEventTypes() + delay(300) + + val dayList = mutableListOf() + + val events = withContext(Dispatchers.Default) { app.db.eventDao().getAllNow(app.profileId) } + val unreadEventDates = mutableSetOf() + + events.forEach { event -> + val eventIcon = IconicsDrawable(activity).apply { + icon = CommunityMaterial.Icon.cmd_checkbox_blank_circle + sizeDp = 10 + colorInt = event.eventColor + } + + dayList.add(EventDay(event.startTimeCalendar, eventIcon)) + + if (!event.seen) unreadEventDates.add(event.date.value) + } + + b.agendaCalendarView.setEvents(dayList) + b.agendaCalendarView.setOnDayClickListener { day -> this@AgendaFragment.launch { + val date = Date.fromCalendar(day.calendar) + + if (date.value in unreadEventDates) { + withContext(Dispatchers.Default) { app.db.eventDao().setSeenByDate(app.profileId, date, true) } + unreadEventDates.remove(date.value) + } + + DayDialog(activity, app.profileId, date).show() + }} + + b.progressBar.visibility = View.GONE + }}} +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/AgendaFragmentDefault.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/AgendaFragmentDefault.kt new file mode 100644 index 00000000..d51e2e70 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/AgendaFragmentDefault.kt @@ -0,0 +1,318 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-4-8. + */ + +package pl.szczodrzynski.edziennik.ui.agenda + +import android.util.SparseIntArray +import android.widget.AbsListView +import android.widget.AbsListView.OnScrollListener +import androidx.core.util.forEach +import androidx.core.util.set +import androidx.core.view.isVisible +import com.github.tibolte.agendacalendarview.CalendarManager +import com.github.tibolte.agendacalendarview.CalendarPickerController +import com.github.tibolte.agendacalendarview.agenda.AgendaAdapter +import com.github.tibolte.agendacalendarview.models.BaseCalendarEvent +import com.github.tibolte.agendacalendarview.models.CalendarEvent +import com.github.tibolte.agendacalendarview.models.IDayItem +import kotlinx.coroutines.* +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.MainActivity +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.databinding.FragmentAgendaDefaultBinding +import pl.szczodrzynski.edziennik.ui.agenda.event.AgendaEvent +import pl.szczodrzynski.edziennik.ui.agenda.event.AgendaEventGroup +import pl.szczodrzynski.edziennik.ui.agenda.event.AgendaEventGroupRenderer +import pl.szczodrzynski.edziennik.ui.agenda.event.AgendaEventRenderer +import pl.szczodrzynski.edziennik.ui.agenda.lessonchanges.LessonChangesDialog +import pl.szczodrzynski.edziennik.ui.agenda.lessonchanges.LessonChangesEvent +import pl.szczodrzynski.edziennik.ui.agenda.lessonchanges.LessonChangesEventRenderer +import pl.szczodrzynski.edziennik.ui.agenda.teacherabsence.TeacherAbsenceDialog +import pl.szczodrzynski.edziennik.ui.agenda.teacherabsence.TeacherAbsenceEvent +import pl.szczodrzynski.edziennik.ui.agenda.teacherabsence.TeacherAbsenceEventRenderer +import pl.szczodrzynski.edziennik.ui.event.EventDetailsDialog +import pl.szczodrzynski.edziennik.utils.models.Date +import java.util.* + +class AgendaFragmentDefault( + private val activity: MainActivity, + private val app: App, + private val b: FragmentAgendaDefaultBinding +) : OnScrollListener, CoroutineScope { + companion object { + var selectedDate: Date = Date.getToday() + } + + override val coroutineContext = Job() + Dispatchers.Main + + private val unreadDates = mutableSetOf() + private val events = mutableListOf() + private var isInitialized = false + private val profileConfig by lazy { app.config.forProfile().ui } + + private val listView + get() = b.agendaDefaultView.agendaView.agendaListView + private val adapter + get() = listView.adapter as? AgendaAdapter + private val manager + get() = CalendarManager.getInstance() + + private var scrollState = OnScrollListener.SCROLL_STATE_IDLE + private var updatePending = false + private var notifyPending = false + override fun onScrollStateChanged(view: AbsListView?, newScrollState: Int) { + b.agendaDefaultView.agendaScrollListener.onScrollStateChanged(view, scrollState) + scrollState = newScrollState + if (updatePending) updateData() + if (notifyPending) notifyDataSetChanged() + } + + override fun onScroll( + view: AbsListView?, + firstVisibleItem: Int, + visibleItemCount: Int, + totalItemCount: Int + ) = b.agendaDefaultView.agendaScrollListener.onScroll( + view, + firstVisibleItem, + visibleItemCount, + totalItemCount + ) + + /** + * Mark the data as needing update, either after 1 second (when + * not scrolling) or 1 second after scrolling stops. + */ + private fun updateData() = launch { + if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { + updatePending = false + delay(1000) + notifyDataSetChanged() + } else updatePending = true + } + + /** + * Notify the adapter about changes, either instantly or after + * scrolling stops. + */ + private fun notifyDataSetChanged() { + if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { + notifyPending = false + adapter?.notifyDataSetChanged() + } else notifyPending = true + } + + suspend fun initView(fragment: AgendaFragment) { + isInitialized = false + + withContext(Dispatchers.Default) { + if (profileConfig.agendaLessonChanges) + addLessonChanges(events) + + if (profileConfig.agendaTeacherAbsence) + addTeacherAbsence(events) + } + + app.db.eventDao().getAll(app.profileId).observe(fragment) { + addEvents(events, it) + if (isInitialized) + updateView() + else + initViewPriv() + } + } + + private fun initViewPriv() { + val dateStart = app.profile.dateSemester1Start.asCalendar + val dateEnd = app.profile.dateYearEnd.asCalendar + + val isCompactMode = profileConfig.agendaCompactMode + + b.agendaDefaultView.init( + events, + dateStart, + dateEnd, + Locale.getDefault(), + object : CalendarPickerController { + override fun onDaySelected(dayItem: IDayItem) { + val c = Calendar.getInstance() + c.time = dayItem.date + if (c.timeInMillis == selectedDate.inMillis) { + DayDialog(activity, app.profileId, selectedDate).show() + } + } + + override fun onEventSelected(event: CalendarEvent) { + val date = Date.fromCalendar(event.instanceDay) + + when (event) { + is AgendaEvent -> EventDetailsDialog(activity, event.event).show() + is LessonChangesEvent -> LessonChangesDialog( + activity = activity, + profileId = app.profileId, + defaultDate = date + ).show() + is TeacherAbsenceEvent -> TeacherAbsenceDialog( + activity = activity, + profileId = app.profileId, + date = date + ).show() + is AgendaEventGroup -> DayDialog( + activity = activity, + profileId = app.profileId, + date = date, + eventTypeId = event.typeId, + ).show() + is BaseCalendarEvent -> if (event.isPlaceHolder) + DayDialog(activity, app.profileId, date).show() + } + + if (event is BaseEvent && event.showItemBadge) { + val unreadCount = manager.events.count { + it.instanceDay.equals(event.instanceDay) && it.showBadge + } + // only clicked event is unread, remove the day badge + if (unreadCount == 1 && event.showBadge) { + event.dayReference.showBadge = false + unreadDates.remove(date.value) + } + setAsRead(event) + } + } + + override fun onScrollToDate(calendar: Calendar) { + selectedDate = Date.fromCalendar(calendar) + + // Mark as read scrolled date + if (selectedDate.value in unreadDates) { + setAsRead(calendar) + activity.launch(Dispatchers.Default) { + app.db.eventDao().setSeenByDate(app.profileId, selectedDate, true) + } + unreadDates.remove(selectedDate.value) + } + } + }, + AgendaEventRenderer(app.eventManager, isCompactMode), + AgendaEventGroupRenderer(), + LessonChangesEventRenderer(), + TeacherAbsenceEventRenderer() + ) + + listView.setOnScrollListener(this) + + isInitialized = true + b.progressBar.isVisible = false + } + + private fun updateView() { + manager.events.clear() + manager.loadEvents(events, BaseCalendarEvent()) + + adapter?.updateEvents(manager.events) + //listView.scrollToCurrentDate(selectedDate.asCalendar) + } + + private fun setAsRead(date: Calendar) { + // get all events matching the date + val events = manager.events.filter { + if (it.instanceDay.equals(date) && it.showBadge && it is AgendaEvent) { + // hide the day badge for the date + it.dayReference.showBadge = false + return@filter true + } + false + } + // set this date's events as read + setAsRead(*events.toTypedArray()) + } + + private fun setAsRead(vararg event: CalendarEvent) { + // hide per-event badges + for (e in event) { + events.firstOrNull { + it == e + }?.showBadge = false + e.showBadge = false + } + + listView.setOnScrollListener(this) + updateData() + } + + private fun addEvents( + events: MutableList, + eventList: List + ) { + events.removeAll { it is AgendaEvent || it is AgendaEventGroup } + + if (!profileConfig.agendaGroupByType) { + events += eventList.map { + if (!it.seen) + unreadDates.add(it.date.value) + AgendaEvent(it) + } + return + } + + eventList.groupBy { + it.date.value to it.type + }.forEach { (_, list) -> + val event = list.first() + if (list.size == 1) { + if (!event.seen) + unreadDates.add(event.date.value) + events += AgendaEvent(event) + } else { + events.add(0, AgendaEventGroup( + profileId = event.profileId, + date = event.date, + typeId = event.type, + typeName = event.typeName ?: "-", + typeColor = event.typeColor ?: event.eventColor, + count = list.size, + showBadge = list.any { !it.seen } + )) + } + } + } + + private fun addLessonChanges(events: MutableList) { + val lessons = app.db.timetableDao().getChangesNow(app.profileId) + + val grouped = lessons.groupBy { + it.displayDate + } + + events += grouped.mapNotNull { (date, changes) -> + LessonChangesEvent( + app.profileId, + date = date ?: return@mapNotNull null, + count = changes.size, + showBadge = changes.any { !it.seen } + ) + } + } + + private fun addTeacherAbsence(events: MutableList) { + val teacherAbsence = app.db.teacherAbsenceDao().getAllNow(app.profileId) + + val countMap = SparseIntArray() + + for (absence in teacherAbsence) { + while (absence.dateFrom <= absence.dateTo) { + countMap[absence.dateFrom.value] += 1 + absence.dateFrom.stepForward(0, 0, 1) + } + } + + countMap.forEach { dateInt, count -> + events += TeacherAbsenceEvent( + app.profileId, + date = Date.fromValue(dateInt), + count = count + ) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/BaseEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/BaseEvent.kt new file mode 100644 index 00000000..3f28ca40 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/BaseEvent.kt @@ -0,0 +1,66 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-4-9. + */ + +package pl.szczodrzynski.edziennik.ui.agenda + +import com.github.tibolte.agendacalendarview.models.CalendarEvent +import com.github.tibolte.agendacalendarview.models.IDayItem +import com.github.tibolte.agendacalendarview.models.IWeekItem +import java.util.* + +open class BaseEvent( + private val id: Long, + private val time: Calendar, + private val color: Int, + private var showBadge: Boolean, + var showItemBadge: Boolean = showBadge +) : CalendarEvent { + + override fun copy() = BaseEvent(id, time, color, showBadge) + + private lateinit var date: Calendar + override fun getInstanceDay() = date + override fun setInstanceDay(value: Calendar) { + date = value + } + + private lateinit var dayReference: IDayItem + override fun getDayReference() = dayReference + override fun setDayReference(value: IDayItem) { + dayReference = value + } + + private lateinit var weekReference: IWeekItem + override fun getWeekReference() = weekReference + override fun setWeekReference(value: IWeekItem) { + weekReference = value + } + + override fun getShowBadge() = showBadge + override fun setShowBadge(value: Boolean) { + showBadge = value + showItemBadge = value + } + + override fun getId() = id + override fun getStartTime() = time + override fun getEndTime() = time + override fun getTitle() = "" + override fun getDescription() = "" + override fun getLocation() = "" + override fun getColor() = color + override fun getTextColor() = 0 + override fun isPlaceholder() = false + override fun isAllDay() = false + + override fun setId(value: Long) = Unit + override fun setStartTime(value: Calendar) = Unit + override fun setEndTime(value: Calendar) = Unit + override fun setTitle(value: String) = Unit + override fun setDescription(value: String) = Unit + override fun setLocation(value: String) = Unit + override fun setTextColor(value: Int) = Unit + override fun setPlaceholder(value: Boolean) = Unit + override fun setAllDay(value: Boolean) = Unit +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/DayDialog.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/DayDialog.kt new file mode 100644 index 00000000..cacd51a1 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/DayDialog.kt @@ -0,0 +1,219 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2019-12-16. + */ + +package pl.szczodrzynski.edziennik.ui.agenda + +import android.view.LayoutInflater +import android.view.View +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.isVisible +import androidx.recyclerview.widget.LinearLayoutManager +import kotlinx.coroutines.* +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.db.entity.Lesson +import pl.szczodrzynski.edziennik.databinding.DialogDayBinding +import pl.szczodrzynski.edziennik.ext.ifNotEmpty +import pl.szczodrzynski.edziennik.ext.onClick +import pl.szczodrzynski.edziennik.ext.setText +import pl.szczodrzynski.edziennik.ui.agenda.lessonchanges.LessonChangesDialog +import pl.szczodrzynski.edziennik.ui.agenda.lessonchanges.LessonChangesEvent +import pl.szczodrzynski.edziennik.ui.agenda.lessonchanges.LessonChangesEventRenderer +import pl.szczodrzynski.edziennik.ui.agenda.teacherabsence.TeacherAbsenceDialog +import pl.szczodrzynski.edziennik.ui.agenda.teacherabsence.TeacherAbsenceEvent +import pl.szczodrzynski.edziennik.ui.agenda.teacherabsence.TeacherAbsenceEventRenderer +import pl.szczodrzynski.edziennik.ui.dialogs.base.BindingDialog +import pl.szczodrzynski.edziennik.ui.event.EventDetailsDialog +import pl.szczodrzynski.edziennik.ui.event.EventListAdapter +import pl.szczodrzynski.edziennik.ui.event.EventManualDialog +import pl.szczodrzynski.edziennik.ui.notes.setupNotesButton +import pl.szczodrzynski.edziennik.utils.SimpleDividerItemDecoration +import pl.szczodrzynski.edziennik.utils.managers.NoteManager +import pl.szczodrzynski.edziennik.utils.models.Date +import pl.szczodrzynski.edziennik.utils.models.Time +import pl.szczodrzynski.edziennik.utils.models.Week + +class DayDialog( + activity: AppCompatActivity, + private val profileId: Int, + private val date: Date, + private val eventTypeId: Long? = null, + private val showNotes: Boolean = false, + onShowListener: ((tag: String) -> Unit)? = null, + onDismissListener: ((tag: String) -> Unit)? = null, +) : BindingDialog(activity, onShowListener, onDismissListener) { + + override val TAG = "DayDialog" + + override fun getTitleRes(): Int? = null + override fun inflate(layoutInflater: LayoutInflater) = + DialogDayBinding.inflate(layoutInflater) + + override fun getPositiveButtonText() = R.string.close + override fun getNeutralButtonText() = R.string.add + + private lateinit var adapter: EventListAdapter + + override suspend fun onNeutralClick(): Boolean { + EventManualDialog( + activity, + profileId, + defaultDate = date, + onShowListener = onShowListener, + onDismissListener = onDismissListener + ).show() + return NO_DISMISS + } + + override suspend fun onShow() { + b.dayDate.setText( + R.string.dialog_day_date_format, + Week.getFullDayName(date.weekDay), + date.formattedString + ) + + val lessons = withContext(Dispatchers.Default) { + app.db.timetableDao().getAllForDateNow(profileId, date) + }.filter { it.type != Lesson.TYPE_NO_LESSONS } + + if (lessons.isNotEmpty()) { + run { + val startTime = lessons.first().startTime ?: return@run + val endTime = lessons.last().endTime ?: return@run + val diff = Time.diff(startTime, endTime) + + b.lessonsInfo.setText( + R.string.dialog_day_lessons_info, + startTime.stringHM, + endTime.stringHM, + lessons.size.toString(), + diff.hour.toString(), + diff.minute.toString() + ) + + b.lessonsInfo.visibility = View.VISIBLE + } + } + + val lessonChanges = withContext(Dispatchers.Default) { + app.db.timetableDao().getChangesForDateNow(profileId, date) + } + + lessonChanges.ifNotEmpty { + LessonChangesEventRenderer().render( + b.lessonChanges, LessonChangesEvent( + profileId = profileId, + date = date, + count = it.size, + showBadge = false + ) + ) + + b.lessonChangesFrame.onClick { + LessonChangesDialog( + activity, + profileId, + date, + onShowListener = onShowListener, + onDismissListener = onDismissListener + ).show() + } + } + b.lessonChangesFrame.isVisible = lessonChanges.isNotEmpty() + + val teacherAbsences = withContext(Dispatchers.Default) { + app.db.teacherAbsenceDao().getAllByDateNow(profileId, date) + } + + teacherAbsences.ifNotEmpty { + TeacherAbsenceEventRenderer().render( + b.teacherAbsence, TeacherAbsenceEvent( + profileId = profileId, + date = date, + count = it.size + ) + ) + + b.teacherAbsenceFrame.onClick { + TeacherAbsenceDialog( + activity, + profileId, + date, + onShowListener = onShowListener, + onDismissListener = onDismissListener + ).show() + } + } + b.teacherAbsenceFrame.isVisible = teacherAbsences.isNotEmpty() + + adapter = EventListAdapter( + activity = activity, + showWeekDay = false, + showDate = false, + showType = true, + showTime = true, + showSubject = true, + markAsSeen = true, + onEventClick = { + EventDetailsDialog( + activity, + it, + onShowListener = onShowListener, + onDismissListener = onDismissListener + ).show() + }, + onEventEditClick = { + EventManualDialog( + activity, + it.profileId, + editingEvent = it, + onShowListener = onShowListener, + onDismissListener = onDismissListener + ).show() + } + ) + + app.db.eventDao().getAllByDate(profileId, date).observe(activity) { events -> + events.forEach { + it.filterNotes() + } + + adapter.setAllItems( + if (eventTypeId != null) + events.filter { it.type == eventTypeId } + else + events, + ) + + if (b.eventsView.adapter == null) { + b.eventsView.adapter = adapter + b.eventsView.apply { + isNestedScrollingEnabled = false + setHasFixedSize(true) + layoutManager = LinearLayoutManager(context) + addItemDecoration(SimpleDividerItemDecoration(context)) + } + } + adapter.notifyDataSetChanged() + + if (events != null && events.isNotEmpty()) { + b.eventsView.visibility = View.VISIBLE + b.eventsNoData.visibility = View.GONE + } else { + b.eventsView.visibility = View.GONE + b.eventsNoData.visibility = View.VISIBLE + } + } + + b.notesButton.isVisible = showNotes + b.notesButton.setupNotesButton( + activity = activity, + owner = date, + onShowListener = onShowListener, + onDismissListener = onDismissListener, + ) + b.legend.isVisible = showNotes + if (showNotes) + NoteManager.setLegendText(date, b.legend) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/event/AgendaEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/event/AgendaEvent.kt new file mode 100644 index 00000000..ebff08f9 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/event/AgendaEvent.kt @@ -0,0 +1,20 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-4-8. + */ + +package pl.szczodrzynski.edziennik.ui.agenda.event + +import pl.szczodrzynski.edziennik.data.db.full.EventFull +import pl.szczodrzynski.edziennik.ui.agenda.BaseEvent + +class AgendaEvent( + val event: EventFull, + showBadge: Boolean = !event.seen +) : BaseEvent( + id = event.id, + time = event.startTimeCalendar, + color = event.eventColor, + showBadge = showBadge +) { + override fun copy() = AgendaEvent(event, showBadge) +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/event/AgendaEventGroup.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/event/AgendaEventGroup.kt new file mode 100644 index 00000000..cccfb292 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/event/AgendaEventGroup.kt @@ -0,0 +1,25 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-4-10. + */ + +package pl.szczodrzynski.edziennik.ui.agenda.event + +import pl.szczodrzynski.edziennik.ui.agenda.BaseEvent +import pl.szczodrzynski.edziennik.utils.models.Date + +class AgendaEventGroup( + val profileId: Int, + val date: Date, + val typeId: Long, + val typeName: String, + val typeColor: Int, + val count: Int, + showBadge: Boolean +) : BaseEvent( + id = date.value.toLong(), + time = date.asCalendar, + color = typeColor, + showBadge = showBadge +) { + override fun copy() = AgendaEventGroup(profileId, date, typeId, typeName, typeColor, count, showBadge) +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/event/AgendaEventGroupRenderer.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/event/AgendaEventGroupRenderer.kt new file mode 100644 index 00000000..59d15cbe --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/event/AgendaEventGroupRenderer.kt @@ -0,0 +1,33 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-4-10. + */ + +package pl.szczodrzynski.edziennik.ui.agenda.event + +import android.view.View +import androidx.core.view.isVisible +import com.github.tibolte.agendacalendarview.render.EventRenderer +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.databinding.AgendaWrappedGroupBinding +import pl.szczodrzynski.edziennik.ext.resolveAttr +import pl.szczodrzynski.edziennik.ext.setTintColor +import pl.szczodrzynski.edziennik.utils.Colors + +class AgendaEventGroupRenderer : EventRenderer() { + + override fun render(view: View, event: AgendaEventGroup) { + val b = AgendaWrappedGroupBinding.bind(view).item + + b.card.foreground.setTintColor(event.color) + b.card.background.setTintColor(event.color) + b.name.text = event.typeName + b.name.setTextColor(Colors.legibleTextColor(event.color)) + b.count.text = event.count.toString() + b.count.background.setTintColor(android.R.attr.colorBackground.resolveAttr(view.context)) + + b.badge.isVisible = event.showItemBadge + } + + override fun getEventLayout(): Int = R.layout.agenda_wrapped_group +} + diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/event/AgendaEventRenderer.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/event/AgendaEventRenderer.kt new file mode 100644 index 00000000..31eb6730 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/event/AgendaEventRenderer.kt @@ -0,0 +1,81 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-4-8. + */ + +package pl.szczodrzynski.edziennik.ui.agenda.event + +import android.annotation.SuppressLint +import android.view.View +import android.widget.FrameLayout +import android.widget.TextView +import androidx.core.view.isVisible +import com.github.tibolte.agendacalendarview.render.EventRenderer +import com.mikepenz.iconics.view.IconicsTextView +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.databinding.AgendaWrappedEventBinding +import pl.szczodrzynski.edziennik.databinding.AgendaWrappedEventCompactBinding +import pl.szczodrzynski.edziennik.ext.join +import pl.szczodrzynski.edziennik.ext.resolveAttr +import pl.szczodrzynski.edziennik.ext.setTintColor +import pl.szczodrzynski.edziennik.utils.Colors +import pl.szczodrzynski.edziennik.utils.managers.EventManager + +class AgendaEventRenderer( + val manager: EventManager, + val isCompact: Boolean +) : EventRenderer() { + + @SuppressLint("SetTextI18n") + override fun render(view: View, aEvent: AgendaEvent) { + if (isCompact) { + val b = AgendaWrappedEventCompactBinding.bind(view).item + bindView(aEvent, b.card, b.title, null, b.badgeBackground, b.badge) + } else { + val b = AgendaWrappedEventBinding.bind(view).item + bindView(aEvent, b.card, b.title, b.subtitle, b.badgeBackground, b.badge) + } + } + + private fun bindView( + aEvent: AgendaEvent, + card: FrameLayout, + title: IconicsTextView, + subtitle: TextView?, + badgeBackground: View, + badge: View + ) { + val event = aEvent.event + + val textColor = Colors.legibleTextColor(event.eventColor) + + val timeText = if (event.time == null) + card.context.getString(R.string.agenda_event_all_day) + else + event.time!!.stringHM + + val eventSubtitle = listOfNotNull( + timeText, + event.subjectLongName, + event.teacherName, + event.teamName + ).join(", ") + + card.foreground.setTintColor(event.eventColor) + card.background.setTintColor(event.eventColor) + manager.setEventTopic(title, event, doneIconColor = textColor) + title.setTextColor(textColor) + subtitle?.text = eventSubtitle + subtitle?.setTextColor(textColor) + + badgeBackground.isVisible = aEvent.showItemBadge + badgeBackground.background.setTintColor( + android.R.attr.colorBackground.resolveAttr(card.context) + ) + badge.isVisible = aEvent.showItemBadge + } + + override fun getEventLayout() = if (isCompact) + R.layout.agenda_wrapped_event_compact + else + R.layout.agenda_wrapped_event +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/dialogs/lessonchange/LessonChangeAdapter.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/lessonchanges/LessonChangesAdapter.kt similarity index 91% rename from app/src/main/java/pl/szczodrzynski/edziennik/ui/dialogs/lessonchange/LessonChangeAdapter.kt rename to app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/lessonchanges/LessonChangesAdapter.kt index b15803ed..cf6b0cae 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/ui/dialogs/lessonchange/LessonChangeAdapter.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/lessonchanges/LessonChangesAdapter.kt @@ -2,7 +2,7 @@ * Copyright (c) Kuba Szczodrzyński 2019-12-19. */ -package pl.szczodrzynski.edziennik.ui.dialogs.lessonchange +package pl.szczodrzynski.edziennik.ui.agenda.lessonchanges import android.content.Context import android.graphics.PorterDuff @@ -11,16 +11,19 @@ import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.view.updateLayoutParams import androidx.recyclerview.widget.RecyclerView -import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.R import pl.szczodrzynski.edziennik.data.db.entity.Lesson import pl.szczodrzynski.edziennik.data.db.full.LessonFull import pl.szczodrzynski.edziennik.databinding.TimetableLessonBinding +import pl.szczodrzynski.edziennik.ext.* +import pl.szczodrzynski.edziennik.utils.managers.NoteManager import pl.szczodrzynski.navlib.getColorFromAttr -class LessonChangeAdapter( +class LessonChangesAdapter( val context: Context, - private val onItemClick: ((lesson: LessonFull) -> Unit)? = null -) : RecyclerView.Adapter() { + private val showNotes: Boolean = true, + private val onLessonClick: ((lesson: LessonFull) -> Unit)? = null +) : RecyclerView.Adapter() { var items = listOf() @@ -38,8 +41,10 @@ class LessonChangeAdapter( val lesson = items[position] val b = holder.b - b.root.onClick { - onItemClick?.invoke(lesson) + if (onLessonClick != null) { + b.root.onClick { + onLessonClick.invoke(lesson) + } } val startTime = lesson.displayStartTime ?: return @@ -83,7 +88,8 @@ class LessonChangeAdapter( b.lessonNumber = lesson.displayLessonNumber - b.subjectName.text = lesson.displaySubjectName?.let { + val lessonText = lesson.getNoteSubstituteText(showNotes) ?: lesson.displaySubjectName + b.subjectName.text = lessonText?.let { if (lesson.type == Lesson.TYPE_CANCELLED || lesson.type == Lesson.TYPE_SHIFTED_SOURCE) it.asStrikethroughSpannable().asColoredSpannable(colorSecondary) else @@ -92,6 +98,9 @@ class LessonChangeAdapter( b.detailsFirst.text = listOfNotEmpty(timeRange, classroomInfo).concat(bullet) b.detailsSecond.text = listOfNotEmpty(teacherInfo, teamInfo).concat(bullet) + if (showNotes) + NoteManager.prependIcon(lesson, b.subjectName) + //lb.subjectName.typeface = Typeface.create("sans-serif-light", Typeface.BOLD) when (lesson.type) { Lesson.TYPE_NORMAL -> { diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/lessonchanges/LessonChangesDialog.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/lessonchanges/LessonChangesDialog.kt new file mode 100644 index 00000000..50e972a6 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/lessonchanges/LessonChangesDialog.kt @@ -0,0 +1,53 @@ +package pl.szczodrzynski.edziennik.ui.agenda.lessonchanges + +import android.view.LayoutInflater +import androidx.appcompat.app.AppCompatActivity +import androidx.recyclerview.widget.LinearLayoutManager +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.databinding.DialogLessonChangeListBinding +import pl.szczodrzynski.edziennik.ui.dialogs.base.BindingDialog +import pl.szczodrzynski.edziennik.ui.timetable.LessonDetailsDialog +import pl.szczodrzynski.edziennik.utils.models.Date + +class LessonChangesDialog( + activity: AppCompatActivity, + private val profileId: Int, + private val defaultDate: Date, + onShowListener: ((tag: String) -> Unit)? = null, + onDismissListener: ((tag: String) -> Unit)? = null, +) : BindingDialog(activity, onShowListener, onDismissListener) { + + override val TAG = "LessonChangesDialog" + + override fun getTitle(): String = defaultDate.formattedString + override fun getTitleRes(): Int? = null + override fun inflate(layoutInflater: LayoutInflater) = + DialogLessonChangeListBinding.inflate(layoutInflater) + + override fun getPositiveButtonText() = R.string.close + + override suspend fun onShow() { + val lessonChanges = withContext(Dispatchers.Default) { + app.db.timetableDao().getChangesForDateNow(profileId, defaultDate) + } + + val adapter = LessonChangesAdapter( + activity, + onLessonClick = { + LessonDetailsDialog( + activity, + it, + onShowListener = onShowListener, + onDismissListener = onDismissListener + ).show() + } + ).apply { + items = lessonChanges + } + + b.lessonChangeView.adapter = adapter + b.lessonChangeView.layoutManager = LinearLayoutManager(activity) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/lessonchanges/LessonChangesEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/lessonchanges/LessonChangesEvent.kt new file mode 100644 index 00000000..c011af59 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/lessonchanges/LessonChangesEvent.kt @@ -0,0 +1,25 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-4-8. + */ + +package pl.szczodrzynski.edziennik.ui.agenda.lessonchanges + +import pl.szczodrzynski.edziennik.ui.agenda.BaseEvent +import pl.szczodrzynski.edziennik.utils.models.Date + +class LessonChangesEvent( + val profileId: Int, + val date: Date, + val count: Int, + showBadge: Boolean +) : BaseEvent( + id = date.value.toLong(), + time = date.asCalendar, + color = 0xff78909c.toInt(), + showBadge = false, + showItemBadge = showBadge +) { + override fun copy() = LessonChangesEvent(profileId, date, count, showItemBadge) + + override fun getShowBadge() = false +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/lessonchanges/LessonChangesEventRenderer.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/lessonchanges/LessonChangesEventRenderer.kt new file mode 100644 index 00000000..2ef4aecc --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/lessonchanges/LessonChangesEventRenderer.kt @@ -0,0 +1,55 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-4-8. + */ + +package pl.szczodrzynski.edziennik.ui.agenda.lessonchanges + +import android.view.View +import androidx.core.view.isVisible +import com.github.tibolte.agendacalendarview.render.EventRenderer +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.databinding.AgendaCounterItemBinding +import pl.szczodrzynski.edziennik.databinding.AgendaWrappedCounterBinding +import pl.szczodrzynski.edziennik.ext.resolveAttr +import pl.szczodrzynski.edziennik.ext.setTintColor +import pl.szczodrzynski.edziennik.utils.Colors + +class LessonChangesEventRenderer : EventRenderer() { + + override fun render(view: View, event: LessonChangesEvent) { + val b = AgendaWrappedCounterBinding.bind(view).item + val textColor = Colors.legibleTextColor(event.color) + + b.card.foreground.setTintColor(event.color) + b.card.background.setTintColor(event.color) + b.name.setText(R.string.agenda_lesson_changes) + b.name.setTextColor(textColor) + b.count.text = event.count.toString() + b.count.setTextColor(textColor) + + b.badgeBackground.isVisible = event.showItemBadge + b.badgeBackground.background.setTintColor( + android.R.attr.colorBackground.resolveAttr(view.context) + ) + b.badge.isVisible = event.showItemBadge + } + + fun render(b: AgendaCounterItemBinding, event: LessonChangesEvent) { + val textColor = Colors.legibleTextColor(event.color) + + b.card.foreground.setTintColor(event.color) + b.card.background.setTintColor(event.color) + b.name.setText(R.string.agenda_lesson_changes) + b.name.setTextColor(textColor) + b.count.text = event.count.toString() + b.count.setTextColor(textColor) + + b.badgeBackground.isVisible = event.showItemBadge + b.badgeBackground.background.setTintColor( + android.R.attr.colorBackground.resolveAttr(b.root.context) + ) + b.badge.isVisible = event.showItemBadge + } + + override fun getEventLayout(): Int = R.layout.agenda_wrapped_counter +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/dialogs/teacherabsence/TeacherAbsenceAdapter.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/teacherabsence/TeacherAbsenceAdapter.kt similarity index 97% rename from app/src/main/java/pl/szczodrzynski/edziennik/ui/dialogs/teacherabsence/TeacherAbsenceAdapter.kt rename to app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/teacherabsence/TeacherAbsenceAdapter.kt index d8c11307..89cbf3ee 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/ui/dialogs/teacherabsence/TeacherAbsenceAdapter.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/teacherabsence/TeacherAbsenceAdapter.kt @@ -1,4 +1,4 @@ -package pl.szczodrzynski.edziennik.ui.dialogs.teacherabsence +package pl.szczodrzynski.edziennik.ui.agenda.teacherabsence import android.content.Context import android.view.LayoutInflater @@ -29,7 +29,7 @@ class TeacherAbsenceAdapter( override fun onBindViewHolder(holder: ViewHolder, position: Int) { val teacherAbsence: TeacherAbsenceFull = teacherAbsenceList[position] - holder.teacherAbsenceTeacher.text = teacherAbsence.teacherFullName + holder.teacherAbsenceTeacher.text = teacherAbsence.teacherName val time = when (teacherAbsence.timeFrom != null && teacherAbsence.timeTo != null) { true -> when (teacherAbsence.dateFrom.compareTo(teacherAbsence.dateTo)) { diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/teacherabsence/TeacherAbsenceDialog.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/teacherabsence/TeacherAbsenceDialog.kt new file mode 100644 index 00000000..7a1071de --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/teacherabsence/TeacherAbsenceDialog.kt @@ -0,0 +1,42 @@ +package pl.szczodrzynski.edziennik.ui.agenda.teacherabsence + +import android.view.LayoutInflater +import android.view.View +import androidx.appcompat.app.AppCompatActivity +import androidx.lifecycle.LifecycleOwner +import androidx.recyclerview.widget.LinearLayoutManager +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.databinding.DialogTeacherAbsenceListBinding +import pl.szczodrzynski.edziennik.ui.dialogs.base.BindingDialog +import pl.szczodrzynski.edziennik.utils.models.Date + +class TeacherAbsenceDialog( + activity: AppCompatActivity, + private val profileId: Int, + private val date: Date, + onShowListener: ((tag: String) -> Unit)? = null, + onDismissListener: ((tag: String) -> Unit)? = null, +) : BindingDialog(activity, onShowListener, onDismissListener) { + + override val TAG = "TeacherAbsenceDialog" + + override fun getTitle(): String = date.formattedString + override fun getTitleRes(): Int? = null + override fun inflate(layoutInflater: LayoutInflater) = + DialogTeacherAbsenceListBinding.inflate(layoutInflater) + + override fun getPositiveButtonText() = R.string.close + + override suspend fun onShow() { + b.teacherAbsenceView.setHasFixedSize(true) + b.teacherAbsenceView.layoutManager = LinearLayoutManager(activity) + + app.db.teacherAbsenceDao().getAllByDate(profileId, date).observe( + activity as LifecycleOwner + ) { absenceList -> + val adapter = TeacherAbsenceAdapter(activity, date, absenceList) + b.teacherAbsenceView.adapter = adapter + b.teacherAbsenceView.visibility = View.VISIBLE + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/teacherabsence/TeacherAbsenceEvent.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/teacherabsence/TeacherAbsenceEvent.kt new file mode 100644 index 00000000..d9defda1 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/teacherabsence/TeacherAbsenceEvent.kt @@ -0,0 +1,21 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-4-8. + */ + +package pl.szczodrzynski.edziennik.ui.agenda.teacherabsence + +import pl.szczodrzynski.edziennik.ui.agenda.BaseEvent +import pl.szczodrzynski.edziennik.utils.models.Date + +class TeacherAbsenceEvent( + val profileId: Int, + val date: Date, + val count: Int +) : BaseEvent( + id = date.value.toLong(), + time = date.asCalendar, + color = 0xffff1744.toInt(), + showBadge = false +) { + override fun copy() = TeacherAbsenceEvent(profileId, date, count) +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/teacherabsence/TeacherAbsenceEventRenderer.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/teacherabsence/TeacherAbsenceEventRenderer.kt new file mode 100644 index 00000000..7d87acfa --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/agenda/teacherabsence/TeacherAbsenceEventRenderer.kt @@ -0,0 +1,48 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-4-8. + */ + +package pl.szczodrzynski.edziennik.ui.agenda.teacherabsence + +import android.view.View +import androidx.core.view.isVisible +import com.github.tibolte.agendacalendarview.render.EventRenderer +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.databinding.AgendaCounterItemBinding +import pl.szczodrzynski.edziennik.databinding.AgendaWrappedCounterBinding +import pl.szczodrzynski.edziennik.ext.setTintColor +import pl.szczodrzynski.edziennik.utils.Colors + +class TeacherAbsenceEventRenderer : EventRenderer() { + + override fun render(view: View, event: TeacherAbsenceEvent) { + val b = AgendaWrappedCounterBinding.bind(view).item + val textColor = Colors.legibleTextColor(event.color) + + b.card.foreground.setTintColor(event.color) + b.card.background.setTintColor(event.color) + b.name.setText(R.string.agenda_teacher_absence) + b.name.setTextColor(textColor) + b.count.text = event.count.toString() + b.count.setTextColor(textColor) + + b.badgeBackground.isVisible = false + b.badge.isVisible = false + } + + fun render(b: AgendaCounterItemBinding, event: TeacherAbsenceEvent) { + val textColor = Colors.legibleTextColor(event.color) + + b.card.foreground.setTintColor(event.color) + b.card.background.setTintColor(event.color) + b.name.setText(R.string.agenda_teacher_absence) + b.name.setTextColor(textColor) + b.count.text = event.count.toString() + b.count.setTextColor(textColor) + + b.badgeBackground.isVisible = false + b.badge.isVisible = false + } + + override fun getEventLayout(): Int = R.layout.agenda_wrapped_counter +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/modules/announcements/AnnouncementsAdapter.java b/app/src/main/java/pl/szczodrzynski/edziennik/ui/announcements/AnnouncementsAdapter.java similarity index 72% rename from app/src/main/java/pl/szczodrzynski/edziennik/ui/modules/announcements/AnnouncementsAdapter.java rename to app/src/main/java/pl/szczodrzynski/edziennik/ui/announcements/AnnouncementsAdapter.java index 7f9b600d..d50d6670 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/ui/modules/announcements/AnnouncementsAdapter.java +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/announcements/AnnouncementsAdapter.java @@ -1,4 +1,4 @@ -package pl.szczodrzynski.edziennik.ui.modules.announcements; +package pl.szczodrzynski.edziennik.ui.announcements; import android.content.Context; import android.graphics.Bitmap; @@ -10,6 +10,7 @@ import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import androidx.databinding.DataBindingUtil; import androidx.recyclerview.widget.RecyclerView; @@ -18,19 +19,20 @@ import java.util.List; import pl.szczodrzynski.edziennik.R; import pl.szczodrzynski.edziennik.data.db.full.AnnouncementFull; import pl.szczodrzynski.edziennik.databinding.RowAnnouncementsItemBinding; -import pl.szczodrzynski.edziennik.ui.modules.messages.MessagesUtils; +import pl.szczodrzynski.edziennik.ui.messages.MessagesUtils; public class AnnouncementsAdapter extends RecyclerView.Adapter { private Context context; public List announcementList; + @Nullable public OnAnnouncementClickListener onClick; public interface OnAnnouncementClickListener { void onClick(View v, AnnouncementFull announcement); } - public AnnouncementsAdapter(Context context, List announcementList, OnAnnouncementClickListener onClick) { + public AnnouncementsAdapter(Context context, List announcementList, @Nullable OnAnnouncementClickListener onClick) { //setHasStableIds(true); this.context = context; @@ -54,22 +56,26 @@ public class AnnouncementsAdapter extends RecyclerView.Adapter { - if (onClick != null) { - onClick.onClick(v, item); - } - })); - b.announcementsItemSender.setText(item.teacherFullName); - b.announcementsItemTitle.setText(item.subject); - b.announcementsItemText.setText(item.text); + if (onClick != null) { + b.announcementsItem.setOnClickListener(v -> onClick.onClick(v, item)); + } + else { + b.announcementsItem.setOnClickListener(null); + } + b.announcementsItemSender.setText(item.getTeacherName()); + b.announcementsItemTitle.setText(item.getSubject()); + b.announcementsItemText.setText(item.getText()); - if (item.endDate == null) { - b.announcementsItemDate.setText(item.startDate.getFormattedString()); - } else { - b.announcementsItemDate.setText(context.getString(R.string.date_relative_format, item.startDate.getFormattedStringShort(), item.endDate.getFormattedStringShort())); + if (item.getEndDate() == null && item.getStartDate() != null) { + b.announcementsItemDate.setText(item.getStartDate().getFormattedString()); + } else if (item.getStartDate() != null) { + b.announcementsItemDate.setText(context.getString(R.string.date_relative_format, item.getStartDate().getFormattedStringShort(), item.getEndDate().getFormattedStringShort())); + } + else { + b.announcementsItemDate.setText(""); } - if (!item.seen) { + if (!item.getSeen()) { b.announcementsItemTitle.setBackground(context.getResources().getDrawable(R.drawable.bg_rounded_8dp)); b.announcementsItemTitle.getBackground().setColorFilter(new PorterDuffColorFilter(0x692196f3, PorterDuff.Mode.MULTIPLY)); b.announcementsItemSender.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD)); @@ -80,7 +86,7 @@ public class AnnouncementsAdapter extends RecyclerView.Adapter { - if (announcement.text == null || (app.getProfile().getLoginStoreType() == LOGIN_TYPE_LIBRUS && !announcement.seen && app.getNetworkUtils().isOnline())) { + if (announcement.getText() == null || (app.getProfile().getLoginStoreType() == LOGIN_TYPE_LIBRUS && !announcement.getSeen())) { EdziennikTask.Companion.announcementGet(App.Companion.getProfileId(), announcement).enqueue(requireContext()); } else { showAnnouncementDetailsDialog(announcement); @@ -161,15 +165,15 @@ public class AnnouncementsFragment extends Fragment { } private void showAnnouncementDetailsDialog(AnnouncementFull announcement) { - MaterialDialog dialog = new MaterialDialog.Builder(activity) - .title(announcement.subject) - .customView(R.layout.dialog_announcement, true) - .positiveText(R.string.ok) + DialogAnnouncementBinding b = DialogAnnouncementBinding.inflate(LayoutInflater.from(activity), null, false); + new MaterialAlertDialogBuilder(activity) + .setTitle(announcement.getSubject()) + .setView(b.getRoot()) + .setPositiveButton(R.string.ok, null) .show(); - DialogAnnouncementBinding b = DialogAnnouncementBinding.bind(dialog.getCustomView()); - b.text.setText(announcement.teacherFullName+"\n\n"+ (announcement.startDate != null ? announcement.startDate.getFormattedString() : "-") + (announcement.endDate != null ? " do " + announcement.endDate.getFormattedString() : "")+"\n\n" +announcement.text); - if (!announcement.seen && app.getProfile().getLoginStoreType() != LOGIN_TYPE_LIBRUS) { - announcement.seen = true; + b.text.setText(announcement.getTeacherName() +"\n\n"+ (announcement.getStartDate() != null ? announcement.getStartDate().getFormattedString() : "-") + (announcement.getEndDate() != null ? " do " + announcement.getEndDate().getFormattedString() : "")+"\n\n" +announcement.getText()); + if (!announcement.getSeen() && app.getProfile().getLoginStoreType() != LOGIN_TYPE_LIBRUS) { + announcement.setSeen(true); AsyncTask.execute(() -> App.db.metadataDao().setSeen(App.Companion.getProfileId(), announcement, true)); if (recyclerView.getAdapter() != null) recyclerView.getAdapter().notifyDataSetChanged(); diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceAdapter.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceAdapter.kt new file mode 100644 index 00000000..00a1b361 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceAdapter.kt @@ -0,0 +1,194 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-29. + */ + +package pl.szczodrzynski.edziennik.ui.attendance + +import android.animation.ObjectAnimator +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.isInvisible +import androidx.core.view.isVisible +import androidx.recyclerview.widget.RecyclerView +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.db.full.AttendanceFull +import pl.szczodrzynski.edziennik.ext.startCoroutineTimer +import pl.szczodrzynski.edziennik.ui.attendance.models.* +import pl.szczodrzynski.edziennik.ui.attendance.viewholder.* +import pl.szczodrzynski.edziennik.ui.grades.models.ExpandableItemModel +import pl.szczodrzynski.edziennik.ui.grades.viewholder.BindableViewHolder +import kotlin.coroutines.CoroutineContext + +class AttendanceAdapter( + val activity: AppCompatActivity, + val type: Int, + val showNotes: Boolean = true, + var onAttendanceClick: ((item: AttendanceFull) -> Unit)? = null +) : RecyclerView.Adapter(), CoroutineScope { + companion object { + private const val TAG = "AttendanceAdapter" + private const val ITEM_TYPE_ATTENDANCE = 0 + private const val ITEM_TYPE_DAY_RANGE = 1 + private const val ITEM_TYPE_MONTH = 2 + private const val ITEM_TYPE_SUBJECT = 3 + private const val ITEM_TYPE_TYPE = 4 + private const val ITEM_TYPE_EMPTY = 5 + const val STATE_CLOSED = 0 + const val STATE_OPENED = 1 + } + + private val app = activity.applicationContext as App + // optional: place the manager here + + private val job = Job() + override val coroutineContext: CoroutineContext + get() = job + Dispatchers.Main + + var items = mutableListOf() + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + val inflater = LayoutInflater.from(parent.context) + return when (viewType) { + ITEM_TYPE_ATTENDANCE -> AttendanceViewHolder(inflater, parent) + ITEM_TYPE_DAY_RANGE -> DayRangeViewHolder(inflater, parent) + ITEM_TYPE_MONTH -> MonthViewHolder(inflater, parent) + ITEM_TYPE_SUBJECT -> SubjectViewHolder(inflater, parent) + ITEM_TYPE_TYPE -> TypeViewHolder(inflater, parent) + ITEM_TYPE_EMPTY -> EmptyViewHolder(inflater, parent) + else -> throw IllegalArgumentException("Incorrect viewType") + } + } + + override fun getItemViewType(position: Int): Int { + return when (items[position]) { + is AttendanceFull -> ITEM_TYPE_ATTENDANCE + is AttendanceDayRange -> ITEM_TYPE_DAY_RANGE + is AttendanceMonth -> ITEM_TYPE_MONTH + is AttendanceSubject -> ITEM_TYPE_SUBJECT + is AttendanceTypeGroup -> ITEM_TYPE_TYPE + is AttendanceEmpty -> ITEM_TYPE_EMPTY + else -> throw IllegalArgumentException("Incorrect viewType") + } + } + + private val onClickListener = View.OnClickListener { view -> + val model = view.getTag(R.string.tag_key_model) + if (model is AttendanceFull) { + onAttendanceClick?.invoke(model) + return@OnClickListener + } + if (model !is ExpandableItemModel<*>) + return@OnClickListener + expandModel(model, view) + } + + fun expandModel(model: ExpandableItemModel<*>?, view: View?, notifyAdapter: Boolean = true) { + model ?: return + val position = items.indexOf(model) + if (position == -1) + return + + view?.findViewById(R.id.dropdownIcon)?.let { dropdownIcon -> + ObjectAnimator.ofFloat( + dropdownIcon, + View.ROTATION, + if (model.state == STATE_CLOSED) 0f else 180f, + if (model.state == STATE_CLOSED) 180f else 0f + ).setDuration(200).start(); + } + + if (model is AttendanceDayRange || model is AttendanceMonth || model is AttendanceTypeGroup) { + // hide the preview, show summary + val preview = view?.findViewById(R.id.previewContainer) + val summary = view?.findViewById(R.id.summaryContainer) + val percentage = view?.findViewById(R.id.percentage) + preview?.isInvisible = model.state == STATE_CLOSED + summary?.isInvisible = model.state != STATE_CLOSED + percentage?.isVisible = model.state != STATE_CLOSED + } + + if (model.state == STATE_CLOSED) { + + val subItems = when { + model.items.isEmpty() -> listOf(AttendanceEmpty()) + else -> model.items + } + + model.state = STATE_OPENED + items.addAll(position + 1, subItems.filterNotNull()) + if (notifyAdapter) notifyItemRangeInserted(position + 1, subItems.size) + } + else { + val start = position + 1 + var end: Int = items.size + for (i in start until items.size) { + val model1 = items[i] + val level = (model1 as? ExpandableItemModel<*>)?.level ?: 3 + if (level <= model.level) { + end = i + break + } else { + if (model1 is ExpandableItemModel<*> && model1.state == STATE_OPENED) { + model1.state = STATE_CLOSED + } + } + } + + if (end != -1) { + items.subList(start, end).clear() + if (notifyAdapter) notifyItemRangeRemoved(start, end - start) + } + + model.state = STATE_CLOSED + } + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + val item = items[position] + if (holder !is BindableViewHolder<*, *>) + return + + val viewType = when (holder) { + is AttendanceViewHolder -> ITEM_TYPE_ATTENDANCE + is DayRangeViewHolder -> ITEM_TYPE_DAY_RANGE + is MonthViewHolder -> ITEM_TYPE_MONTH + is SubjectViewHolder -> ITEM_TYPE_SUBJECT + is TypeViewHolder -> ITEM_TYPE_TYPE + is EmptyViewHolder -> ITEM_TYPE_EMPTY + else -> throw IllegalArgumentException("Incorrect viewType") + } + holder.itemView.setTag(R.string.tag_key_view_type, viewType) + holder.itemView.setTag(R.string.tag_key_position, position) + holder.itemView.setTag(R.string.tag_key_model, item) + + when { + holder is AttendanceViewHolder && item is AttendanceFull -> holder.onBind(activity, app, item, position, this) + holder is DayRangeViewHolder && item is AttendanceDayRange -> holder.onBind(activity, app, item, position, this) + holder is MonthViewHolder && item is AttendanceMonth -> holder.onBind(activity, app, item, position, this) + holder is SubjectViewHolder && item is AttendanceSubject -> holder.onBind(activity, app, item, position, this) + holder is TypeViewHolder && item is AttendanceTypeGroup -> holder.onBind(activity, app, item, position, this) + holder is EmptyViewHolder && item is AttendanceEmpty -> holder.onBind(activity, app, item, position, this) + } + + if (item !is AttendanceFull || onAttendanceClick != null) + holder.itemView.setOnClickListener(onClickListener) + else + holder.itemView.setOnClickListener(null) + } + + fun notifyItemChanged(model: Any) { + startCoroutineTimer(1000L, 0L) { + val index = items.indexOf(model) + if (index != -1) + notifyItemChanged(index) + } + } + + override fun getItemCount() = items.size +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceBar.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceBar.kt new file mode 100644 index 00000000..f8dee4ce --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceBar.kt @@ -0,0 +1,106 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-5-1. + */ + +package pl.szczodrzynski.edziennik.ui.attendance + +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.* +import android.text.TextPaint +import android.util.AttributeSet +import android.view.View +import pl.szczodrzynski.edziennik.ext.dp +import pl.szczodrzynski.edziennik.utils.Colors +import kotlin.math.roundToInt + +/* https://github.com/JakubekWeg/Mobishit/blob/master/app/src/main/java/jakubweg/mobishit/view/AttendanceBarView.kt */ +class AttendanceBar : View { + + constructor(context: Context) : super(context) + + constructor(context: Context, attrs: AttributeSet) : super(context, attrs) + + constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) + + private var attendancesList = listOf() + private val mainPaint = Paint(Paint.ANTI_ALIAS_FLAG) + private val textPaint = TextPaint(Paint.ANTI_ALIAS_FLAG).also { + it.textAlign = Paint.Align.CENTER + } + private var mPath = Path() + private var mCornerRadius: Float = 0.toFloat() + + init { + mCornerRadius = 4.dp.toFloat() + + if (isInEditMode) + setAttendanceData(listOf( + 0xff43a047.toInt() to 23, + 0xff009688.toInt() to 187, + 0xff3f51b5.toInt() to 46, + 0xff3f51b5.toInt() to 5, + 0xffffc107.toInt() to 5, + 0xff9e9e9e.toInt() to 26, + 0xff76ff03.toInt() to 34, + 0xffff3d00.toInt() to 8 + )) + } + + // color, count + private class AttendanceItem(var color: Int, var count: Int) + + fun setAttendanceData(list: List>) { + attendancesList = list.map { AttendanceItem(it.first, it.second) } + setWillNotDraw(false) + invalidate() + } + + override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { + super.onSizeChanged(w, h, oldw, oldh) + val r = RectF(0f, 0f, w.toFloat(), h.toFloat()) + mPath = Path().apply { + addRoundRect(r, mCornerRadius, mCornerRadius, Path.Direction.CW) + close() + } + } + + @SuppressLint("DrawAllocation", "CanvasSize") + override fun onDraw(canvas: Canvas?) { + canvas ?: return + + val sum = attendancesList.sumOf { it.count } + if (sum == 0) { + return + } + + canvas.clipPath(mPath) + + val top = paddingTop.toFloat() + val bottom = (height - paddingBottom).toFloat() + var left = paddingLeft.toFloat() + val unitWidth = (width - paddingRight - paddingLeft).toFloat() / sum.toFloat() + + textPaint.color = Color.BLACK + textPaint.textSize = 14.dp.toFloat() + + for (e in attendancesList) { + if (e.count == 0) + continue + + val width = unitWidth * e.count + mainPaint.color = e.color + canvas.drawRect(left, top, left + width, bottom, mainPaint) + + val percentage = (100f * e.count / sum).roundToInt().toString() + "%" + val textBounds = Rect() + textPaint.getTextBounds(percentage, 0, percentage.length, textBounds) + if (width > textBounds.width() + 8.dp && height > textBounds.height() + 2.dp) { + textPaint.color = Colors.legibleTextColor(e.color) + canvas.drawText(percentage, left + width / 2, bottom - height / 2 + textBounds.height()/2, textPaint) + } + + left += width + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceDetailsDialog.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceDetailsDialog.kt new file mode 100644 index 00000000..b0c67241 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceDetailsDialog.kt @@ -0,0 +1,67 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-5-9. + */ + +package pl.szczodrzynski.edziennik.ui.attendance + +import android.view.LayoutInflater +import androidx.appcompat.app.AppCompatActivity +import androidx.core.graphics.ColorUtils +import androidx.core.view.isVisible +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.db.full.AttendanceFull +import pl.szczodrzynski.edziennik.databinding.AttendanceDetailsDialogBinding +import pl.szczodrzynski.edziennik.ext.setTintColor +import pl.szczodrzynski.edziennik.ui.dialogs.base.BindingDialog +import pl.szczodrzynski.edziennik.ui.notes.setupNotesButton +import pl.szczodrzynski.edziennik.utils.BetterLink +import pl.szczodrzynski.edziennik.utils.managers.NoteManager + +class AttendanceDetailsDialog( + activity: AppCompatActivity, + private val attendance: AttendanceFull, + private val showNotes: Boolean = true, + onShowListener: ((tag: String) -> Unit)? = null, + onDismissListener: ((tag: String) -> Unit)? = null, +) : BindingDialog(activity, onShowListener, onDismissListener) { + + override val TAG = "AttendanceDetailsDialog" + + override fun getTitleRes(): Int? = null + override fun inflate(layoutInflater: LayoutInflater) = + AttendanceDetailsDialogBinding.inflate(layoutInflater) + + override fun getPositiveButtonText() = R.string.close + + override suspend fun onShow() { + val manager = app.attendanceManager + + val attendanceColor = manager.getAttendanceColor(attendance) + b.attendance = attendance + b.devMode = App.devMode + b.attendanceName.setTextColor(if (ColorUtils.calculateLuminance(attendanceColor) > 0.3) 0xaa000000.toInt() else 0xccffffff.toInt()) + b.attendanceName.background.setTintColor(attendanceColor) + + b.attendanceIsCounted.setText(if (attendance.isCounted) R.string.yes else R.string.no) + + attendance.teacherName?.let { name -> + BetterLink.attach( + b.teacherName, + teachers = mapOf(attendance.teacherId to name), + onActionSelected = dialog::dismiss + ) + } + + b.notesButton.isVisible = showNotes + b.notesButton.setupNotesButton( + activity = activity, + owner = attendance, + onShowListener = onShowListener, + onDismissListener = onDismissListener, + ) + b.legend.isVisible = showNotes + if (showNotes) + NoteManager.setLegendText(attendance, b.legend) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceFragment.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceFragment.kt new file mode 100644 index 00000000..e5687a3c --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceFragment.kt @@ -0,0 +1,121 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-30. + */ + +package pl.szczodrzynski.edziennik.ui.attendance + +import android.os.AsyncTask +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.fragment.app.Fragment +import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.MainActivity +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.db.entity.Metadata +import pl.szczodrzynski.edziennik.databinding.AttendanceFragmentBinding +import pl.szczodrzynski.edziennik.ext.Bundle +import pl.szczodrzynski.edziennik.ext.addOnPageSelectedListener +import pl.szczodrzynski.edziennik.ui.base.lazypager.FragmentLazyPagerAdapter +import pl.szczodrzynski.edziennik.ui.dialogs.settings.AttendanceConfigDialog +import pl.szczodrzynski.navlib.bottomsheet.items.BottomSheetPrimaryItem +import pl.szczodrzynski.navlib.bottomsheet.items.BottomSheetSeparatorItem +import kotlin.coroutines.CoroutineContext + +class AttendanceFragment : Fragment(), CoroutineScope { + companion object { + private const val TAG = "AttendanceFragment" + const val VIEW_SUMMARY = 0 + const val VIEW_DAYS = 1 + const val VIEW_MONTHS = 2 + const val VIEW_TYPES = 3 + const val VIEW_LIST = 4 + var pageSelection = 1 + } + + private lateinit var app: App + private lateinit var activity: MainActivity + private lateinit var b: AttendanceFragmentBinding + + private val job: Job = Job() + override val coroutineContext: CoroutineContext + get() = job + Dispatchers.Main + + // local/private variables go here + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + activity = (getActivity() as MainActivity?) ?: return null + context ?: return null + app = activity.application as App + b = AttendanceFragmentBinding.inflate(inflater) + b.refreshLayout.setParent(activity.swipeRefreshLayout) + return b.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + if (!isAdded) return + + activity.bottomSheet.prependItems( + BottomSheetPrimaryItem(true) + .withTitle(R.string.menu_attendance_config) + .withIcon(CommunityMaterial.Icon.cmd_cog_outline) + .withOnClickListener(View.OnClickListener { + activity.bottomSheet.close() + AttendanceConfigDialog(activity, true, null, null).show() + }), + BottomSheetSeparatorItem(true), + BottomSheetPrimaryItem(true) + .withTitle(R.string.menu_mark_as_read) + .withIcon(CommunityMaterial.Icon.cmd_eye_check_outline) + .withOnClickListener(View.OnClickListener { + activity.bottomSheet.close() + AsyncTask.execute { App.db.metadataDao().setAllSeen(App.profileId, Metadata.TYPE_ATTENDANCE, true) } + Toast.makeText(activity, R.string.main_menu_mark_as_read_success, Toast.LENGTH_SHORT).show() + }) + ) + activity.gainAttention() + + if (pageSelection == 1) + pageSelection = app.config.forProfile().attendance.attendancePageSelection + + val pagerAdapter = FragmentLazyPagerAdapter( + parentFragmentManager, + b.refreshLayout, + listOf( + AttendanceSummaryFragment() to getString(R.string.attendance_tab_summary), + + AttendanceListFragment().apply { + arguments = Bundle("viewType" to VIEW_DAYS) + } to getString(R.string.attendance_tab_days), + + AttendanceListFragment().apply { + arguments = Bundle("viewType" to VIEW_MONTHS) + } to getString(R.string.attendance_tab_months), + + AttendanceListFragment().apply { + arguments = Bundle("viewType" to VIEW_TYPES) + } to getString(R.string.attendance_tab_types), + + AttendanceListFragment().apply { + arguments = Bundle("viewType" to VIEW_LIST) + } to getString(R.string.attendance_tab_list) + ) + ) + b.viewPager.apply { + offscreenPageLimit = 1 + adapter = pagerAdapter + currentItem = pageSelection + addOnPageSelectedListener { + pageSelection = it + app.config.forProfile().attendance.attendancePageSelection = it + } + b.tabLayout.setupWithViewPager(this) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceListFragment.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceListFragment.kt new file mode 100644 index 00000000..acc19715 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceListFragment.kt @@ -0,0 +1,235 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-30. + */ + +package pl.szczodrzynski.edziennik.ui.attendance + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.core.view.isVisible +import androidx.lifecycle.Observer +import androidx.recyclerview.widget.LinearLayoutManager +import kotlinx.coroutines.* +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.MainActivity +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.data.db.full.AttendanceFull +import pl.szczodrzynski.edziennik.databinding.AttendanceListFragmentBinding +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty +import pl.szczodrzynski.edziennik.ext.startCoroutineTimer +import pl.szczodrzynski.edziennik.ui.attendance.models.AttendanceDayRange +import pl.szczodrzynski.edziennik.ui.attendance.models.AttendanceMonth +import pl.szczodrzynski.edziennik.ui.attendance.models.AttendanceTypeGroup +import pl.szczodrzynski.edziennik.ui.base.lazypager.LazyFragment +import pl.szczodrzynski.edziennik.ui.grades.models.GradesSubject +import pl.szczodrzynski.edziennik.utils.models.Date +import kotlin.coroutines.CoroutineContext + +class AttendanceListFragment : LazyFragment(), CoroutineScope { + companion object { + private const val TAG = "AttendanceListFragment" + } + + private lateinit var app: App + private lateinit var activity: MainActivity + private lateinit var b: AttendanceListFragmentBinding + + private val job: Job = Job() + override val coroutineContext: CoroutineContext + get() = job + Dispatchers.Main + + // local/private variables go here + private val manager + get() = app.attendanceManager + private var viewType = AttendanceFragment.VIEW_DAYS + private var expandSubjectId = 0L + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + activity = (getActivity() as MainActivity?) ?: return null + context ?: return null + app = activity.application as App + b = AttendanceListFragmentBinding.inflate(inflater) + return b.root + } + + override fun onPageCreated(): Boolean { startCoroutineTimer(100L) { + if (!isAdded) return@startCoroutineTimer + + viewType = arguments?.getInt("viewType") ?: AttendanceFragment.VIEW_DAYS + expandSubjectId = arguments?.getLong("gradesSubjectId") ?: 0L + + val adapter = AttendanceAdapter(activity, viewType) + var firstRun = true + + app.db.attendanceDao().getAll(App.profileId).observe(this@AttendanceListFragment, Observer { items -> this@AttendanceListFragment.launch { + if (!isAdded) return@launch + + items.forEach { + it.filterNotes() + } + + // load & configure the adapter + adapter.items = withContext(Dispatchers.Default) { processAttendance(items) } + if (adapter.items.isNotNullNorEmpty() && b.list.adapter == null) { + b.list.adapter = adapter + b.list.apply { + setHasFixedSize(true) + layoutManager = LinearLayoutManager(context) + addOnScrollListener(onScrollListener) + } + } + adapter.notifyDataSetChanged() + setSwipeToRefresh(adapter.items.isNullOrEmpty()) + + if (firstRun) { + expandSubject(adapter) + firstRun = false + } + + // show/hide relevant views + b.progressBar.isVisible = false + if (adapter.items.isNullOrEmpty()) { + b.list.isVisible = false + b.noData.isVisible = true + } else { + b.list.isVisible = true + b.noData.isVisible = false + } + }}) + + adapter.onAttendanceClick = { + AttendanceDetailsDialog(activity, it).show() + } + }; return true} + + private fun expandSubject(adapter: AttendanceAdapter) { + var expandSubjectModel: GradesSubject? = null + if (expandSubjectId != 0L) { + expandSubjectModel = adapter.items.firstOrNull { it is GradesSubject && it.subjectId == expandSubjectId } as? GradesSubject + adapter.expandModel( + model = expandSubjectModel, + view = null, + notifyAdapter = false + ) + } + + startCoroutineTimer(500L) { + if (expandSubjectModel != null) { + b.list.smoothScrollToPosition( + adapter.items.indexOf(expandSubjectModel) + expandSubjectModel.semesters.size + (expandSubjectModel.semesters.firstOrNull()?.grades?.size ?: 0) + ) + } + } + } + + @Suppress("SuspendFunctionOnCoroutineScope") + private fun processAttendance(attendance: List): MutableList { + if (attendance.isEmpty()) + return mutableListOf() + + val groupConsecutiveDays = app.config.forProfile().attendance.groupConsecutiveDays + val showPresenceInMonth = app.config.forProfile().attendance.showPresenceInMonth + + if (viewType == AttendanceFragment.VIEW_DAYS) { + val items = attendance + .filter { it.baseType != Attendance.TYPE_PRESENT } + .groupBy { it.date } + .map { AttendanceDayRange( + rangeStart = it.key, + rangeEnd = null, + items = it.value.toMutableList() + ) } + .toMutableList() + + if (groupConsecutiveDays) { + items.sortByDescending { it.rangeStart } + val iterator = items.listIterator() + + if (!iterator.hasNext()) + return items.toMutableList() + var element = iterator.next() + while (iterator.hasNext()) { + var nextElement = iterator.next() + while (Date.diffDays(element.rangeStart, nextElement.rangeStart) <= 1 && iterator.hasNext()) { + if (element.rangeEnd == null) + element.rangeEnd = element.rangeStart + + element.items.addAll(nextElement.items) + element.rangeStart = nextElement.rangeStart + iterator.remove() + nextElement = iterator.next() + } + element = nextElement + } + } + + return items.toMutableList() + } + else if (viewType == AttendanceFragment.VIEW_MONTHS) { + val items = attendance + .groupBy { it.date.year to it.date.month } + .map { AttendanceMonth( + year = it.key.first, + month = it.key.second, + items = it.value.toMutableList() + ) } + + items.forEach { month -> + month.typeCountMap = month.items + .groupBy { it.typeObject } + .map { it.key to it.value.size } + .sortedBy { it.first } + .toMap() + + val totalCount = month.typeCountMap.entries.sumOf { + if (!it.key.isCounted || it.key.baseType == Attendance.TYPE_UNKNOWN) + 0 + else it.value + } + val presenceCount = month.typeCountMap.entries.sumOf { + when (it.key.baseType) { + Attendance.TYPE_PRESENT, + Attendance.TYPE_PRESENT_CUSTOM, + Attendance.TYPE_BELATED, + Attendance.TYPE_BELATED_EXCUSED, + Attendance.TYPE_RELEASED -> if (it.key.isCounted) it.value else 0 + else -> 0 + } + } + + month.percentage = if (totalCount == 0) + 0f + else + presenceCount.toFloat() / totalCount.toFloat() * 100f + + if (!showPresenceInMonth) + month.items.removeAll { it.baseType == Attendance.TYPE_PRESENT } + } + + return items.toMutableList() + } + else if (viewType == AttendanceFragment.VIEW_TYPES) { + val items = attendance + .groupBy { it.typeObject } + .map { AttendanceTypeGroup( + type = it.key, + items = it.value.toMutableList() + ) } + .sortedBy { it.items.size } + + items.forEach { type -> + type.percentage = if (attendance.isEmpty()) + 0f + else + type.items.size.toFloat() / attendance.size.toFloat() * 100f + + type.semesterCount = type.items.count { it.semester == app.profile.currentSemester } + } + + return items.toMutableList() + } + return attendance.filter { it.baseType != Attendance.TYPE_PRESENT }.toMutableList() + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceSummaryFragment.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceSummaryFragment.kt new file mode 100644 index 00000000..828e5a95 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceSummaryFragment.kt @@ -0,0 +1,315 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-5-4. + */ + +package pl.szczodrzynski.edziennik.ui.attendance + +import android.graphics.Color +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.view.animation.AccelerateDecelerateInterpolator +import android.view.animation.Animation +import android.view.animation.Transformation +import android.widget.LinearLayout +import android.widget.TextView +import androidx.core.graphics.ColorUtils +import androidx.core.view.isInvisible +import androidx.core.view.isVisible +import androidx.lifecycle.Observer +import androidx.recyclerview.widget.LinearLayoutManager +import kotlinx.coroutines.* +import pl.szczodrzynski.edziennik.* +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.data.db.full.AttendanceFull +import pl.szczodrzynski.edziennik.databinding.AttendanceSummaryFragmentBinding +import pl.szczodrzynski.edziennik.ext.dp +import pl.szczodrzynski.edziennik.ext.isNotNullNorEmpty +import pl.szczodrzynski.edziennik.ext.setText +import pl.szczodrzynski.edziennik.ext.startCoroutineTimer +import pl.szczodrzynski.edziennik.ui.attendance.AttendanceFragment.Companion.VIEW_SUMMARY +import pl.szczodrzynski.edziennik.ui.attendance.models.AttendanceSubject +import pl.szczodrzynski.edziennik.ui.base.lazypager.LazyFragment +import pl.szczodrzynski.edziennik.ui.grades.models.GradesSubject +import pl.szczodrzynski.edziennik.utils.models.Date +import java.text.DecimalFormat +import kotlin.coroutines.CoroutineContext + +class AttendanceSummaryFragment : LazyFragment(), CoroutineScope { + companion object { + private const val TAG = "AttendanceSummaryFragment" + private var periodSelection = 0 + } + + private lateinit var app: App + private lateinit var activity: MainActivity + private lateinit var b: AttendanceSummaryFragmentBinding + + private val job: Job = Job() + override val coroutineContext: CoroutineContext + get() = job + Dispatchers.Main + + // local/private variables go here + private val manager + get() = app.attendanceManager + private var expandSubjectId = 0L + private var attendance = listOf() + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + activity = (getActivity() as MainActivity?) ?: return null + context ?: return null + app = activity.application as App + b = AttendanceSummaryFragmentBinding.inflate(inflater) + return b.root + } + + override fun onPageCreated(): Boolean { startCoroutineTimer(100L) { + if (!isAdded) return@startCoroutineTimer + + expandSubjectId = arguments?.getLong("gradesSubjectId") ?: 0L + + val adapter = AttendanceAdapter(activity, VIEW_SUMMARY) + var firstRun = true + + app.db.attendanceDao().getAll(App.profileId).observe(this@AttendanceSummaryFragment, Observer { items -> this@AttendanceSummaryFragment.launch { + if (!isAdded) return@launch + + items.forEach { + it.filterNotes() + } + + // load & configure the adapter + attendance = items + adapter.items = withContext(Dispatchers.Default) { processAttendance() } + if (adapter.items.isNotNullNorEmpty() && b.list.adapter == null) { + b.list.adapter = adapter + b.list.apply { + setHasFixedSize(false) + layoutManager = LinearLayoutManager(context) + isNestedScrollingEnabled = false + } + } + adapter.notifyDataSetChanged() + setSwipeToRefresh(adapter.items.isNullOrEmpty()) + + if (firstRun) { + expandSubject(adapter) + firstRun = false + } + + // show/hide relevant views + b.progressBar.isVisible = false + if (adapter.items.isNullOrEmpty()) { + b.statsLayout.isVisible = false + b.list.isVisible = false + b.noData.isVisible = true + } else { + b.statsLayout.isVisible = true + b.list.isVisible = true + b.noData.isVisible = false + } + }}) + + adapter.onAttendanceClick = { + AttendanceDetailsDialog(activity, it).show() + } + + b.toggleGroup.check(when (periodSelection) { + 0 -> R.id.allYear + 1 -> R.id.semester1 + 2 -> R.id.semester2 + else -> R.id.allYear + }) + b.toggleGroup.addOnButtonCheckedListener { _, checkedId, isChecked -> + if (!isChecked) + return@addOnButtonCheckedListener + periodSelection = when (checkedId) { + R.id.allYear -> 0 + R.id.semester1 -> 1 + R.id.semester2 -> 2 + else -> 0 + } + this@AttendanceSummaryFragment.launch { + adapter.items = withContext(Dispatchers.Default) { processAttendance() } + if (adapter.items.isNullOrEmpty()) { + b.statsLayout.isVisible = false + b.list.isVisible = false + b.noData.isVisible = true + } else { + b.statsLayout.isVisible = true + b.list.isVisible = true + b.noData.isVisible = false + } + adapter.notifyDataSetChanged() + } + } + }; return true} + + private fun expandSubject(adapter: AttendanceAdapter) { + var expandSubjectModel: GradesSubject? = null + if (expandSubjectId != 0L) { + expandSubjectModel = adapter.items.firstOrNull { it is GradesSubject && it.subjectId == expandSubjectId } as? GradesSubject + adapter.expandModel( + model = expandSubjectModel, + view = null, + notifyAdapter = false + ) + } + + startCoroutineTimer(500L) { + if (expandSubjectModel != null) { + b.list.smoothScrollToPosition( + adapter.items.indexOf(expandSubjectModel) + expandSubjectModel.semesters.size + (expandSubjectModel.semesters.firstOrNull()?.grades?.size ?: 0) + ) + } + } + } + + @Suppress("SuspendFunctionOnCoroutineScope") + private fun processAttendance(): MutableList { + val attendance = when (periodSelection) { + 0 -> attendance + 1 -> attendance.filter { it.semester == 1 } + 2 -> attendance.filter { it.semester == 2 } + else -> attendance + } + + if (attendance.isEmpty()) + return mutableListOf() + + val items = attendance + .groupBy { it.subjectId } + .map { AttendanceSubject( + subjectId = it.key, + subjectName = it.value.firstOrNull()?.subjectLongName ?: "", + items = it.value.toMutableList() + ) } + .sortedBy { it.subjectName.lowercase() } + + var totalCountSum = 0 + var presenceCountSum = 0 + + items.forEach { subject -> + subject.typeCountMap = subject.items + .groupBy { it.typeObject } + .map { it.key to it.value.size } + .sortedBy { it.first } + .toMap() + + val totalCount = subject.typeCountMap.entries.sumOf { + if (!it.key.isCounted || it.key.baseType == Attendance.TYPE_UNKNOWN) + 0 + else it.value + } + val presenceCount = subject.typeCountMap.entries.sumOf { + when (it.key.baseType) { + Attendance.TYPE_PRESENT, + Attendance.TYPE_PRESENT_CUSTOM, + Attendance.TYPE_BELATED, + Attendance.TYPE_BELATED_EXCUSED, + Attendance.TYPE_RELEASED -> if (it.key.isCounted) it.value else 0 + else -> 0 + } + } + totalCountSum += totalCount + presenceCountSum += presenceCount + + subject.percentage = if (totalCount == 0) + 0f + else + presenceCount.toFloat() / totalCount.toFloat() * 100f + + if (!false /* showPresenceInSubject */) + subject.items.removeAll { it.baseType == Attendance.TYPE_PRESENT } + } + + val typeCountMap = attendance + .groupBy { it.typeObject } + .map { it.key to it.value.size } + .sortedBy { it.first } + .toMap() + + val percentage = if (totalCountSum == 0) + 0f + else + presenceCountSum.toFloat() / totalCountSum.toFloat() * 100f + + launch { + b.attendanceBar.setAttendanceData(typeCountMap.map { manager.getAttendanceColor(it.key) to it.value }) + b.attendanceBar.isInvisible = typeCountMap.isEmpty() + + b.previewContainer.removeAllViews() + //val sum = typeCountMap.entries.sumBy { it.value }.toFloat() + typeCountMap.forEach { (type, count) -> + val layout = LinearLayout(activity) + val attendanceObject = Attendance( + profileId = 0, + id = 0, + baseType = type.baseType, + typeName = "", + typeShort = type.typeShort, + typeSymbol = type.typeSymbol, + typeColor = type.typeColor, + date = Date(0, 0, 0), + startTime = null, + semester = 0, + teacherId = 0, + subjectId = 0, + addedDate = 0 + ) + layout.addView(AttendanceView(activity, attendanceObject, manager)) + layout.addView(TextView(activity).also { + //it.setText(R.string.attendance_percentage_format, count/sum*100f) + it.text = count.toString() + it.setPadding(0, 0, 5.dp, 0) + }) + layout.setPadding(0, 8.dp, 0, 8.dp) + b.previewContainer.addView(layout) + } + + if (percentage == 0f) { + b.percentage.isInvisible = true + b.percentageCircle.isInvisible = true + } + else { + b.percentage.isVisible = true + b.percentageCircle.isVisible = true + b.percentage.setText(R.string.attendance_period_summary_format, percentage) + + val df = DecimalFormat("0.##") + b.percentageCircle.setProgressTextAdapter { value -> + df.format(value) + "%" + } + b.percentageCircle.maxProgress = 100.0 + animatePercentageIndicator(percentage.toDouble()) + } + } + + return items.toMutableList() + } + + private fun animatePercentageIndicator(targetProgress: Double) { + val startingProgress = b.percentageCircle.progress + val progressChange = targetProgress - startingProgress + + val a: Animation = object : Animation() { + override fun applyTransformation(interpolatedTime: Float, t: Transformation) { + val progress = startingProgress + (progressChange * interpolatedTime) + //if (interpolatedTime == 1f) + // progress = startingProgress + progressChange + + val color = ColorUtils.blendARGB(Color.RED, Color.GREEN, progress.toFloat() / 100.0f) + b.percentageCircle.progressColor = color + b.percentageCircle.setProgress(progress, 100.0) + } + + override fun willChangeBounds(): Boolean { + return false + } + } + a.duration = 1300 + a.interpolator = AccelerateDecelerateInterpolator() + b.percentageCircle.startAnimation(a) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceView.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceView.kt new file mode 100644 index 00000000..02be63ad --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/AttendanceView.kt @@ -0,0 +1,84 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-29. + */ + +package pl.szczodrzynski.edziennik.ui.attendance + +import android.annotation.SuppressLint +import android.content.Context +import android.text.TextUtils +import android.util.AttributeSet +import android.util.TypedValue +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.widget.LinearLayout +import androidx.appcompat.widget.AppCompatTextView +import androidx.core.graphics.ColorUtils +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.ext.dp +import pl.szczodrzynski.edziennik.ext.setTintColor +import pl.szczodrzynski.edziennik.utils.managers.AttendanceManager + +class AttendanceView : AppCompatTextView { + + @JvmOverloads + constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr) + + constructor(context: Context, attendance: Attendance, manager: AttendanceManager) : this(context, null) { + setAttendance(attendance, manager, false) + } + + @SuppressLint("RestrictedApi") + fun setAttendance(attendance: Attendance?, manager: AttendanceManager, bigView: Boolean = false) { + if (attendance == null) { + visibility = View.GONE + return + } + visibility = View.VISIBLE + + val attendanceName = if (manager.useSymbols) + attendance.typeSymbol + else + attendance.typeShort + + val attendanceColor = manager.getAttendanceColor(attendance) + + text = when { + attendanceName.isBlank() -> " " + else -> attendanceName + } + + setTextColor(if (ColorUtils.calculateLuminance(attendanceColor) > 0.3) + 0xaa000000.toInt() + else + 0xccffffff.toInt()) + + setBackgroundResource(if (bigView) R.drawable.bg_rounded_8dp else R.drawable.bg_rounded_4dp) + background.setTintColor(attendanceColor) + gravity = Gravity.CENTER + + if (bigView) { + setTextSize(TypedValue.COMPLEX_UNIT_SP, 22f) + setAutoSizeTextTypeUniformWithConfiguration( + 14, + 32, + 1, + TypedValue.COMPLEX_UNIT_SP + ) + setPadding(2.dp, 2.dp, 2.dp, 2.dp) + } + else { + setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f) + setPadding(5.dp, 0, 5.dp, 0) + layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { + setMargins(0, 0, 5.dp, 0) + } + maxLines = 1 + ellipsize = TextUtils.TruncateAt.END + measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) + } + } +} + diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceCount.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceCount.kt new file mode 100644 index 00000000..787c10e3 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceCount.kt @@ -0,0 +1,20 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-30. + */ + +package pl.szczodrzynski.edziennik.ui.attendance.models + +class AttendanceCount { + var normalSum = 0f + var normalCount = 0 + var normalWeightedSum = 0f + var normalWeightedCount = 0f + + var pointSum = 0f + + var pointAvgSum = 0f + var pointAvgMax = 0f + + var normalAvg: Float? = null + var pointAvgPercent: Float? = null +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceDayRange.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceDayRange.kt new file mode 100644 index 00000000..a3815861 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceDayRange.kt @@ -0,0 +1,23 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-30. + */ + +package pl.szczodrzynski.edziennik.ui.attendance.models + +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.data.db.full.AttendanceFull +import pl.szczodrzynski.edziennik.ui.grades.models.ExpandableItemModel +import pl.szczodrzynski.edziennik.utils.models.Date + +data class AttendanceDayRange( + var rangeStart: Date, + var rangeEnd: Date?, + override val items: MutableList = mutableListOf() +) : ExpandableItemModel(items) { + override var level = 1 + + var lastAddedDate = 0L + + var hasUnseen: Boolean = false + get() = field || items.any { it.baseType != Attendance.TYPE_PRESENT && !it.seen } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceEmpty.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceEmpty.kt new file mode 100644 index 00000000..82a8a5be --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceEmpty.kt @@ -0,0 +1,7 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-5-4. + */ + +package pl.szczodrzynski.edziennik.ui.attendance.models + +class AttendanceEmpty diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceMonth.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceMonth.kt new file mode 100644 index 00000000..a51af848 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceMonth.kt @@ -0,0 +1,26 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-30. + */ + +package pl.szczodrzynski.edziennik.ui.attendance.models + +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.data.db.entity.AttendanceType +import pl.szczodrzynski.edziennik.data.db.full.AttendanceFull +import pl.szczodrzynski.edziennik.ui.grades.models.ExpandableItemModel + +data class AttendanceMonth( + val year: Int, + val month: Int, + override val items: MutableList = mutableListOf() +) : ExpandableItemModel(items) { + override var level = 1 + + var lastAddedDate = 0L + + var hasUnseen: Boolean = false + get() = field || items.any { it.baseType != Attendance.TYPE_PRESENT && !it.seen } + + var typeCountMap: Map = mapOf() + var percentage: Float = 0f +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceSubject.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceSubject.kt new file mode 100644 index 00000000..db5f34a1 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceSubject.kt @@ -0,0 +1,26 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-5-4. + */ + +package pl.szczodrzynski.edziennik.ui.attendance.models + +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.data.db.entity.AttendanceType +import pl.szczodrzynski.edziennik.data.db.full.AttendanceFull +import pl.szczodrzynski.edziennik.ui.grades.models.ExpandableItemModel + +data class AttendanceSubject( + val subjectId: Long, + val subjectName: String, + override val items: MutableList = mutableListOf() +) : ExpandableItemModel(items) { + override var level = 1 + + var lastAddedDate = 0L + + var hasUnseen: Boolean = false + get() = field || items.any { it.baseType != Attendance.TYPE_PRESENT && !it.seen } + + var typeCountMap: Map = mapOf() + var percentage: Float = 0f +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceTypeGroup.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceTypeGroup.kt new file mode 100644 index 00000000..a6399456 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/models/AttendanceTypeGroup.kt @@ -0,0 +1,25 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-5-8. + */ + +package pl.szczodrzynski.edziennik.ui.attendance.models + +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.data.db.entity.AttendanceType +import pl.szczodrzynski.edziennik.data.db.full.AttendanceFull +import pl.szczodrzynski.edziennik.ui.grades.models.ExpandableItemModel + +data class AttendanceTypeGroup( + val type: AttendanceType, + override val items: MutableList = mutableListOf() +) : ExpandableItemModel(items) { + override var level = 1 + + var lastAddedDate = 0L + + var hasUnseen: Boolean = false + get() = field || items.any { it.baseType != Attendance.TYPE_PRESENT && !it.seen } + + var percentage: Float = 0f + var semesterCount: Int = 0 +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/AttendanceViewHolder.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/AttendanceViewHolder.kt new file mode 100644 index 00000000..ab6a0b92 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/AttendanceViewHolder.kt @@ -0,0 +1,80 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-30. + */ + +package pl.szczodrzynski.edziennik.ui.attendance.viewholder + +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.isVisible +import androidx.recyclerview.widget.RecyclerView +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.db.full.AttendanceFull +import pl.szczodrzynski.edziennik.databinding.AttendanceItemAttendanceBinding +import pl.szczodrzynski.edziennik.ext.concat +import pl.szczodrzynski.edziennik.ui.attendance.AttendanceAdapter +import pl.szczodrzynski.edziennik.ui.attendance.models.AttendanceDayRange +import pl.szczodrzynski.edziennik.ui.attendance.models.AttendanceMonth +import pl.szczodrzynski.edziennik.ui.grades.models.ExpandableItemModel +import pl.szczodrzynski.edziennik.ui.grades.viewholder.BindableViewHolder +import pl.szczodrzynski.edziennik.utils.managers.NoteManager +import pl.szczodrzynski.edziennik.utils.models.Week + +class AttendanceViewHolder( + inflater: LayoutInflater, + parent: ViewGroup, + val b: AttendanceItemAttendanceBinding = AttendanceItemAttendanceBinding.inflate(inflater, parent, false) +) : RecyclerView.ViewHolder(b.root), BindableViewHolder { + companion object { + private const val TAG = "AttendanceViewHolder" + } + + override fun onBind(activity: AppCompatActivity, app: App, item: AttendanceFull, position: Int, adapter: AttendanceAdapter) { + val manager = app.attendanceManager + + val bullet = " • " + + b.attendanceView.setAttendance(item, manager, bigView = true) + + b.type.text = item.typeName + b.subjectName.text = item.getNoteSubstituteText(adapter.showNotes) ?: item.subjectLongName + ?: item.lessonTopic + if (adapter.showNotes) + NoteManager.prependIcon(item, b.subjectName) + b.dateTime.text = listOf( + Week.getFullDayName(item.date.weekDay), + item.date.formattedStringShort, + item.startTime?.stringHM, + item.lessonNumber?.let { app.getString(R.string.attendance_lesson_number_format, it) } + ).concat(bullet) + + if (item.showAsUnseen == null) + item.showAsUnseen = !item.seen + + b.unread.isVisible = item.showAsUnseen == true + if (!item.seen) { + manager.markAsSeen(item) + + val container = adapter.items.firstOrNull { + it is ExpandableItemModel<*> && it.items.contains(item) + } as? ExpandableItemModel<*> ?: return + + var hasUnseen = true + if (container is AttendanceDayRange) { + hasUnseen = container.items.any { !it.seen } + container.hasUnseen = hasUnseen + } + if (container is AttendanceMonth) { + hasUnseen = container.items.any { !it.seen } + container.hasUnseen = hasUnseen + } + + // check if the unseen status has changed + if (!hasUnseen) { + adapter.notifyItemChanged(container) + } + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/DayRangeViewHolder.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/DayRangeViewHolder.kt new file mode 100644 index 00000000..ef0647bb --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/DayRangeViewHolder.kt @@ -0,0 +1,72 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-30. + */ + +package pl.szczodrzynski.edziennik.ui.attendance.viewholder + +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import androidx.appcompat.app.AppCompatActivity +import androidx.appcompat.view.ContextThemeWrapper +import androidx.core.view.isVisible +import androidx.recyclerview.widget.RecyclerView +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.databinding.AttendanceItemDayRangeBinding +import pl.szczodrzynski.edziennik.ext.concat +import pl.szczodrzynski.edziennik.ui.attendance.AttendanceAdapter +import pl.szczodrzynski.edziennik.ui.attendance.AttendanceAdapter.Companion.STATE_CLOSED +import pl.szczodrzynski.edziennik.ui.attendance.AttendanceView +import pl.szczodrzynski.edziennik.ui.attendance.models.AttendanceDayRange +import pl.szczodrzynski.edziennik.ui.grades.viewholder.BindableViewHolder +import pl.szczodrzynski.edziennik.utils.Themes + +class DayRangeViewHolder( + inflater: LayoutInflater, + parent: ViewGroup, + val b: AttendanceItemDayRangeBinding = AttendanceItemDayRangeBinding.inflate(inflater, parent, false) +) : RecyclerView.ViewHolder(b.root), BindableViewHolder { + companion object { + private const val TAG = "DayRangeViewHolder" + } + + override fun onBind(activity: AppCompatActivity, app: App, item: AttendanceDayRange, position: Int, adapter: AttendanceAdapter) { + val manager = app.attendanceManager + val contextWrapper = ContextThemeWrapper(activity, Themes.appTheme) + + b.title.text = listOf( + item.rangeStart.formattedString, + item.rangeEnd?.formattedString + ).concat(" - ") + + b.dropdownIcon.rotation = when (item.state) { + STATE_CLOSED -> 0f + else -> 180f + } + + b.unread.isVisible = item.hasUnseen + + b.previewContainer.visibility = if (item.state == STATE_CLOSED) View.VISIBLE else View.INVISIBLE + b.summaryContainer.visibility = if (item.state == STATE_CLOSED) View.INVISIBLE else View.VISIBLE + + b.previewContainer.removeAllViews() + + for (attendance in item.items) { + if (attendance.baseType == Attendance.TYPE_PRESENT_CUSTOM || attendance.baseType == Attendance.TYPE_UNKNOWN) + continue + b.previewContainer.addView(AttendanceView( + contextWrapper, + attendance, + manager + )) + } + if (item.items.isEmpty() || item.items.none { it.baseType != Attendance.TYPE_PRESENT_CUSTOM && it.baseType != Attendance.TYPE_UNKNOWN }) { + b.previewContainer.addView(TextView(contextWrapper).also { + it.setText(R.string.attendance_empty_text) + }) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/EmptyViewHolder.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/EmptyViewHolder.kt new file mode 100644 index 00000000..0a0786d6 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/EmptyViewHolder.kt @@ -0,0 +1,29 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-5-4. + */ + +package pl.szczodrzynski.edziennik.ui.attendance.viewholder + +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import androidx.recyclerview.widget.RecyclerView +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.databinding.AttendanceItemEmptyBinding +import pl.szczodrzynski.edziennik.ui.attendance.AttendanceAdapter +import pl.szczodrzynski.edziennik.ui.attendance.models.AttendanceEmpty +import pl.szczodrzynski.edziennik.ui.grades.viewholder.BindableViewHolder + +class EmptyViewHolder( + inflater: LayoutInflater, + parent: ViewGroup, + val b: AttendanceItemEmptyBinding = AttendanceItemEmptyBinding.inflate(inflater, parent, false) +) : RecyclerView.ViewHolder(b.root), BindableViewHolder { + companion object { + private const val TAG = "EmptyViewHolder" + } + + override fun onBind(activity: AppCompatActivity, app: App, item: AttendanceEmpty, position: Int, adapter: AttendanceAdapter) { + + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/MonthViewHolder.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/MonthViewHolder.kt new file mode 100644 index 00000000..f9afd2f3 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/MonthViewHolder.kt @@ -0,0 +1,103 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-4-30. + */ + +package pl.szczodrzynski.edziennik.ui.attendance.viewholder + +import android.view.LayoutInflater +import android.view.ViewGroup +import android.widget.LinearLayout +import android.widget.TextView +import androidx.appcompat.app.AppCompatActivity +import androidx.appcompat.view.ContextThemeWrapper +import androidx.core.view.isInvisible +import androidx.core.view.isVisible +import androidx.recyclerview.widget.RecyclerView +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.databinding.AttendanceItemMonthBinding +import pl.szczodrzynski.edziennik.ext.concat +import pl.szczodrzynski.edziennik.ext.dp +import pl.szczodrzynski.edziennik.ext.fixName +import pl.szczodrzynski.edziennik.ext.setText +import pl.szczodrzynski.edziennik.ui.attendance.AttendanceAdapter +import pl.szczodrzynski.edziennik.ui.attendance.AttendanceAdapter.Companion.STATE_CLOSED +import pl.szczodrzynski.edziennik.ui.attendance.AttendanceView +import pl.szczodrzynski.edziennik.ui.attendance.models.AttendanceMonth +import pl.szczodrzynski.edziennik.ui.grades.viewholder.BindableViewHolder +import pl.szczodrzynski.edziennik.utils.Themes +import pl.szczodrzynski.edziennik.utils.models.Date + +class MonthViewHolder( + inflater: LayoutInflater, + parent: ViewGroup, + val b: AttendanceItemMonthBinding = AttendanceItemMonthBinding.inflate(inflater, parent, false) +) : RecyclerView.ViewHolder(b.root), BindableViewHolder { + companion object { + private const val TAG = "MonthViewHolder" + } + + override fun onBind(activity: AppCompatActivity, app: App, item: AttendanceMonth, position: Int, adapter: AttendanceAdapter) { + val manager = app.attendanceManager + val contextWrapper = ContextThemeWrapper(activity, Themes.appTheme) + + b.title.text = listOf( + app.resources.getStringArray(R.array.material_calendar_months_array).getOrNull(item.month - 1)?.fixName(), + item.year.toString() + ).concat(" ") + + b.dropdownIcon.rotation = when (item.state) { + STATE_CLOSED -> 0f + else -> 180f + } + + b.unread.isVisible = item.hasUnseen + + b.attendanceBar.setAttendanceData(item.typeCountMap.map { manager.getAttendanceColor(it.key) to it.value }) + + b.previewContainer.isInvisible = item.state != STATE_CLOSED + b.summaryContainer.isInvisible = item.state == STATE_CLOSED + b.percentage.isVisible = item.state == STATE_CLOSED + + b.previewContainer.removeAllViews() + + item.typeCountMap.forEach { (type, count) -> + val layout = LinearLayout(contextWrapper) + val attendance = Attendance( + profileId = 0, + id = 0, + baseType = type.baseType, + typeName = "", + typeShort = type.typeShort, + typeSymbol = type.typeSymbol, + typeColor = type.typeColor, + date = Date(0, 0, 0), + startTime = null, + semester = 0, + teacherId = 0, + subjectId = 0, + addedDate = 0 + ) + layout.addView(AttendanceView(contextWrapper, attendance, manager)) + layout.addView(TextView(contextWrapper).also { + //it.setText(R.string.attendance_percentage_format, count/sum*100f) + it.text = count.toString() + it.setPadding(0, 0, 5.dp, 0) + }) + layout.setPadding(0, 8.dp, 0, 0) + b.previewContainer.addView(layout) + } + + if (item.percentage == 0f) { + b.percentage.isVisible = false + b.percentage.text = null + b.summaryContainer.isVisible = false + b.summaryContainer.text = null + } + else { + b.percentage.setText(R.string.attendance_percentage_format, item.percentage) + b.summaryContainer.setText(R.string.attendance_period_summary_format, item.percentage) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/SubjectViewHolder.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/SubjectViewHolder.kt new file mode 100644 index 00000000..a7e5e562 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/SubjectViewHolder.kt @@ -0,0 +1,54 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-5-4. + */ + +package pl.szczodrzynski.edziennik.ui.attendance.viewholder + +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.isVisible +import androidx.recyclerview.widget.RecyclerView +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.databinding.AttendanceItemSubjectBinding +import pl.szczodrzynski.edziennik.ext.setText +import pl.szczodrzynski.edziennik.ui.attendance.AttendanceAdapter +import pl.szczodrzynski.edziennik.ui.attendance.AttendanceAdapter.Companion.STATE_CLOSED +import pl.szczodrzynski.edziennik.ui.attendance.models.AttendanceSubject +import pl.szczodrzynski.edziennik.ui.grades.viewholder.BindableViewHolder + +class SubjectViewHolder( + inflater: LayoutInflater, + parent: ViewGroup, + val b: AttendanceItemSubjectBinding = AttendanceItemSubjectBinding.inflate(inflater, parent, false) +) : RecyclerView.ViewHolder(b.root), BindableViewHolder { + companion object { + private const val TAG = "SubjectViewHolder" + } + + override fun onBind(activity: AppCompatActivity, app: App, item: AttendanceSubject, position: Int, adapter: AttendanceAdapter) { + val manager = app.attendanceManager + + b.title.text = item.subjectName + + b.dropdownIcon.rotation = when (item.state) { + STATE_CLOSED -> 0f + else -> 180f + } + + b.unread.isVisible = item.hasUnseen + + b.attendanceBar.setAttendanceData(item.typeCountMap.map { manager.getAttendanceColor(it.key) to it.value }) + + b.percentage.isVisible = true + + if (item.percentage == 0f) { + b.percentage.isVisible = false + b.percentage.text = null + } + else { + b.percentage.setText(R.string.attendance_percentage_format, item.percentage) + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/TypeViewHolder.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/TypeViewHolder.kt new file mode 100644 index 00000000..6719c3a6 --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/attendance/viewholder/TypeViewHolder.kt @@ -0,0 +1,66 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2020-5-8. + */ + +package pl.szczodrzynski.edziennik.ui.attendance.viewholder + +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.isVisible +import androidx.recyclerview.widget.RecyclerView +import pl.szczodrzynski.edziennik.App +import pl.szczodrzynski.edziennik.R +import pl.szczodrzynski.edziennik.data.db.entity.Attendance +import pl.szczodrzynski.edziennik.databinding.AttendanceItemTypeBinding +import pl.szczodrzynski.edziennik.ext.concat +import pl.szczodrzynski.edziennik.ui.attendance.AttendanceAdapter +import pl.szczodrzynski.edziennik.ui.attendance.models.AttendanceTypeGroup +import pl.szczodrzynski.edziennik.ui.grades.viewholder.BindableViewHolder +import pl.szczodrzynski.edziennik.utils.models.Date + +class TypeViewHolder( + inflater: LayoutInflater, + parent: ViewGroup, + val b: AttendanceItemTypeBinding = AttendanceItemTypeBinding.inflate(inflater, parent, false) +) : RecyclerView.ViewHolder(b.root), BindableViewHolder { + companion object { + private const val TAG = "TypeViewHolder" + } + + override fun onBind(activity: AppCompatActivity, app: App, item: AttendanceTypeGroup, position: Int, adapter: AttendanceAdapter) { + val manager = app.attendanceManager + + val type = item.type + b.title.text = type.typeName + + b.dropdownIcon.rotation = when (item.state) { + AttendanceAdapter.STATE_CLOSED -> 0f + else -> 180f + } + + b.unread.isVisible = item.hasUnseen + + b.details.text = listOf( + app.getString(R.string.attendance_percentage_format, item.percentage), + app.getString(R.string.attendance_type_yearly_format, item.items.size), + app.getString(R.string.attendance_type_semester_format, item.semesterCount) + ).concat(" • ") + + b.type.setAttendance(Attendance( + profileId = 0, + id = 0, + baseType = type.baseType, + typeName = "", + typeShort = type.typeShort, + typeSymbol = type.typeSymbol, + typeColor = type.typeColor, + date = Date(0, 0, 0), + startTime = null, + semester = 0, + teacherId = 0, + subjectId = 0, + addedDate = 0 + ), manager, bigView = false) + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/base/BuildInvalidActivity.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/base/BuildInvalidActivity.kt new file mode 100644 index 00000000..5aa6a84a --- /dev/null +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/base/BuildInvalidActivity.kt @@ -0,0 +1,33 @@ +/* + * Copyright (c) Kuba Szczodrzyński 2021-3-27. + */ + +package pl.szczodrzynski.edziennik.ui.base + +import android.graphics.Color +import android.os.Bundle +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.isVisible +import com.mikepenz.iconics.utils.colorInt +import pl.szczodrzynski.edziennik.databinding.ActivityBuildInvalidBinding +import pl.szczodrzynski.edziennik.ext.onClick +import pl.szczodrzynski.edziennik.utils.Themes + +class BuildInvalidActivity : AppCompatActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setTheme(Themes.themeInt) + val b = ActivityBuildInvalidBinding.inflate(layoutInflater, null, false) + setContentView(b.root) + + setSupportActionBar(b.toolbar) + + b.icon.icon?.colorInt = intent.getIntExtra("color", Color.GREEN) + b.message.text = intent.getStringExtra("message") + b.closeButton.isVisible = !intent.getBooleanExtra("isCritical", true) + b.closeButton.onClick { + finish() + } + } +} diff --git a/app/src/main/java/pl/szczodrzynski/edziennik/ui/modules/base/CrashActivity.kt b/app/src/main/java/pl/szczodrzynski/edziennik/ui/base/CrashActivity.kt similarity index 73% rename from app/src/main/java/pl/szczodrzynski/edziennik/ui/modules/base/CrashActivity.kt rename to app/src/main/java/pl/szczodrzynski/edziennik/ui/base/CrashActivity.kt index 3ae649f6..398134b3 100644 --- a/app/src/main/java/pl/szczodrzynski/edziennik/ui/modules/base/CrashActivity.kt +++ b/app/src/main/java/pl/szczodrzynski/edziennik/ui/base/CrashActivity.kt @@ -1,4 +1,4 @@ -package pl.szczodrzynski.edziennik.ui.modules.base +package pl.szczodrzynski.edziennik.ui.base import android.content.ClipData import android.content.ClipboardManager @@ -6,13 +6,12 @@ import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle -import android.text.Html import android.view.View import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import cat.ereza.customactivityoncrash.CustomActivityOnCrash -import com.afollestad.materialdialogs.MaterialDialog +import com.google.android.material.dialog.MaterialAlertDialogBuilder import kotlinx.coroutines.* import pl.szczodrzynski.edziennik.App import pl.szczodrzynski.edziennik.BuildConfig @@ -20,8 +19,9 @@ import pl.szczodrzynski.edziennik.R import pl.szczodrzynski.edziennik.data.api.ERROR_APP_CRASH import pl.szczodrzynski.edziennik.data.api.szkolny.SzkolnyApi import pl.szczodrzynski.edziennik.data.api.szkolny.request.ErrorReportRequest -import pl.szczodrzynski.edziennik.data.db.entity.Profile +import pl.szczodrzynski.edziennik.ext.resolveColor import pl.szczodrzynski.edziennik.utils.Themes.appTheme +import pl.szczodrzynski.edziennik.utils.html.BetterHtml import kotlin.coroutines.CoroutineContext /* @@ -69,47 +69,31 @@ class CrashActivity : AppCompatActivity(), CoroutineScope { val restartButton = findViewById