Compare commits
371
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a76f6a6a1f | ||
|
|
743caeb681 | ||
|
|
0f50e2f712 | ||
|
|
ce10a3a2bf | ||
|
|
2bb1ae76af | ||
|
|
023c62e5cd | ||
|
|
0117f72b1e | ||
|
|
2060bbe484 | ||
|
|
32742cb5f7 | ||
|
|
5455c9bd9b | ||
|
|
1958adea92 | ||
|
|
2076bc4101 | ||
|
|
43a48eddc3 | ||
|
|
6ccc7d5bf7 | ||
|
|
68c27fa15b | ||
|
|
8b05449dae | ||
|
|
f4cc4ca045 | ||
|
|
b9acfc62cc | ||
|
|
5aa5394d62 | ||
|
|
86be405468 | ||
|
|
0ca55c4750 | ||
|
|
6072328c3a | ||
|
|
5eab12e8bc | ||
|
|
c0c8570ec6 | ||
|
|
50b8438af1 | ||
|
|
bbf71f8e3c | ||
|
|
be55403760 | ||
|
|
b8864a7b3a | ||
|
|
7abce00274 | ||
|
|
f50eaf4b73 | ||
|
|
91d739acf9 | ||
|
|
abaccf6349 | ||
|
|
1e7b01ac0b | ||
|
|
33daaf4625 | ||
|
|
5c294f5fa7 | ||
|
|
700a813bb2 | ||
|
|
3a66b8ea11 | ||
|
|
61e788ea35 | ||
|
|
3115d0b6a8 | ||
|
|
3751f3fd87 | ||
|
|
7401f17ac7 | ||
|
|
11360b355c | ||
|
|
574350f8ee | ||
|
|
e89cbbc8cb | ||
|
|
af4df95121 | ||
|
|
2b83d960d2 | ||
|
|
dae83866e7 | ||
|
|
f290682fe9 | ||
|
|
1241123a3f | ||
|
|
b38398c1c1 | ||
|
|
33218b7489 | ||
|
|
412bffd8b4 | ||
|
|
21a2d7491c | ||
|
|
aa12f3948a | ||
|
|
2735dd7448 | ||
|
|
185885b98b | ||
|
|
3844bdeec6 | ||
|
|
674d743435 | ||
|
|
004d7457f4 | ||
|
|
70bd1d971a | ||
|
|
48ec307f80 | ||
|
|
0bdb093115 | ||
|
|
cc4ac9bee4 | ||
|
|
45d37750a9 | ||
|
|
8a095c4e46 | ||
|
|
20088c58b9 | ||
|
|
06740c9016 | ||
|
|
06a0be21b0 | ||
|
|
90e1a0e432 | ||
|
|
b7a1a18bcc | ||
|
|
e6983a6169 | ||
|
|
7a144d1d93 | ||
|
|
d4023f1b48 | ||
|
|
5426a72d34 | ||
|
|
39643efe60 | ||
|
|
ad6c31017b | ||
|
|
e7a9a06289 | ||
|
|
7a0c64052d | ||
|
|
51361e594a | ||
|
|
cf24691642 | ||
|
|
8ce7411cc4 | ||
|
|
2a94a4f5cd | ||
|
|
b2f37db196 | ||
|
|
6d96355bd4 | ||
|
|
e5322e8112 | ||
|
|
0674521b95 | ||
|
|
c7eb8988e2 | ||
|
|
11f42601eb | ||
|
|
5ee7cffd84 | ||
|
|
34d534d601 | ||
|
|
3a2d3e0cbc | ||
|
|
49a99d89fa | ||
|
|
449d1c3545 | ||
|
|
7bd5b75cd9 | ||
|
|
d7696ea07b | ||
|
|
ff652fcb6e | ||
|
|
2b9c190be0 | ||
|
|
d4a7c387e4 | ||
|
|
9c07c50e8c | ||
|
|
bbe77bf40e | ||
|
|
96cb943f7d | ||
|
|
691f2020b9 | ||
|
|
933c55057e | ||
|
|
a6a7eb425a | ||
|
|
7d9d40e2a4 | ||
|
|
2cfbb1a113 | ||
|
|
b6928a8a58 | ||
|
|
f1f9cdeaf4 | ||
|
|
d379ab9753 | ||
|
|
010088dff5 | ||
|
|
14fef753bd | ||
|
|
35d68cc543 | ||
|
|
911a23cdb8 | ||
|
|
f4c475cc40 | ||
|
|
a0598e97e8 | ||
|
|
3221f2f7ab | ||
|
|
0763a6dc86 | ||
|
|
f8bfacebf8 | ||
|
|
cfaa13a354 | ||
|
|
6ccaa98f6e | ||
|
|
f8b8674216 | ||
|
|
8b2915f917 | ||
|
|
3a5766f3b7 | ||
|
|
93367166a4 | ||
|
|
2860e283c3 | ||
|
|
77ae68c142 | ||
|
|
ba4d1b6b2e | ||
|
|
2d0cc3404b | ||
|
|
9bdb6bc0b2 | ||
|
|
f1e4cc9297 | ||
|
|
a5fe8d7021 | ||
|
|
3e5d8eb65d | ||
|
|
884cf7120d | ||
|
|
1817ea91d5 | ||
|
|
2bee524490 | ||
|
|
7246cf0d36 | ||
|
|
b0f50cf513 | ||
|
|
64fbfd1b1a | ||
|
|
5bf6753ce3 | ||
|
|
e6514e6f19 | ||
|
|
aee3149319 | ||
|
|
41bf8f6000 | ||
|
|
cc6df72b71 | ||
|
|
596d27053d | ||
|
|
f5d1e32650 | ||
|
|
da6d07dc01 | ||
|
|
f35583f972 | ||
|
|
cd702b0476 | ||
|
|
17a7215fd7 | ||
|
|
01366e9fea | ||
|
|
60117173ab | ||
|
|
eefd06d1b4 | ||
|
|
b26126e860 | ||
|
|
067d29618c | ||
|
|
5fe394d880 | ||
|
|
8c113d104e | ||
|
|
9c47dbae94 | ||
|
|
6d8c69f84f | ||
|
|
78701b6cb4 | ||
|
|
bbea7ca25e | ||
|
|
47ff8887f6 | ||
|
|
714d66b094 | ||
|
|
dc9137baa2 | ||
|
|
c54a4c4b58 | ||
|
|
aeb26f1df8 | ||
|
|
14216857e0 | ||
|
|
2c8e25e4c5 | ||
|
|
67a1dbd1d3 | ||
|
|
cd4a3b0e40 | ||
|
|
8508b6e087 | ||
|
|
abadf12b34 | ||
|
|
a08bccf52c | ||
|
|
e176697bb0 | ||
|
|
e2d0ef9543 | ||
|
|
c48d46c1a1 | ||
|
|
d4f2f60205 | ||
|
|
15588caf3e | ||
|
|
c714e9dbf1 | ||
|
|
3a7d11269e | ||
|
|
b7c600ceb0 | ||
|
|
8e418990d8 | ||
|
|
77b3e0b87f | ||
|
|
408768fe68 | ||
|
|
0ed7bb81c9 | ||
|
|
c507443e07 | ||
|
|
d29759bd39 | ||
|
|
1a384ce6fa | ||
|
|
70782cfa87 | ||
|
|
32084225a1 | ||
|
|
342642108b | ||
|
|
74a4087e83 | ||
|
|
a8d64cc7c8 | ||
|
|
f81c9f3f46 | ||
|
|
13d118fe53 | ||
|
|
4a1d21ebcb | ||
|
|
1c26ca53ee | ||
|
|
3de6a81c8c | ||
|
|
8cd27d3609 | ||
|
|
b47365b969 | ||
|
|
0e4fc703d2 | ||
|
|
12f3784129 | ||
|
|
280bee125a | ||
|
|
4f602fe9b2 | ||
|
|
22cfd14d76 | ||
|
|
bb619da1fc | ||
|
|
e35894de57 | ||
|
|
dc5e49ecf7 | ||
|
|
be6de28c10 | ||
|
|
4453d4e743 | ||
|
|
30494030e2 | ||
|
|
906836dec6 | ||
|
|
f5142b3500 | ||
|
|
0fb606f178 | ||
|
|
7fd0847296 | ||
|
|
5ca93caf13 | ||
|
|
dee96e0e81 | ||
|
|
8c2decf6f3 | ||
|
|
493eab1d88 | ||
|
|
9cca391dbd | ||
|
|
0e85a81811 | ||
|
|
20ae8cbc3e | ||
|
|
97eeb9a50a | ||
|
|
e5ffe3bf1d | ||
|
|
da9938beea | ||
|
|
6e3cb94bcb | ||
|
|
a31dede44c | ||
|
|
0a9431439a | ||
|
|
bfede15b81 | ||
|
|
668a2ade4a | ||
|
|
296506ce61 | ||
|
|
b46e9a89ae | ||
|
|
788621ddb4 | ||
|
|
f14f6cb528 | ||
|
|
2fade8210a | ||
|
|
11548cd889 | ||
|
|
ee990006b7 | ||
|
|
1661888b0d | ||
|
|
e47daa2a07 | ||
|
|
a0a089d0b0 | ||
|
|
c8e558fdb2 | ||
|
|
3440c8f431 | ||
|
|
284000a0c2 | ||
|
|
a5e0f4e546 | ||
|
|
438c9ca358 | ||
|
|
d4931fb71c | ||
|
|
36894c179f | ||
|
|
c60067146f | ||
|
|
08bf11fc47 | ||
|
|
6bc444ae51 | ||
|
|
3c00d5e18b | ||
|
|
27c669a319 | ||
|
|
33d69d5aca | ||
|
|
ca514a8a8a | ||
|
|
0802ca07f4 | ||
|
|
59f3255ecd | ||
|
|
52d29c241a | ||
|
|
16663f9b7b | ||
|
|
6f85844587 | ||
|
|
04b9782c57 | ||
|
|
36e8870ef1 | ||
|
|
7db6df6654 | ||
|
|
6efa55f09a | ||
|
|
9eeff8323e | ||
|
|
ddbcdb084c | ||
|
|
e802659c0c | ||
|
|
25fe01ab43 | ||
|
|
b20cbbd5f5 | ||
|
|
b4b8614c33 | ||
|
|
c1d23005a7 | ||
|
|
e102fa6a11 | ||
|
|
bf5400841d | ||
|
|
219587f1c2 | ||
|
|
a22bdd387d | ||
|
|
aefa37ff2e | ||
|
|
41eb72306c | ||
|
|
50e01fe256 | ||
|
|
bb370e8467 | ||
|
|
46d231fa9b | ||
|
|
4b17913271 | ||
|
|
3eb1c79a3e | ||
|
|
6e16f4874c | ||
|
|
2e51293f70 | ||
|
|
f5a4983384 | ||
|
|
06ab182c96 | ||
|
|
dd9c094cc4 | ||
|
|
de442fa508 | ||
|
|
9c76de1e72 | ||
|
|
0785bae437 | ||
|
|
e13ecad3a4 | ||
|
|
e564917cfc | ||
|
|
8f9eaa90ed | ||
|
|
e8aee23c33 | ||
|
|
6dd6959f5b | ||
|
|
bbdf6313e7 | ||
|
|
dfd6fdfd75 | ||
|
|
b5e24ae623 | ||
|
|
61753c6f20 | ||
|
|
d6ba5b2900 | ||
|
|
86c0fac7c1 | ||
|
|
69b48d72f3 | ||
|
|
c57ad1a52f | ||
|
|
c73ec19aae | ||
|
|
f60bd6291c | ||
|
|
e28aec5bd4 | ||
|
|
0e57cf845d | ||
|
|
70681271a0 | ||
|
|
60d72c9990 | ||
|
|
61069b36a4 | ||
|
|
4e98d9e39e | ||
|
|
6b0ed3f312 | ||
|
|
9873834024 | ||
|
|
c13258371e | ||
|
|
2a9f17492a | ||
|
|
5a3e682cc6 | ||
|
|
f873a1fe65 | ||
|
|
e9e9e56841 | ||
|
|
6606fb3867 | ||
|
|
2792cb409b | ||
|
|
9729847c8e | ||
|
|
0314ceb071 | ||
|
|
2e6f069c18 | ||
|
|
094d7f5129 | ||
|
|
d22c9c8346 | ||
|
|
640206f2a5 | ||
|
|
576dc13e8f | ||
|
|
87b12e8218 | ||
|
|
112318024d | ||
|
|
bbaf1bfb13 | ||
|
|
21add7252c | ||
|
|
6a307d4a98 | ||
|
|
4a8bc91d8c | ||
|
|
92ef82afbc | ||
|
|
2affe52783 | ||
|
|
14a7e87bdd | ||
|
|
66e1f00d42 | ||
|
|
c9917ded8e | ||
|
|
6d9fabb398 | ||
|
|
57311cf2b8 | ||
|
|
90ae4ed1e2 | ||
|
|
4b4391e145 | ||
|
|
4dfe198732 | ||
|
|
65336213a6 | ||
|
|
5fbc88c212 | ||
|
|
c74248938a | ||
|
|
e5b56f3d93 | ||
|
|
011d83b508 | ||
|
|
0a3d4d559e | ||
|
|
af99094219 | ||
|
|
cb2de5ca71 | ||
|
|
12f8c055ac | ||
|
|
3b0efbb2a7 | ||
|
|
d90384b34b | ||
|
|
5ee406f451 | ||
|
|
880ef3b489 | ||
|
|
a6cc236992 | ||
|
|
cfec844cb8 | ||
|
|
8a7eb8e96a | ||
|
|
0f03ff9b36 | ||
|
|
b2bef4a86a | ||
|
|
538347cc47 | ||
|
|
27793020bc | ||
|
|
6aec6dd706 | ||
|
|
59689586c9 | ||
|
|
964eda3d5a | ||
|
|
1d72b071b5 | ||
|
|
80f3b69c6b | ||
|
|
b32b929265 | ||
|
|
72d2968837 | ||
|
|
1b845af5d0 | ||
|
|
d131d51ac4 | ||
|
|
155baeba00 |
No files matched your search
@@ -1,4 +1,4 @@
|
||||
FROM ubuntu:resolute@sha256:2260313b31c8c011cd2eebe728008efac1b3982be73eb71348ea2648d2c0e09b
|
||||
FROM ubuntu:resolute@sha256:513c074113a871b51a8d16ab445c88779d6452d937a164fb5cc479f32668a41d
|
||||
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
ENV ANDROID_HOME=/usr/lib/android-sdk
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
@@ -0,0 +1,179 @@
|
||||
# This workflow is provided via the organization template repository
|
||||
#
|
||||
# https://github.com/nextcloud/.github
|
||||
# https://docs.github.com/en/actions/learn-github-actions/sharing-workflows-with-your-organization
|
||||
#
|
||||
# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
name: AI Policy
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened]
|
||||
branches: [master, main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
# Required to add the "AI assisted" label via `gh pr edit --add-label`
|
||||
pull-requests: write
|
||||
# Required to create the "AI assisted" label via the REST labels endpoint
|
||||
# (labels are an issues-scoped resource in the GitHub API)
|
||||
issues: write
|
||||
|
||||
concurrency:
|
||||
group: ai-policy-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
check-ai-trailers:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Collect PR commit messages
|
||||
id: collect
|
||||
env:
|
||||
BASE_REF: ${{ github.base_ref }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch origin "${BASE_REF}"
|
||||
MERGE_BASE=$(git merge-base "origin/${BASE_REF}" HEAD)
|
||||
git log --format="%B" "${MERGE_BASE}..HEAD" > /tmp/pr_commits.txt
|
||||
echo "--- PR commit messages ---"
|
||||
cat /tmp/pr_commits.txt
|
||||
echo "--------------------------"
|
||||
|
||||
- name: Define shared agent detection patterns
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
# Email addresses known to be used by coding agents.
|
||||
# These should never appear in Signed-off-by because the DCO can only be attested by a human.
|
||||
EMAIL_PATTERN="copilot@github\.com\
|
||||
|noreply@anthropic\.com\
|
||||
|devin@cognition\.ai\
|
||||
|devin@cognition-labs\.com\
|
||||
|aider@aider\.chat\
|
||||
|noreply@aider\.chat\
|
||||
|codex@openai\.com\
|
||||
|cursor@anysphere\.com\
|
||||
|windsurf@codeium\.com\
|
||||
|codeium@codeium\.com\
|
||||
|amazon-q@amazon\.com\
|
||||
|codewhisperer@amazon\.com\
|
||||
|gemini-code-assist@google\.com\
|
||||
|openhands@all-hands\.dev\
|
||||
|swe-agent@princeton\.edu"
|
||||
|
||||
# Strip embedded whitespace (used above only for readability)
|
||||
EMAIL_PATTERN=$(echo "$EMAIL_PATTERN" | tr -d ' \n')
|
||||
echo "AGENT_EMAIL_PATTERN=${EMAIL_PATTERN}" >> "$GITHUB_ENV"
|
||||
|
||||
# Display-name prefixes used by known coding agents (shared by Signed-off-by and Co-Authored-By checks)
|
||||
# shellcheck disable=SC2016
|
||||
echo 'AGENT_NAMES=GitHub Copilot|Claude( [A-Za-z0-9. -]+)?|Devin( AI)?|aider( \(.*\))?|OpenAI Codex|Cursor( AI)?|Windsurf|Amazon Q|CodeWhisperer|Gemini Code Assist|OpenHands|SWE-agent|AutoCodeRover|Tabnine' >> "$GITHUB_ENV"
|
||||
|
||||
- name: Check for AI-assistant / Assisted-by trailers
|
||||
id: ai_trailers
|
||||
run: |
|
||||
set -euo pipefail
|
||||
AI_ASSISTED=false
|
||||
if grep -qiE '^(AI-assistant|Assisted-by):' /tmp/pr_commits.txt; then
|
||||
AI_ASSISTED=true
|
||||
echo "Found AI-assistant/Assisted-by trailer(s):"
|
||||
grep -iE '^(AI-assistant|Assisted-by):' /tmp/pr_commits.txt
|
||||
fi
|
||||
echo "ai_assisted=${AI_ASSISTED}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Check for coding-agent Signed-off-by trailers
|
||||
id: agent_signoff
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
EMAIL_HITS=$(grep -iE "^Signed-off-by:.*<(${AGENT_EMAIL_PATTERN})>" /tmp/pr_commits.txt 2>/dev/null || true)
|
||||
NAME_HITS=$(grep -iE "^Signed-off-by: *(${AGENT_NAMES}) *[<(]" /tmp/pr_commits.txt 2>/dev/null || true)
|
||||
|
||||
AGENT_LINES=$(printf '%s\n%s' "$EMAIL_HITS" "$NAME_HITS" | sort -u | sed '/^[[:space:]]*$/d')
|
||||
|
||||
AGENT_SIGNOFF=false
|
||||
if [ -n "$AGENT_LINES" ]; then
|
||||
AGENT_SIGNOFF=true
|
||||
fi
|
||||
|
||||
echo "agent_signoff=${AGENT_SIGNOFF}" >> "$GITHUB_OUTPUT"
|
||||
{
|
||||
echo "agent_lines<<AGENT_EOF"
|
||||
echo "${AGENT_LINES}"
|
||||
echo "AGENT_EOF"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Check for coding-agent Co-Authored-By trailers
|
||||
id: co_authored
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
EMAIL_HITS=$(grep -iE "^Co-Authored-By:.*<(${AGENT_EMAIL_PATTERN})>" /tmp/pr_commits.txt 2>/dev/null || true)
|
||||
NAME_HITS=$(grep -iE "^Co-Authored-By: *(${AGENT_NAMES}) *[<(]" /tmp/pr_commits.txt 2>/dev/null || true)
|
||||
|
||||
CO_AUTHORED=false
|
||||
if [ -n "$EMAIL_HITS" ] || [ -n "$NAME_HITS" ]; then
|
||||
CO_AUTHORED=true
|
||||
echo "Found coding-agent Co-Authored-By trailer(s):"
|
||||
printf '%s\n%s' "$EMAIL_HITS" "$NAME_HITS" | sort -u | sed '/^[[:space:]]*$/d'
|
||||
fi
|
||||
|
||||
echo "co_authored=${CO_AUTHORED}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create 'AI assisted' label if absent
|
||||
if: steps.ai_trailers.outputs.ai_assisted == 'true' || steps.agent_signoff.outputs.agent_signoff == 'true' || steps.co_authored.outputs.co_authored == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh api "repos/${{ github.repository }}/labels" \
|
||||
--method POST \
|
||||
-f name="AI assisted" \
|
||||
-f color="d93f0b" \
|
||||
-f description="This PR contains AI-assisted commits" \
|
||||
2>/dev/null || true
|
||||
|
||||
- name: Label PR as AI assisted
|
||||
if: steps.ai_trailers.outputs.ai_assisted == 'true' || steps.agent_signoff.outputs.agent_signoff == 'true' || steps.co_authored.outputs.co_authored == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh pr edit "${{ github.event.pull_request.number }}" \
|
||||
--repo "${{ github.repository }}" \
|
||||
--add-label "AI assisted"
|
||||
echo "Added 'AI assisted' label to PR #${{ github.event.pull_request.number }}"
|
||||
|
||||
- name: Fail on coding-agent Signed-off-by
|
||||
if: steps.agent_signoff.outputs.agent_signoff == 'true'
|
||||
env:
|
||||
AGENT_LINES: ${{ steps.agent_signoff.outputs.agent_lines }}
|
||||
AGENTS_MD_URL: https://github.com/${{ github.repository }}/blob/${{ github.base_ref }}/AGENTS.md
|
||||
run: |
|
||||
echo "::error title=Coding-agent sign-off detected::A Signed-off-by trailer from a known coding agent was found in one or more commits."
|
||||
echo ""
|
||||
echo "Offending trailer(s):"
|
||||
echo "${AGENT_LINES}"
|
||||
echo ""
|
||||
echo "The 'Signed-off-by' trailer represents the Developer Certificate of Origin (DCO)"
|
||||
echo "and must only be attested by a human contributor."
|
||||
echo "Please amend the affected commit(s) to remove the coding-agent sign-off"
|
||||
echo "and replace it with an 'Assisted-by' trailer, for example:"
|
||||
echo ""
|
||||
echo " Assisted-by: Claude Code:claude-sonnet-4-6"
|
||||
echo ""
|
||||
echo "References:"
|
||||
echo " • AGENTS.md (this repository)"
|
||||
echo " ${AGENTS_MD_URL}"
|
||||
echo " • AI Contribution Policy"
|
||||
echo " https://github.com/nextcloud/.github/blob/master/AI_POLICY.md"
|
||||
echo " • Contribution Guidelines"
|
||||
echo " https://github.com/nextcloud/.github/blob/master/CONTRIBUTING.md"
|
||||
exit 1
|
||||
@@ -0,0 +1,76 @@
|
||||
# synced from @nextcloud/android-config
|
||||
|
||||
# SPDX-FileCopyrightText: 2023-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2023 Tobias Kaminsky <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2023 Andy Scherzinger <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2023 Josh Richards <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2025 Marcel Hibbe <[email protected]>
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
name: "Analysis"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [ "master", "main", "stable-*" ]
|
||||
push:
|
||||
branches: [ "master", "main", "stable-*" ]
|
||||
|
||||
permissions:
|
||||
pull-requests: write
|
||||
contents: write
|
||||
|
||||
concurrency:
|
||||
group: analysis-wrapper-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
analysis:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Disabled on forks
|
||||
if: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }}
|
||||
run: |
|
||||
echo 'Can not analyze PRs from forks'
|
||||
exit 1
|
||||
- name: Setup variables # zizmor: ignore[template-injection]
|
||||
id: get-vars
|
||||
run: |
|
||||
if [ -z "$GITHUB_HEAD_REF" ]; then
|
||||
# push
|
||||
{
|
||||
echo "branch=$GITHUB_REF_NAME"
|
||||
echo "pr=$GITHUB_RUN_ID"
|
||||
echo "repo=${{ github.repository }}"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
# pull request
|
||||
{
|
||||
echo "branch=$GITHUB_HEAD_REF"
|
||||
echo "pr=${{ github.event.pull_request.number }}"
|
||||
echo "repo=${{ github.event.pull_request.head.repo.full_name }}"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
repository: ${{ steps.get-vars.outputs.repo }}
|
||||
ref: ${{ steps.get-vars.outputs.branch }}
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 21
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
sudo apt install python3-defusedxml
|
||||
- name: Run analysis wrapper
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
mkdir -p "$HOME/.gradle"
|
||||
{
|
||||
echo "org.gradle.jvmargs=-Xmx1g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8"
|
||||
echo "org.gradle.configureondemand=true"
|
||||
} > "$HOME/.gradle/gradle.properties"
|
||||
scripts/analysis/analysis-wrapper.sh "${{ steps.get-vars.outputs.branch }}" "${{ secrets.LOG_USERNAME }}" "${{ secrets.LOG_PASSWORD }}" "$GITHUB_RUN_NUMBER" "${{ steps.get-vars.outputs.pr }}"
|
||||
@@ -5,7 +5,9 @@ name: "Assemble"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [master, stable-*]
|
||||
branches: [ master, stable-* ]
|
||||
push:
|
||||
branches: [ master ]
|
||||
|
||||
# Declare default permissions as read only.
|
||||
permissions: read-all
|
||||
@@ -15,54 +17,35 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
compile:
|
||||
runs-on: ubuntu-latest-max
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: set up JDK 21
|
||||
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 21
|
||||
- name: compile
|
||||
run: |
|
||||
echo "org.gradle.dependency.verification=lenient" >> gradle.properties
|
||||
echo "org.gradle.jvmargs=-Xmx10g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g" >> gradle.properties
|
||||
echo "org.gradle.caching=true" >> gradle.properties
|
||||
echo "org.gradle.parallel=true" >> gradle.properties
|
||||
echo "org.gradle.configureondemand=true" >> gradle.properties
|
||||
- uses: gradle/actions/wrapper-validation@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
|
||||
- name: Gradle Cache
|
||||
uses: burrunan/gradle-cache-action@404534c34a2faa40430357a3183522a845b04f3b # v3.0.3
|
||||
with:
|
||||
job-id: assemble
|
||||
arguments: assembleGeneric
|
||||
|
||||
flavor:
|
||||
name: flavor (${{ matrix.flavor }})
|
||||
runs-on: ubuntu-latest
|
||||
needs: [compile]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
flavor: [Generic, Gplay, Huawei]
|
||||
include:
|
||||
- flavor: Generic
|
||||
tasks: assembleGenericDebug
|
||||
- flavor: Gplay
|
||||
tasks: assembleGplayDebug assembleGplayRelease
|
||||
- flavor: Huawei
|
||||
tasks: assembleHuaweiDebug
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: set up JDK 21
|
||||
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 21
|
||||
- uses: gradle/actions/wrapper-validation@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
|
||||
- name: compile
|
||||
run: |
|
||||
echo "org.gradle.dependency.verification=lenient" >> gradle.properties
|
||||
echo "org.gradle.jvmargs=-Xmx10g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g" >> gradle.properties
|
||||
echo "org.gradle.caching=true" >> gradle.properties
|
||||
echo "org.gradle.parallel=true" >> gradle.properties
|
||||
echo "org.gradle.configureondemand=true" >> gradle.properties
|
||||
- uses: gradle/actions/wrapper-validation@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
|
||||
- name: Gradle Cache
|
||||
uses: burrunan/gradle-cache-action@404534c34a2faa40430357a3183522a845b04f3b # v3.0.3
|
||||
with:
|
||||
job-id: assemble
|
||||
arguments: assemble${{ matrix.flavor }}
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: set up JDK 21
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 21
|
||||
- uses: gradle/actions/wrapper-validation@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
|
||||
- name: Build ${{ matrix.flavor }}
|
||||
run: |
|
||||
{
|
||||
echo "org.gradle.jvmargs=-Xmx4g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=768m"
|
||||
echo "kotlin.daemon.jvmargs=-Xmx3g -XX:+UseParallelGC -XX:MaxMetaspaceSize=512m"
|
||||
echo "org.gradle.workers.max=2"
|
||||
} >> gradle.properties
|
||||
./gradlew ${{ matrix.tasks }}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# synced from @nextcloud/android-config
|
||||
|
||||
# SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-FileCopyrightText: 2023 Álvaro Brey <[email protected]>
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
name: Auto approve sync
|
||||
on:
|
||||
pull_request_target: # zizmor: ignore[dangerous-triggers]
|
||||
branches:
|
||||
- master
|
||||
- main
|
||||
types:
|
||||
- opened
|
||||
- reopened
|
||||
- synchronize
|
||||
- labeled
|
||||
|
||||
concurrency:
|
||||
group: sync-approve-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
auto-approve:
|
||||
name: Auto approve sync
|
||||
runs-on: ubuntu-latest-low
|
||||
if: ${{ contains(github.event.pull_request.labels.*.name, 'sync') && github.actor == 'nextcloud-android-bot' }}
|
||||
steps:
|
||||
- name: Disabled on forks
|
||||
if: ${{ github.event.pull_request.head.repo.full_name != github.repository }}
|
||||
run: |
|
||||
echo 'Can not approve PRs from forks'
|
||||
exit 1
|
||||
|
||||
- uses: hmarr/auto-approve-action@f0939ea97e9205ef24d872e76833fa908a770363 # v4.0.0
|
||||
with:
|
||||
github-token: "${{ secrets.GITHUB_TOKEN }}"
|
||||
@@ -0,0 +1,36 @@
|
||||
# SPDX-FileCopyrightText: 2020-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
|
||||
name: Check
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [ master, stable-* ]
|
||||
push:
|
||||
branches: [ master ]
|
||||
|
||||
# Declare default permissions as read only.
|
||||
permissions: read-all
|
||||
|
||||
concurrency:
|
||||
group: check-kotlin-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
task: [ detekt, spotlessKotlinCheck, lint ]
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 21
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
|
||||
- name: Check ${{ matrix.task }}
|
||||
run: ./gradlew ${{ matrix.task }}
|
||||
@@ -0,0 +1,63 @@
|
||||
# synced from @nextcloud/android-config
|
||||
|
||||
# SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-FileCopyrightText: 2023-2024 Andy Scherzinger <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2022 Tobias Kaminsky <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2022 Álvaro Brey <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2025 Marcel Hibbe <[email protected]>
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
name: "CodeQL"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master", "main", "stable-*" ]
|
||||
pull_request:
|
||||
branches: [ "master", "main" ]
|
||||
schedule:
|
||||
- cron: '24 18 * * 3'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: codeql-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
security-events: write
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: [ 'java' ]
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Set Swap Space
|
||||
if: runner.environment == 'github-hosted'
|
||||
uses: pierotofy/set-swap-space@49819abfb41bd9b44fb781159c033dba90353a7c # v1.0
|
||||
with:
|
||||
swap-size-gb: 10
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 21
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
|
||||
- name: Compile sources
|
||||
run: ./gradlew --no-daemon --no-build-cache :app:compileGplayDebugSources
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/bin/sh
|
||||
|
||||
# Nextcloud Android Library
|
||||
#
|
||||
# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-License-Identifier: MIT
|
||||
#
|
||||
|
||||
if [ $1 = "master" ]; then
|
||||
SERVER_VERSION_MAIN="main"
|
||||
SERVER_VERSION_MASTER="master"
|
||||
else
|
||||
SERVER_VERSION_MAIN=$1
|
||||
SERVER_VERSION_MASTER=$1
|
||||
fi
|
||||
|
||||
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash
|
||||
export NVM_DIR="$HOME/.nvm"
|
||||
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
|
||||
|
||||
. ~/.bashrc; nvm install node
|
||||
|
||||
php /var/www/html/occ log:manage --level warning
|
||||
|
||||
OC_PASS=user1 php /var/www/html/occ user:add --password-from-env --display-name='User One' user1
|
||||
OC_PASS=user2 php /var/www/html/occ user:add --password-from-env --display-name='User Two' user2
|
||||
OC_PASS=user3 php /var/www/html/occ user:add --password-from-env --display-name='User Three' user3
|
||||
OC_PASS=test php /var/www/html/occ user:add --password-from-env --display-name='Test@Test' test@test
|
||||
OC_PASS=test php /var/www/html/occ user:add --password-from-env --display-name='Test Spaces' 'test test'
|
||||
php /var/www/html/occ user:setting user2 files quota 1G
|
||||
php /var/www/html/occ group:add users
|
||||
php /var/www/html/occ group:adduser users user1
|
||||
php /var/www/html/occ group:adduser users user2
|
||||
php /var/www/html/occ group:adduser users test
|
||||
|
||||
git clone --depth=1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/activity.git /var/www/html/apps/activity/
|
||||
php /var/www/html/occ app:enable -f activity
|
||||
|
||||
git clone --depth=1 -b $SERVER_VERSION_MAIN https://github.com/nextcloud/text.git /var/www/html/apps/text/
|
||||
php /var/www/html/occ app:enable -f text
|
||||
|
||||
git clone --depth=1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/end_to_end_encryption.git /var/www/html/apps/end_to_end_encryption/
|
||||
php /var/www/html/occ app:enable -f end_to_end_encryption
|
||||
|
||||
git clone --depth=1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/password_policy.git /var/www/html/apps/password_policy/
|
||||
php /var/www/html/occ app:enable -f password_policy
|
||||
|
||||
git clone --depth=1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/external.git /var/www/html/apps/external/
|
||||
cd /var/www/html/apps/external; composer install --no-dev
|
||||
php /var/www/html/occ app:enable -f external
|
||||
php /var/www/html/occ config:app:set external sites --value="{\"1\":{\"id\":1,\"name\":\"Nextcloud\",\"url\":\"https:\/\/www.nextcloud.com\",\"lang\":\"\",\"type\":\"link\",\"device\":\"\",\"icon\":\"external.svg\",\"groups\":[],\"redirect\":false},\"2\":{\"id\":2,\"name\":\"Forum\",\"url\":\"https:\/\/help.nextcloud.com\",\"lang\":\"\",\"type\":\"link\",\"device\":\"\",\"icon\":\"external.svg\",\"groups\":[],\"redirect\":false}}"
|
||||
|
||||
git clone --depth=1 -b $SERVER_VERSION_MAIN https://github.com/nextcloud/files_lock.git /var/www/html/apps/files_lock/
|
||||
php /var/www/html/occ app:enable -f files_lock
|
||||
|
||||
git clone --depth=1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/notifications.git /var/www/html/apps/notifications/
|
||||
cd /var/www/html/apps/notifications; composer install --no-dev
|
||||
php /var/www/html/occ app:enable -f notifications
|
||||
|
||||
if [ $1 = 'stable22' ]; then
|
||||
php /var/www/html/occ notification:generate test test
|
||||
else
|
||||
php /var/www/html/occ notification:generate test -d test
|
||||
fi
|
||||
|
||||
git clone --depth=1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/photos.git /var/www/html/apps/photos/
|
||||
cd /var/www/html/apps/photos; composer install --no-dev
|
||||
php /var/www/html/occ app:enable -f photos
|
||||
|
||||
git clone --depth=1 -b $SERVER_VERSION_MAIN https://github.com/nextcloud/assistant.git /var/www/html/apps/assistant/
|
||||
cd /var/www/html/apps/assistant; . ~/.bashrc; make
|
||||
php /var/www/html/occ app:enable -f assistant
|
||||
|
||||
php /var/www/html/occ app:enable -f testing
|
||||
|
||||
git clone --depth 1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/files_downloadlimit.git /var/www/html/apps/files_downloadlimit/
|
||||
php /var/www/html/occ app:enable -f files_downloadlimit
|
||||
|
||||
git clone --depth 1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/recommendations.git /var/www/html/apps/recommendations/
|
||||
cd /var/www/html/apps/recommendations; composer install --no-dev
|
||||
php /var/www/html/occ app:enable -f recommendations
|
||||
|
||||
git clone --depth 1 -b $SERVER_VERSION_MASTER https://github.com/nextcloud/viewer.git /var/www/html/apps/viewer/
|
||||
php /var/www/html/occ app:enable -f viewer
|
||||
|
||||
php /var/www/html/occ config:system:set ratelimit.protection.enabled --value false --type bool
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
|
||||
# Nextcloud Android Library
|
||||
#
|
||||
# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-License-Identifier: MIT
|
||||
#
|
||||
|
||||
wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg
|
||||
apt-get update && apt-get install -y composer
|
||||
mkdir /var/www/.nvm /var/www/.npm
|
||||
mkdir /var/www/.cache/
|
||||
touch /var/www/.bashrc
|
||||
chown -R 33:33 /var/www/.nvm /var/www/.npm /var/www/.bashrc /var/www/.cache
|
||||
|
||||
cd /var/www/html/
|
||||
rm data -rf
|
||||
rm config/config.php
|
||||
su www-data -c "git reset --hard"
|
||||
BRANCH="$1" /usr/local/bin/initnc.sh
|
||||
@@ -0,0 +1,43 @@
|
||||
# synced from @nextcloud/android-config
|
||||
|
||||
# SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-FileCopyrightText: 2023 Andy Scherzinger <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2022 Tobias Kaminsky <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2022 Álvaro Brey <[email protected]>
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
name: "Detect new java files"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [ master, main, stable-* ]
|
||||
|
||||
permissions: read-all
|
||||
|
||||
concurrency:
|
||||
group: detect-new-java-files-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
detectNewJavaFiles:
|
||||
runs-on: ubuntu-latest-low
|
||||
steps:
|
||||
- id: file_changes
|
||||
uses: trilom/file-changes-action@a6ca26c14274c33b15e6499323aac178af06ad4b # v1.2.4
|
||||
with:
|
||||
output: ','
|
||||
- name: Detect new java files
|
||||
run: |
|
||||
if [ -z '${{ steps.file_changes.outputs.files_added }}' ]; then
|
||||
echo "No new files added"
|
||||
exit 0
|
||||
fi
|
||||
new_java=$(echo '${{ steps.file_changes.outputs.files_added }}' | tr ',' '\n' | grep '\.java$' | cat)
|
||||
if [ -n "$new_java" ]; then
|
||||
# shellcheck disable=SC2016
|
||||
printf 'New java files detected:\n```\n%s\n```\n' "$new_java" | tee "$GITHUB_STEP_SUMMARY"
|
||||
exit 1
|
||||
else
|
||||
echo "No new java files detected"
|
||||
exit 0
|
||||
fi
|
||||
@@ -0,0 +1,30 @@
|
||||
# SPDX-FileCopyrightText: 2023-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-FileCopyrightText: 2023 Tobias Kaminsky <[email protected]>
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
|
||||
name: "Detect wrong settings"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [ master, stable-* ]
|
||||
|
||||
# Declare default permissions as read only.
|
||||
permissions: read-all
|
||||
|
||||
concurrency:
|
||||
group: detect-wrong-settings-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
detectWrongSettings:
|
||||
runs-on: ubuntu-24.04
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 21
|
||||
- name: Detect SNAPSHOT
|
||||
run: scripts/analysis/detectWrongSettings.sh
|
||||
@@ -0,0 +1,107 @@
|
||||
# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
name: "Garm"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [ master, stable-* ]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-24.04
|
||||
services:
|
||||
server:
|
||||
image: ${{ matrix.server == 'stable22' && 'ghcr.io/nextcloud/continuous-integration-shallow-server-php8.0:1' || 'ghcr.io/nextcloud/continuous-integration-shallow-server-php8.3:latest' }}
|
||||
options: --name server
|
||||
ports:
|
||||
- 80:80
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
server: [ stable22, stable35, master ]
|
||||
api-level: [ 29 ] # [ 21, 36 ]
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: configure server
|
||||
run: |
|
||||
sudo apt-get update && sudo apt-get install unzip cpu-checker qemu-kvm --yes
|
||||
sudo chmod 666 /dev/kvm
|
||||
docker cp .github/workflows/configServer.sh server:/tmp/
|
||||
docker exec server chmod +x /tmp/configServer.sh
|
||||
docker exec server /tmp/configServer.sh ${{ matrix.server }}
|
||||
docker cp .github/workflows/configNC.sh server:/tmp/
|
||||
docker exec server chmod +x /tmp/configNC.sh
|
||||
docker exec --user www-data server /tmp/configNC.sh ${{ matrix.server }}
|
||||
docker exec server /usr/local/bin/run.sh
|
||||
|
||||
- name: set up JDK 21
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 21
|
||||
|
||||
- name: Enable KVM group perms
|
||||
run: |
|
||||
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
|
||||
sudo udevadm control --reload-rules
|
||||
sudo udevadm trigger --name-match=kvm
|
||||
|
||||
- name: Configure gradle daemon
|
||||
run: |
|
||||
mkdir -p $HOME/.gradle
|
||||
echo "org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g" >> $HOME/.gradle/gradle.properties
|
||||
echo "org.gradle.caching=true" >> $HOME/.gradle/gradle.properties
|
||||
echo "org.gradle.parallel=true" >> $HOME/.gradle/gradle.properties
|
||||
echo "org.gradle.configureondemand=true" >> $HOME/.gradle/gradle.properties
|
||||
|
||||
- name: Config gplay
|
||||
run: |
|
||||
sed -i s#http://server#http://10.0.2.2# gradle.properties
|
||||
sed -i s'#<bool name="is_beta">false</bool>#<bool name="is_beta">true</bool>#'g app/src/main/res/values/setup.xml
|
||||
|
||||
- name: wait and ping server
|
||||
run: |
|
||||
while ! curl http://localhost/status.php 2>&1 | grep installed; do
|
||||
echo "wait…"
|
||||
sleep 5
|
||||
done
|
||||
|
||||
- name: gplay
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GIT_TOKEN }}
|
||||
uses: reactivecircus/android-emulator-runner@a421e43855164a8197daf9d8d40fe71c6996bb0d # v2.38.0
|
||||
with:
|
||||
api-level: ${{ matrix.api-level }}
|
||||
cmake: 4.1.2
|
||||
force-avd-creation: false
|
||||
arch: x86_64
|
||||
sdcard-path-or-size: 100M
|
||||
target: google_apis
|
||||
emulator-options: -no-metrics -no-window -gpu swiftshader_indirect -no-snapshot -noaudio -no-boot-anim -skin 500x833
|
||||
script: scripts/runCombinedTest.sh ${{github.event.number}} ${{ secrets.LOG_USERNAME }} ${{ secrets.LOG_PASSWORD }} ${{github.event.number}} ${{ matrix.server }}
|
||||
|
||||
- name: upload failing results
|
||||
if: ${{ failure() }}
|
||||
env:
|
||||
LOG_USERNAME: ${{ secrets.LOG_USERNAME }}
|
||||
LOG_PASSWORD: ${{ secrets.LOG_PASSWORD }}
|
||||
GIT_USERNAME: ${{ secrets.GIT_USERNAME }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: scripts/uploadReport.sh "${{ secrets.LOG_USERNAME }}" "${{ secrets.LOG_PASSWORD }}" ${{github.event.number}} ${{ matrix.server }} "IT" ${{github.event.number}}
|
||||
- name: Archive Espresso results
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
if: ${{ always() }}
|
||||
with:
|
||||
name: Report-${{ matrix.server }}-${{ matrix.api-level }}
|
||||
path: app/build/reports
|
||||
retention-days: 4
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-FileCopyrightText: 2022 Álvaro Brey <[email protected]>
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
#
|
||||
|
||||
## This file is intended to be sourced by other scripts
|
||||
|
||||
|
||||
function err() {
|
||||
echo >&2 "$@"
|
||||
}
|
||||
|
||||
|
||||
function curl_gh() {
|
||||
if [[ -n "$GITHUB_TOKEN" ]]
|
||||
then
|
||||
curl \
|
||||
--silent \
|
||||
--header "Authorization: token $GITHUB_TOKEN" \
|
||||
"$@"
|
||||
else
|
||||
err "WARNING: No GITHUB_TOKEN found. Skipping API call"
|
||||
fi
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
SPDX-FileCopyrightText: 2019-2025 Nextcloud GmbH and Nextcloud contributors
|
||||
SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
@@ -0,0 +1,39 @@
|
||||
# SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
name: Lint translation files
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [ master, main, stable-* ]
|
||||
push:
|
||||
branches: [ master, main, stable-* ]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: lint-php-cs-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest-low
|
||||
|
||||
name: translations-string-xml
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Check for new lines in translation strings
|
||||
id: counter
|
||||
run: |
|
||||
grep -P '<string name' app/src/main/res/values/strings.xml | grep -vcP '</string>' | grep '^0$'
|
||||
|
||||
- name: Output
|
||||
if: failure()
|
||||
run: |
|
||||
grep -P '<string name' app/src/main/res/values/strings.xml | grep -vP '</string>'
|
||||
@@ -0,0 +1,55 @@
|
||||
# This workflow is provided via the organization template repository
|
||||
#
|
||||
# https://github.com/nextcloud/.github
|
||||
# https://docs.github.com/en/actions/learn-github-actions/sharing-workflows-with-your-organization
|
||||
|
||||
# SPDX-FileCopyrightText: 2023-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-FileCopyrightText: 2023 Marcel Klehr <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2023 Joas Schilling <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2023 Daniel Kesselberg <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2023 Florian Steffens <[email protected]>
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
name: 'Ask for feedback on PRs'
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 1 * * *'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
pr-feedback:
|
||||
if: ${{ github.repository_owner == 'nextcloud' }}
|
||||
runs-on: ubuntu-latest-low
|
||||
steps:
|
||||
- name: The get-github-handles-from-website action
|
||||
uses: marcelklehr/get-github-handles-from-website-action@06b2239db0a48fe1484ba0bfd966a3ab81a08308 # v1.0.1
|
||||
id: scrape
|
||||
with:
|
||||
website: 'https://nextcloud.com/team/'
|
||||
|
||||
- name: Get blocklist
|
||||
id: blocklist
|
||||
run: |
|
||||
blocklist=$(curl https://raw.githubusercontent.com/nextcloud/.github/master/non-community-usernames.txt | paste -s -d, -)
|
||||
echo "blocklist=$blocklist" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: nextcloud/pr-feedback-action@4709fa5b3e1821559d4c312ef937b61f1567aa44 # main
|
||||
with:
|
||||
feedback-message: |
|
||||
Hello there,
|
||||
Thank you so much for taking the time and effort to create a pull request to our Nextcloud project.
|
||||
|
||||
We hope that the review process is going smooth and is helpful for you. We want to ensure your pull request is reviewed to your satisfaction. If you have a moment, our community management team would very much appreciate your feedback on your experience with this PR review process.
|
||||
|
||||
Your feedback is valuable to us as we continuously strive to improve our community developer experience. Please take a moment to complete our short survey by clicking on the following link: https://cloud.nextcloud.com/apps/forms/s/i9Ago4EQRZ7TWxjfmeEpPkf6
|
||||
|
||||
Thank you for contributing to Nextcloud and we hope to hear from you soon!
|
||||
|
||||
(If you believe you should not receive this message, you can add yourself to the [blocklist](https://github.com/nextcloud/.github/blob/master/non-community-usernames.txt).)
|
||||
days-before-feedback: 14
|
||||
start-date: '2024-04-30'
|
||||
exempt-authors: '${{ steps.blocklist.outputs.blocklist }},${{ steps.scrape.outputs.users }}'
|
||||
exempt-bots: true
|
||||
@@ -0,0 +1,116 @@
|
||||
# SPDX-FileCopyrightText: 2021-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-FileCopyrightText: 2023 Andy Scherzinger <[email protected]>
|
||||
# SPDX-License-Identifier: MIT
|
||||
name: "QA"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [ main, master, stable-* ]
|
||||
|
||||
permissions:
|
||||
pull-requests: write
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: qa-build-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
qa:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check if secrets are available
|
||||
run: echo "ok=${{ secrets.KS_PASS != '' }}" >> "$GITHUB_OUTPUT"
|
||||
id: check-secrets
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: set up JDK 21
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 21
|
||||
|
||||
- name: Build QA
|
||||
id: build-qa
|
||||
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
|
||||
env:
|
||||
KS_PASS: ${{ secrets.KS_PASS }}
|
||||
KEY_PASS: ${{ secrets.KEY_PASS }}
|
||||
LOG_USERNAME: ${{ secrets.LOG_USERNAME }}
|
||||
LOG_PASSWORD: ${{ secrets.LOG_PASSWORD }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
mkdir -p "$HOME/.gradle"
|
||||
{
|
||||
echo "org.gradle.jvmargs=-Xmx3g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g"
|
||||
echo "org.gradle.caching=true"
|
||||
echo "org.gradle.parallel=true"
|
||||
echo "org.gradle.configureondemand=true"
|
||||
} > "$HOME/.gradle/gradle.properties"
|
||||
[ -e app/build.gradle ] && sed -i "/qa/,/\}/ s/versionCode .*/versionCode ${{github.event.number}} /" "app/build.gradle"
|
||||
[ -e app/build.gradle ] && sed -i "/qa/,/\}/ s/versionName .*/versionName \"${{github.event.number}}\"/" "app/build.gradle"
|
||||
[ -e app/build.gradle.kts ] && sed -i "/qa/,/\}/ s/versionCode .*/versionCode = ${{github.event.number}} /" "app/build.gradle.kts"
|
||||
[ -e app/build.gradle.kts ] && sed -i "/qa/,/\}/ s/versionName .*/versionName = \"${{github.event.number}}\"/" "app/build.gradle.kts"
|
||||
./gradlew assembleQaDebug
|
||||
$(find /usr/local/lib/android/sdk/build-tools/*/apksigner | sort | tail -n1) sign --ks-pass pass:"$KS_PASS" --key-pass pass:"$KEY_PASS" --ks-key-alias key0 --ks ".github/workflows/QA_keystore.jks" app/build/outputs/apk/qa/debug/*qa-debug*.apk
|
||||
apk=$(find app/build/outputs/apk/qa/debug -name '*qa-debug*.apk' | head -n1)
|
||||
echo "apk-path=$apk" >> "$GITHUB_OUTPUT"
|
||||
echo "apk-name=$(basename "$apk")" >> "$GITHUB_OUTPUT"
|
||||
echo "apk-size=$(du -h "$apk" | cut -f1)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Upload APK
|
||||
id: upload-apk
|
||||
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
|
||||
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f
|
||||
with:
|
||||
path: ${{ steps.build-qa.outputs.apk-path }}
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
archive: false
|
||||
|
||||
- name: Create QR code
|
||||
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
|
||||
env:
|
||||
ARTIFACT_URL: ${{ steps.upload-apk.outputs.artifact-url }}
|
||||
run: |
|
||||
sudo apt-get -y install qrencode
|
||||
qrencode -s 8 -o qr.png "$ARTIFACT_URL"
|
||||
|
||||
- name: Upload QR code
|
||||
id: upload-qr
|
||||
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
|
||||
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f
|
||||
with:
|
||||
path: qr.png
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
archive: false
|
||||
|
||||
- name: Comment PR
|
||||
if: ${{ steps.check-secrets.outputs.ok == 'true' }}
|
||||
uses: thollander/actions-comment-pull-request@e4a76dd2b0a3c2027c3fd84147a67c22ee4c90fa
|
||||
with:
|
||||
comment-tag: qa-apk
|
||||
mode: upsert
|
||||
message: |
|
||||
### :iphone: QA build
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Download** | [${{ steps.build-qa.outputs.apk-name }}](${{ steps.upload-apk.outputs.artifact-url }}) |
|
||||
| **QR code** | [Open the QR code for this download](${{ steps.upload-qr.outputs.artifact-url }}) |
|
||||
| **Commit** | ${{ github.event.pull_request.head.sha }} |
|
||||
| **Version** | `${{ github.event.number }}` |
|
||||
| **Available until** | 7 days after this build |
|
||||
|
||||
The QA build installs alongside a released Nextcloud app, so you can keep
|
||||
using your existing install while testing.
|
||||
|
||||
Downloading the file requires a GitHub account, so open this link on the
|
||||
device you want to test on, or transfer the APK to it.
|
||||
@@ -0,0 +1,61 @@
|
||||
# This workflow is provided via the organization template repository
|
||||
#
|
||||
# https://github.com/nextcloud/.github
|
||||
# https://docs.github.com/en/actions/learn-github-actions/sharing-workflows-with-your-organization
|
||||
#
|
||||
# SPDX-FileCopyrightText: Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
name: Auto approve renovate PRs
|
||||
|
||||
on:
|
||||
pull_request_target: # zizmor: ignore[dangerous-triggers]
|
||||
branches:
|
||||
- main
|
||||
- master
|
||||
- stable*
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: renovate-approve-merge-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
auto-approve-merge:
|
||||
if: github.event.pull_request.user.login == 'renovate[bot]'
|
||||
runs-on: ubuntu-latest-low
|
||||
permissions:
|
||||
# for hmarr/auto-approve-action to approve PRs
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- name: Disabled on forks
|
||||
if: ${{ github.event.pull_request.head.repo.full_name != github.repository }}
|
||||
run: |
|
||||
echo 'Can not approve PRs from forks'
|
||||
exit 1
|
||||
|
||||
- uses: mdecoleman/pr-branch-name@55795d86b4566d300d237883103f052125cc7508 # v3.0.0
|
||||
id: branchname
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# GitHub actions bot approve
|
||||
- uses: hmarr/auto-approve-action@f0939ea97e9205ef24d872e76833fa908a770363 # v4.0.0
|
||||
if: github.actor == 'renovate[bot]'
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.head_ref }}
|
||||
|
||||
# Enable GitHub auto merge
|
||||
- name: Enable Pull Request Automerge
|
||||
if: github.actor == 'renovate[bot]'
|
||||
run: gh pr merge --merge --auto
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.AUTOMERGE }}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# This workflow is provided via the organization template repository
|
||||
#
|
||||
# https://github.com/nextcloud/.github
|
||||
# https://docs.github.com/en/actions/learn-github-actions/sharing-workflows-with-your-organization
|
||||
|
||||
# SPDX-FileCopyrightText: 2022 Free Software Foundation Europe e.V. <https://fsfe.org>
|
||||
#
|
||||
# SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
name: REUSE Compliance Check
|
||||
|
||||
on: [pull_request]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
reuse-compliance-check:
|
||||
runs-on: ubuntu-latest-low
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: REUSE Compliance Check
|
||||
uses: fsfe/reuse-action@676e2d560c9a403aa252096d99fcab3e1132b0f5 # v6.0.0
|
||||
@@ -0,0 +1,47 @@
|
||||
# synced from @nextcloud/android-config
|
||||
|
||||
# SPDX-FileCopyrightText: 2023-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-FileCopyrightText: 2023 Andy Scherzinger <[email protected]>
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
name: Scorecard supply-chain security
|
||||
on:
|
||||
branch_protection_rule:
|
||||
schedule:
|
||||
- cron: '32 23 * * 4'
|
||||
push:
|
||||
branches: [ "main", "master" ]
|
||||
|
||||
# Declare default permissions as read only.
|
||||
permissions: read-all
|
||||
|
||||
concurrency:
|
||||
group: scorecard-supply-chain-security-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
analysis:
|
||||
name: Scorecard analysis
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
# Needed to upload the results to code-scanning dashboard.
|
||||
security-events: write
|
||||
|
||||
steps:
|
||||
- name: "Checkout code"
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: "Run analysis"
|
||||
uses: ossf/scorecard-action@2d1146689b8cda280b9bc96326124645441f03bc # v2.4.4
|
||||
with:
|
||||
results_file: results.sarif
|
||||
results_format: sarif
|
||||
publish_results: false
|
||||
|
||||
# Upload the results to GitHub's code scanning dashboard.
|
||||
- name: "Upload to code-scanning"
|
||||
uses: github/codeql-action/upload-sarif@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
|
||||
with:
|
||||
sarif_file: results.sarif
|
||||
@@ -0,0 +1,35 @@
|
||||
# synced from @nextcloud/android-config
|
||||
|
||||
# SPDX-FileCopyrightText: 2023-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-FileCopyrightText: 2023 Tobias Kaminsky <[email protected]>
|
||||
# SPDX-FileCopyrightText: 2022 Álvaro Brey <[email protected]>
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
name: 'Close stale issues'
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 0 * * *'
|
||||
|
||||
# Declare default permissions as read only.
|
||||
permissions: read-all
|
||||
|
||||
jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-latest-low
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0
|
||||
with:
|
||||
days-before-stale: 28
|
||||
days-before-close: 14
|
||||
days-before-pr-close: -1
|
||||
only-labels: 'bug,needs info'
|
||||
exempt-issue-labels: 'no-stale'
|
||||
stale-issue-message: >-
|
||||
This bug report did not receive an update in the last 4 weeks.
|
||||
Please take a look again and update the issue with new details,
|
||||
otherwise the issue will be automatically closed in 2 weeks. Thank you!
|
||||
exempt-all-pr-milestones: true
|
||||
labels-to-remove-when-unstale: 'needs info'
|
||||
@@ -0,0 +1,64 @@
|
||||
# SPDX-FileCopyrightText: 2022-2025 Nextcloud GmbH and contributors
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
|
||||
name: Unit tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [ master, stable-* ]
|
||||
push:
|
||||
branches: [ master, stable-* ]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
group: unit-tests-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 21
|
||||
|
||||
- name: Delete old comments
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
if: ${{ always() }}
|
||||
run: scripts/deleteOldComments.sh "test" "Unit" ${{github.event.number}}
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
|
||||
|
||||
- name: Run unit tests with coverage
|
||||
run: ./gradlew jacocoTestGplayDebugUnitTest
|
||||
|
||||
- name: Upload failing results
|
||||
if: ${{ failure() }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: scripts/uploadReport.sh "${{ secrets.LOG_USERNAME }}" "${{ secrets.LOG_PASSWORD }}" ${{github.event.number}} "test" "Unit" ${{github.event.number}}
|
||||
|
||||
- name: Upload coverage to codecov
|
||||
uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
flags: unit
|
||||
fail_ci_if_error: true
|
||||
files: app/build/reports/jacoco/jacocoTestGplayDebugUnitTestReport/jacoco.xml
|
||||
|
||||
- name: Upload jacoco artifacts
|
||||
if: ${{ failure() }}
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: test-results
|
||||
path: app/build/reports/jacoco/jacocoTestGplayDebugUnitTestReport/html/
|
||||
Executable
+44
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
#
|
||||
# SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
|
||||
# SPDX-FileCopyrightText: 2019-2022 Tobias Kaminsky <[email protected]>
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
#
|
||||
|
||||
#1: LOG_USERNAME
|
||||
#2: LOG_PASSWORD
|
||||
#3: DRONE_BUILD_NUMBER
|
||||
#4: DRONE_PULL_REQUEST
|
||||
|
||||
|
||||
PUBLIC_URL=https://www.kaminsky.me/nc-dev/android-artifacts
|
||||
USER=$1
|
||||
PASS=$2
|
||||
BUILD=$3
|
||||
PR=$4
|
||||
GITHUB_TOKEN=$5
|
||||
DAV_URL=https://nextcloud.kaminsky.me/remote.php/dav/files/$USER/android-artifacts/
|
||||
|
||||
source .github/workflows/lib.sh
|
||||
REPO=$(cat scripts/repo)
|
||||
|
||||
if ! test -e app/build/outputs/apk/qa/debug/*qa-debug*.apk ; then
|
||||
exit 1
|
||||
fi
|
||||
echo "Uploaded artifact to $DAV_URL/$BUILD.apk"
|
||||
|
||||
# delete all old comments, starting with "APK file:"
|
||||
oldComments=$(curl_gh -X GET https://api.github.com/repos/nextcloud/$REPO/issues/$PR/comments | jq '.[] | (.id |tostring) + "|" + (.user.login | test("github-actions") | tostring) + "|" + (.body | test("APK file:.*") | tostring)' | grep "true|true" | tr -d "\"" | cut -f1 -d"|")
|
||||
|
||||
echo $oldComments | while read comment ; do
|
||||
curl_gh -X DELETE https://api.github.com/repos/nextcloud/$REPO/issues/comments/$comment
|
||||
done
|
||||
|
||||
sudo apt-get -y install qrencode
|
||||
|
||||
qrencode -o $PR.png "$PUBLIC_URL/$BUILD.apk"
|
||||
|
||||
curl -u $USER:$PASS -X PUT $DAV_URL/$BUILD.apk --upload-file app/build/outputs/apk/qa/debug/*qa-debug*.apk
|
||||
curl -u $USER:$PASS -X PUT $DAV_URL/$BUILD.png --upload-file $PR.png
|
||||
curl_gh -X POST https://api.github.com/repos/nextcloud/$REPO/issues/$PR/comments -d "{ \"body\" : \"APK file: $PUBLIC_URL/$BUILD.apk <br/><br/>  <br/><br/>To test this change/fix you can simply download above APK file and install and test it in parallel to your existing Nextcloud app. \" }"
|
||||
+25
-24
@@ -8,8 +8,8 @@ GEM
|
||||
artifactory (3.0.17)
|
||||
atomos (0.1.3)
|
||||
aws-eventstream (1.4.0)
|
||||
aws-partitions (1.1281.0)
|
||||
aws-sdk-core (3.254.1)
|
||||
aws-partitions (1.1287.0)
|
||||
aws-sdk-core (3.257.0)
|
||||
aws-eventstream (~> 1, >= 1.3.0)
|
||||
aws-partitions (~> 1, >= 1.992.0)
|
||||
aws-sigv4 (~> 1.9)
|
||||
@@ -17,11 +17,12 @@ GEM
|
||||
bigdecimal
|
||||
jmespath (~> 1, >= 1.6.1)
|
||||
logger
|
||||
aws-sdk-kms (1.130.0)
|
||||
aws-sdk-core (~> 3, >= 3.254.0)
|
||||
rexml (~> 3.4, >= 3.4.2)
|
||||
aws-sdk-kms (1.132.0)
|
||||
aws-sdk-core (~> 3, >= 3.256.0)
|
||||
aws-sigv4 (~> 1.5)
|
||||
aws-sdk-s3 (1.229.0)
|
||||
aws-sdk-core (~> 3, >= 3.254.1)
|
||||
aws-sdk-s3 (1.232.0)
|
||||
aws-sdk-core (~> 3, >= 3.256.0)
|
||||
aws-sdk-kms (~> 1)
|
||||
aws-sigv4 (~> 1.5)
|
||||
aws-sigv4 (1.12.1)
|
||||
@@ -40,12 +41,12 @@ GEM
|
||||
declarative (0.0.20)
|
||||
digest-crc (0.7.0)
|
||||
rake (>= 12.0.0, < 14.0.0)
|
||||
domain_name (0.6.20240107)
|
||||
domain_name (0.6.20260907)
|
||||
dotenv (2.8.1)
|
||||
emoji_regex (3.2.3)
|
||||
erb (6.0.7)
|
||||
excon (0.112.0)
|
||||
faraday (2.14.3)
|
||||
faraday (2.14.4)
|
||||
faraday-net_http (>= 2.0, < 3.5)
|
||||
json
|
||||
logger
|
||||
@@ -60,7 +61,7 @@ GEM
|
||||
faraday-retry (2.4.0)
|
||||
faraday (~> 2.0)
|
||||
fastimage (2.4.1)
|
||||
fastlane (2.238.0)
|
||||
fastlane (2.240.1)
|
||||
CFPropertyList (>= 2.3, < 5.0.0)
|
||||
abbrev (~> 0.1)
|
||||
addressable (>= 2.9.0, < 3.0.0)
|
||||
@@ -70,6 +71,7 @@ GEM
|
||||
base64 (~> 0.2)
|
||||
benchmark (>= 0.1.0)
|
||||
bundler (>= 2.4.0, < 5.0.0)
|
||||
cgi (~> 0.4)
|
||||
colored (~> 1.2)
|
||||
commander (~> 4.6)
|
||||
csv (~> 3.3)
|
||||
@@ -84,12 +86,11 @@ GEM
|
||||
fastimage (>= 2.1.0, < 3.0.0)
|
||||
fastlane-sirp (>= 1.1.0)
|
||||
gh_inspector (>= 1.1.2, < 2.0.0)
|
||||
google-apis-androidpublisher_v3 (~> 0.3)
|
||||
google-apis-androidpublisher_v3 (~> 0.99)
|
||||
google-apis-playcustomapp_v1 (~> 0.1)
|
||||
google-cloud-env (>= 1.6.0, < 2.3.0)
|
||||
google-cloud-env (>= 1.6.0, < 2.4.0)
|
||||
google-cloud-storage (~> 1.31)
|
||||
highline (~> 2.0)
|
||||
http-cookie (~> 1.0.5)
|
||||
irb (>= 1.8)
|
||||
json (< 3.0.0)
|
||||
jwt (>= 2.10.3, < 4)
|
||||
@@ -103,8 +104,8 @@ GEM
|
||||
optparse (>= 0.1.1, < 1.0.0)
|
||||
ostruct (>= 0.1.0)
|
||||
plist (>= 3.1.0, < 4.0.0)
|
||||
rubyzip (>= 2.0.0, < 3.0.0)
|
||||
security (= 0.1.5)
|
||||
rubyzip (>= 3.4.0, < 4.0.0)
|
||||
security (~> 0.3)
|
||||
simctl (~> 1.6.3)
|
||||
terminal-notifier (>= 2.0.0, < 3.0.0)
|
||||
terminal-table (~> 4)
|
||||
@@ -118,7 +119,7 @@ GEM
|
||||
cgi
|
||||
fastlane-sirp (1.1.0)
|
||||
gh_inspector (1.1.3)
|
||||
google-apis-androidpublisher_v3 (0.106.0)
|
||||
google-apis-androidpublisher_v3 (0.108.0)
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-apis-core (0.18.0)
|
||||
addressable (~> 2.5, >= 2.5.1)
|
||||
@@ -132,12 +133,12 @@ GEM
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-apis-playcustomapp_v1 (0.18.0)
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-apis-storage_v1 (0.66.0)
|
||||
google-apis-storage_v1 (0.67.0)
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-cloud-core (1.9.0)
|
||||
google-cloud-env (>= 1.0, < 3.a)
|
||||
google-cloud-errors (~> 1.0)
|
||||
google-cloud-env (2.2.2)
|
||||
google-cloud-env (2.3.1)
|
||||
base64 (~> 0.2)
|
||||
faraday (>= 1.0, < 3.a)
|
||||
google-cloud-errors (1.7.0)
|
||||
@@ -151,7 +152,7 @@ GEM
|
||||
googleauth (~> 1.9)
|
||||
mini_mime (~> 1.0)
|
||||
google-logging-utils (0.2.0)
|
||||
googleauth (1.17.3)
|
||||
googleauth (1.17.4)
|
||||
faraday (>= 1.0, < 3.a)
|
||||
google-cloud-env (~> 2.2)
|
||||
google-logging-utils (~> 0.1)
|
||||
@@ -160,11 +161,11 @@ GEM
|
||||
pstore (~> 0.1)
|
||||
signet (>= 0.16, < 2.a)
|
||||
highline (2.0.3)
|
||||
http-cookie (1.0.8)
|
||||
http-cookie (1.1.6)
|
||||
domain_name (~> 0.5)
|
||||
httpclient (2.9.0)
|
||||
mutex_m
|
||||
io-console (0.9.2)
|
||||
io-console (0.9.3)
|
||||
irb (1.18.0)
|
||||
pp (>= 0.6.0)
|
||||
prism (>= 1.3.0)
|
||||
@@ -177,7 +178,7 @@ GEM
|
||||
logger (1.7.0)
|
||||
mini_magick (4.13.2)
|
||||
mini_mime (1.1.5)
|
||||
multi_json (1.21.1)
|
||||
multi_json (1.21.2)
|
||||
multipart-post (2.4.1)
|
||||
mutex_m (0.3.0)
|
||||
nanaimo (0.4.0)
|
||||
@@ -194,7 +195,7 @@ GEM
|
||||
pstore (0.2.1)
|
||||
public_suffix (6.0.2)
|
||||
rake (13.4.2)
|
||||
rbs (4.1.3)
|
||||
rbs (4.2.0)
|
||||
logger
|
||||
prism (>= 1.6.0)
|
||||
tsort
|
||||
@@ -212,8 +213,8 @@ GEM
|
||||
retriable (3.8.0)
|
||||
rexml (3.4.4)
|
||||
rouge (3.28.0)
|
||||
rubyzip (2.4.1)
|
||||
security (0.1.5)
|
||||
rubyzip (3.6.0)
|
||||
security (0.3.0)
|
||||
signet (0.22.0)
|
||||
addressable (~> 2.8)
|
||||
faraday (>= 0.17.5, < 3.a)
|
||||
|
||||
@@ -70,7 +70,7 @@ configurations.configureEach {
|
||||
|
||||
// semantic versioning for version code
|
||||
val versionMajor = 35
|
||||
val versionMinor = 0
|
||||
val versionMinor = 1
|
||||
val versionPatch = 0
|
||||
val versionBuild = 50 // 0-50=Alpha / 51-98=RC / 90-99=stable
|
||||
|
||||
@@ -118,7 +118,7 @@ android {
|
||||
compileSdk = 37
|
||||
|
||||
ndk {
|
||||
abiFilters += listOf("arm64-v8a", "x86_64")
|
||||
abiFilters += listOf("armeabi-v7a", "arm64-v8a", "x86", "x86_64")
|
||||
}
|
||||
|
||||
buildConfigField("boolean", "CI", ciBuild.toString())
|
||||
@@ -526,6 +526,7 @@ dependencies {
|
||||
|
||||
// region Kotlin
|
||||
implementation(libs.kotlin.stdlib)
|
||||
implementation(libs.kotlinx.coroutines.core)
|
||||
// endregion
|
||||
|
||||
// region Stateless
|
||||
|
||||
@@ -76,6 +76,11 @@
|
||||
<ignore path="build" />
|
||||
</issue>
|
||||
|
||||
<!-- Dagger factories generated for media3 @UnstableApi types cannot carry an @OptIn annotation. -->
|
||||
<issue id="UnsafeOptInUsageError" severity="error">
|
||||
<ignore path="build" />
|
||||
</issue>
|
||||
|
||||
<issue id="ObsoleteLintCustomCheck" severity="warning">
|
||||
<ignore path="**/fragment-1.2.5/**/lint.jar" />
|
||||
<ignore path="**/work-runtime-2.**/**/lint.jar" />
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -8,6 +8,7 @@
|
||||
package com.nextcloud.client.assistant
|
||||
|
||||
import com.nextcloud.client.assistant.repository.remote.AssistantRemoteRepositoryImpl
|
||||
import com.nextcloud.test.SinceServer
|
||||
import com.owncloud.android.AbstractOnServerIT
|
||||
import com.owncloud.android.lib.resources.assistant.v2.model.TaskTypeData
|
||||
import com.owncloud.android.lib.resources.status.NextcloudVersion
|
||||
@@ -17,6 +18,7 @@ import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
@Suppress("MagicNumber")
|
||||
@SinceServer(majorVersion = 28)
|
||||
class AssistantRepositoryTests : AbstractOnServerIT() {
|
||||
|
||||
private var sut: AssistantRemoteRepositoryImpl? = null
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.nextcloud.test
|
||||
|
||||
import org.junit.runner.Description
|
||||
import org.junit.runner.manipulation.Filter
|
||||
|
||||
class FlakyTestFilter : Filter() {
|
||||
override fun shouldRun(description: Description): Boolean = when {
|
||||
description.isTest -> !description.isFlaky()
|
||||
else -> description.children.any { shouldRun(it) }
|
||||
}
|
||||
|
||||
override fun describe(): String = "skip tests annotated with @Flaky"
|
||||
|
||||
private fun Description.isFlaky(): Boolean {
|
||||
val onMethod = getAnnotation(Flaky::class.java) != null
|
||||
val onClass = testClass?.isAnnotationPresent(Flaky::class.java) == true
|
||||
return onMethod || onClass
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.nextcloud.test
|
||||
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.runner.Description
|
||||
import org.junit.runner.manipulation.Filter
|
||||
|
||||
class ServerVersionFilter : Filter() {
|
||||
|
||||
private val serverVersion: Int? by lazy {
|
||||
InstrumentationRegistry
|
||||
.getArguments()
|
||||
.getString(SERVER_VERSION_ARGUMENT)
|
||||
?.toIntOrNull()
|
||||
}
|
||||
|
||||
override fun shouldRun(description: Description): Boolean {
|
||||
val currentVersion = serverVersion ?: return true
|
||||
|
||||
return when {
|
||||
description.isTest -> description.requiredServerVersion() <= currentVersion
|
||||
else -> description.children.any { shouldRun(it) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun describe(): String = "skip tests annotated with @SinceServer above server version $serverVersion"
|
||||
|
||||
private fun Description.requiredServerVersion(): Int {
|
||||
val onMethod = getAnnotation(SinceServer::class.java)?.majorVersion ?: ANY_SERVER
|
||||
val onClass = testClass?.getAnnotation(SinceServer::class.java)?.majorVersion ?: ANY_SERVER
|
||||
return maxOf(onMethod, onClass)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val SERVER_VERSION_ARGUMENT = "TEST_SERVER_VERSION"
|
||||
private const val ANY_SERVER = 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.nextcloud.test
|
||||
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
|
||||
annotation class SinceServer(val majorVersion: Int)
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
package com.nextcloud.utils
|
||||
|
||||
import com.nextcloud.test.SinceServer
|
||||
import com.nextcloud.utils.autoRename.AutoRename
|
||||
import com.owncloud.android.AbstractOnServerIT
|
||||
import com.owncloud.android.datamodel.e2e.v2.decrypted.DecryptedFile
|
||||
@@ -18,6 +19,7 @@ import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
@Suppress("TooManyFunctions")
|
||||
@SinceServer(majorVersion = 30)
|
||||
class AutoRenameTests : AbstractOnServerIT() {
|
||||
|
||||
private var capability: OCCapability = fileDataStorageManager.getCapability(account.name)
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
package com.nextcloud.utils
|
||||
|
||||
import com.nextcloud.test.SinceServer
|
||||
import com.nextcloud.utils.fileNameValidator.FileNameValidator
|
||||
import com.owncloud.android.AbstractOnServerIT
|
||||
import com.owncloud.android.R
|
||||
@@ -42,6 +43,7 @@ class FileNameValidatorTests : AbstractOnServerIT() {
|
||||
}
|
||||
|
||||
@Test
|
||||
@SinceServer(majorVersion = 30)
|
||||
fun testInvalidCharacter() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_30)
|
||||
|
||||
@@ -53,6 +55,7 @@ class FileNameValidatorTests : AbstractOnServerIT() {
|
||||
}
|
||||
|
||||
@Test
|
||||
@SinceServer(majorVersion = 30)
|
||||
fun testReservedName() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_30)
|
||||
|
||||
@@ -61,6 +64,7 @@ class FileNameValidatorTests : AbstractOnServerIT() {
|
||||
}
|
||||
|
||||
@Test
|
||||
@SinceServer(majorVersion = 30)
|
||||
fun testForbiddenFilenameExtension() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_30)
|
||||
|
||||
@@ -141,6 +145,7 @@ class FileNameValidatorTests : AbstractOnServerIT() {
|
||||
}
|
||||
|
||||
@Test
|
||||
@SinceServer(majorVersion = 30)
|
||||
fun testFolderPathWithReservedName() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_30)
|
||||
|
||||
@@ -152,6 +157,7 @@ class FileNameValidatorTests : AbstractOnServerIT() {
|
||||
}
|
||||
|
||||
@Test
|
||||
@SinceServer(majorVersion = 30)
|
||||
fun testFilePathWithReservedName() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_30)
|
||||
|
||||
@@ -163,6 +169,7 @@ class FileNameValidatorTests : AbstractOnServerIT() {
|
||||
}
|
||||
|
||||
@Test
|
||||
@SinceServer(majorVersion = 30)
|
||||
fun testFolderPathWithInvalidCharacter() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_30)
|
||||
|
||||
@@ -174,6 +181,7 @@ class FileNameValidatorTests : AbstractOnServerIT() {
|
||||
}
|
||||
|
||||
@Test
|
||||
@SinceServer(majorVersion = 30)
|
||||
fun testFilePathWithInvalidCharacter() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_30)
|
||||
|
||||
@@ -203,6 +211,7 @@ class FileNameValidatorTests : AbstractOnServerIT() {
|
||||
}
|
||||
|
||||
@Test
|
||||
@SinceServer(majorVersion = 30)
|
||||
fun testFilePathWithNestedFolder() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_30)
|
||||
|
||||
@@ -222,6 +231,7 @@ class FileNameValidatorTests : AbstractOnServerIT() {
|
||||
}
|
||||
|
||||
@Test
|
||||
@SinceServer(majorVersion = 30)
|
||||
fun testOnlyFolderPathWithOneReservedName() {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_30)
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.utils
|
||||
|
||||
import com.nextcloud.client.device.BatteryStatus
|
||||
import com.nextcloud.client.device.PowerManagementService
|
||||
|
||||
object PowerManagementFactory {
|
||||
@JvmStatic
|
||||
val mock: PowerManagementService = object : PowerManagementService {
|
||||
override val isIgnoringOptimization: Boolean
|
||||
get() = true
|
||||
override val isPowerSavingEnabled: Boolean
|
||||
get() = false
|
||||
override val battery: BatteryStatus
|
||||
get() = BatteryStatus(false, 0)
|
||||
override val blocksAutoUpload: Boolean
|
||||
get() = false
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
@Suppress("MagicNumber")
|
||||
val mockCharging: PowerManagementService = object : PowerManagementService {
|
||||
override val isIgnoringOptimization: Boolean
|
||||
get() = true
|
||||
override val isPowerSavingEnabled: Boolean
|
||||
get() = false
|
||||
override val battery: BatteryStatus
|
||||
get() = BatteryStatus(true, 100)
|
||||
override val blocksAutoUpload: Boolean
|
||||
get() = false
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
package com.nextcloud.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.text.format.DateUtils
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.nextcloud.client.database.entity.UploadEntity
|
||||
@@ -16,11 +17,14 @@ import com.nextcloud.client.database.entity.toOCUpload
|
||||
import com.nextcloud.client.database.entity.toUploadEntity
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.utils.DisplayUtils
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import java.text.DateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
class UploadDateTests {
|
||||
|
||||
@@ -30,17 +34,32 @@ class UploadDateTests {
|
||||
private const val ONE_HOUR = 60 * ONE_MINUTE
|
||||
private const val ONE_DAY = 24 * ONE_HOUR
|
||||
|
||||
private const val ONE_YEAR = 365L * ONE_DAY
|
||||
private const val ONE_MONTH = 30L * ONE_DAY
|
||||
private const val ONE_WEEK = 7L * ONE_DAY
|
||||
private const val TWO_HOURS = 2L * ONE_HOUR
|
||||
private const val ONE_AND_A_HALF_MINUTES = ONE_MINUTE + THIRTY_SECONDS
|
||||
private const val TWO_AND_A_HALF_HOURS = 2 * ONE_HOUR + ONE_HOUR / 2
|
||||
private const val TWO_DAYS = 2 * ONE_DAY
|
||||
private const val ONE_WEEK = 7 * ONE_DAY
|
||||
private const val ONE_MONTH = 30 * ONE_DAY
|
||||
private const val ONE_YEAR = 365 * ONE_DAY
|
||||
|
||||
private const val DATE_AND_TIME_PARTS = 2
|
||||
private const val TIME_OF_DAY_SEPARATOR = ":"
|
||||
private const val NARROW_NO_BREAK_SPACE = ' '
|
||||
private const val NO_BREAK_SPACE = ' '
|
||||
}
|
||||
|
||||
private lateinit var context: Context
|
||||
private lateinit var systemLocale: Locale
|
||||
|
||||
@Before
|
||||
fun setup() {
|
||||
context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
systemLocale = Locale.getDefault()
|
||||
Locale.setDefault(Locale.US)
|
||||
context = InstrumentationRegistry.getInstrumentation().targetContext.localized(Locale.US)
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
Locale.setDefault(systemLocale)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -82,189 +101,139 @@ class UploadDateTests {
|
||||
|
||||
@Test
|
||||
fun getRelativeDateTimeStringReturnsSecondsAgoForRecentPast() {
|
||||
val result = DisplayUtils.getRelativeDateTimeString(
|
||||
context,
|
||||
System.currentTimeMillis() - THIRTY_SECONDS,
|
||||
DateUtils.MINUTE_IN_MILLIS,
|
||||
DateUtils.WEEK_IN_MILLIS,
|
||||
0
|
||||
assertRelativeDateTimeString(
|
||||
time = System.currentTimeMillis() - THIRTY_SECONDS,
|
||||
expected = context.getString(R.string.file_list_seconds_ago)
|
||||
)
|
||||
assertEquals(context.getString(R.string.file_list_seconds_ago), result.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getRelativeDateTimeStringReturnsFutureAsAbsoluteWhenShowFutureIsFalse() {
|
||||
val time = System.currentTimeMillis() + ONE_MINUTE
|
||||
val expected = java.text.DateFormat.getDateTimeInstance().format(Date(time))
|
||||
val time = System.currentTimeMillis() + ONE_AND_A_HALF_MINUTES
|
||||
|
||||
val result = DisplayUtils.getRelativeDateTimeString(
|
||||
context,
|
||||
time,
|
||||
DateUtils.SECOND_IN_MILLIS,
|
||||
DateUtils.WEEK_IN_MILLIS,
|
||||
0,
|
||||
false
|
||||
assertRelativeDateTimeString(
|
||||
time = time,
|
||||
expected = DateFormat.getDateTimeInstance().format(Date(time))
|
||||
)
|
||||
assertEquals(expected, result.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getRelativeDateTimeStringReturnsFutureAsRelativeWhenShowFutureIsTrue() {
|
||||
val expected = "In 1 minute"
|
||||
val time = System.currentTimeMillis() + ONE_MINUTE
|
||||
|
||||
assertRelativeDateTimeString(time, expected, DateUtils.MINUTE_IN_MILLIS, showFuture = true)
|
||||
assertRelativeDateTimeString(
|
||||
time = System.currentTimeMillis() + ONE_AND_A_HALF_MINUTES,
|
||||
expected = "In 1 minute",
|
||||
showFuture = true
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getRelativeDateTimeStringReturnsRelativeStringForHoursAgo() {
|
||||
val expected = "2 hours ago"
|
||||
val time = System.currentTimeMillis() - TWO_HOURS
|
||||
|
||||
assertRelativeDateTimeString(time, expected, DateUtils.SECOND_IN_MILLIS)
|
||||
assertRelativeDateTimeString(
|
||||
time = System.currentTimeMillis() - TWO_AND_A_HALF_HOURS,
|
||||
expected = "2 hours ago",
|
||||
minResolution = DateUtils.SECOND_IN_MILLIS
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getRelativeDateTimeStringReturnsAbbreviatedStringForOneWeekAgo() {
|
||||
val time = System.currentTimeMillis() - ONE_WEEK
|
||||
val expectedString = DateUtils.getRelativeDateTimeString(
|
||||
context,
|
||||
time,
|
||||
DateUtils.MINUTE_IN_MILLIS,
|
||||
DateUtils.WEEK_IN_MILLIS,
|
||||
0
|
||||
).toString()
|
||||
val parts = expectedString.split(",")
|
||||
val expected = if (parts.size == 2) {
|
||||
if (parts[1].contains(":") && !parts[0].contains(":")) parts[0].trim() else parts[1].trim()
|
||||
} else {
|
||||
expectedString
|
||||
}
|
||||
|
||||
assertRelativeDateTimeString(time, expected)
|
||||
fun getRelativeDateTimeStringReturnsTodayForNow() {
|
||||
assertRelativeDateTimeString(
|
||||
time = System.currentTimeMillis(),
|
||||
expected = "Today",
|
||||
minResolution = DateUtils.DAY_IN_MILLIS
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getRelativeDateTimeStringReturnsAbbreviatedStringForOneMonthAgo() {
|
||||
val time = System.currentTimeMillis() - ONE_MONTH
|
||||
val expectedString = DateUtils.getRelativeDateTimeString(
|
||||
context,
|
||||
time,
|
||||
DateUtils.SECOND_IN_MILLIS,
|
||||
DateUtils.WEEK_IN_MILLIS,
|
||||
0
|
||||
).toString()
|
||||
val parts = expectedString.split(",")
|
||||
val expected = if (parts.size == 2) {
|
||||
if (parts[1].contains(":") && !parts[0].contains(":")) parts[0].trim() else parts[1].trim()
|
||||
} else {
|
||||
expectedString
|
||||
}
|
||||
|
||||
assertRelativeDateTimeString(time, expected, DateUtils.SECOND_IN_MILLIS)
|
||||
fun getRelativeDateTimeStringReturnsYesterdayForOneDayAgo() {
|
||||
assertRelativeDateTimeString(
|
||||
time = System.currentTimeMillis() - ONE_DAY,
|
||||
expected = "Yesterday",
|
||||
minResolution = DateUtils.DAY_IN_MILLIS
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getRelativeDateTimeStringReturnsAbsoluteStringForOneYearAgo() {
|
||||
val time = System.currentTimeMillis() - ONE_YEAR
|
||||
val expectedString = DateUtils.getRelativeDateTimeString(
|
||||
context,
|
||||
time,
|
||||
DateUtils.SECOND_IN_MILLIS,
|
||||
DateUtils.WEEK_IN_MILLIS,
|
||||
0
|
||||
).toString()
|
||||
val parts = expectedString.split(",")
|
||||
val expected = if (parts.size == 2) {
|
||||
if (parts[1].contains(":") && !parts[0].contains(":")) parts[0].trim() else parts[1].trim()
|
||||
} else {
|
||||
expectedString
|
||||
}
|
||||
|
||||
assertRelativeDateTimeString(time, expected, DateUtils.SECOND_IN_MILLIS)
|
||||
fun getRelativeDateTimeStringReturnsDaysAgoForTwoDaysAgo() {
|
||||
assertRelativeDateTimeString(
|
||||
time = System.currentTimeMillis() - TWO_DAYS,
|
||||
expected = "2 days ago",
|
||||
minResolution = DateUtils.DAY_IN_MILLIS
|
||||
)
|
||||
}
|
||||
|
||||
@Suppress("MagicNumber")
|
||||
@Test
|
||||
fun getRelativeDateTimeStringReturnsDaysForDayInMillis() {
|
||||
var testTimestamp = System.currentTimeMillis()
|
||||
var expected = "Today"
|
||||
var result = DisplayUtils.getRelativeDateTimeString(
|
||||
context,
|
||||
testTimestamp,
|
||||
DateUtils.DAY_IN_MILLIS,
|
||||
DateUtils.WEEK_IN_MILLIS,
|
||||
0,
|
||||
false
|
||||
)
|
||||
assertEquals(expected, result)
|
||||
fun getRelativeDateTimeStringDropsTimeOfDayForOneWeekAgo() {
|
||||
assertDateWithoutTimeOfDay(System.currentTimeMillis() - ONE_WEEK, DateUtils.MINUTE_IN_MILLIS)
|
||||
}
|
||||
|
||||
testTimestamp = System.currentTimeMillis() - DateUtils.DAY_IN_MILLIS
|
||||
expected = "Yesterday"
|
||||
result = DisplayUtils.getRelativeDateTimeString(
|
||||
context,
|
||||
testTimestamp,
|
||||
DateUtils.DAY_IN_MILLIS,
|
||||
DateUtils.WEEK_IN_MILLIS,
|
||||
0,
|
||||
false
|
||||
)
|
||||
assertEquals(expected, result)
|
||||
@Test
|
||||
fun getRelativeDateTimeStringDropsTimeOfDayForOneWeekAgoWithDayResolution() {
|
||||
assertDateWithoutTimeOfDay(System.currentTimeMillis() - ONE_WEEK, DateUtils.DAY_IN_MILLIS)
|
||||
}
|
||||
|
||||
testTimestamp = System.currentTimeMillis() - 2 * DateUtils.DAY_IN_MILLIS
|
||||
expected = "2 days ago"
|
||||
result = DisplayUtils.getRelativeDateTimeString(
|
||||
context,
|
||||
testTimestamp,
|
||||
DateUtils.DAY_IN_MILLIS,
|
||||
DateUtils.WEEK_IN_MILLIS,
|
||||
0,
|
||||
false
|
||||
)
|
||||
assertEquals(expected, result)
|
||||
@Test
|
||||
fun getRelativeDateTimeStringDropsTimeOfDayForOneMonthAgo() {
|
||||
assertDateWithoutTimeOfDay(System.currentTimeMillis() - ONE_MONTH, DateUtils.SECOND_IN_MILLIS)
|
||||
}
|
||||
|
||||
testTimestamp = System.currentTimeMillis() - 7 * DateUtils.DAY_IN_MILLIS
|
||||
val expectedString = DateUtils.getRelativeDateTimeString(
|
||||
context,
|
||||
testTimestamp,
|
||||
DateUtils.DAY_IN_MILLIS,
|
||||
DateUtils.WEEK_IN_MILLIS,
|
||||
0
|
||||
).toString()
|
||||
val parts = expectedString.split(",")
|
||||
expected = if (parts.size == 2) {
|
||||
if (parts[1].contains(":") && !parts[0].contains(":")) parts[0].trim() else parts[1].trim()
|
||||
} else {
|
||||
expectedString
|
||||
}
|
||||
result = DisplayUtils.getRelativeDateTimeString(
|
||||
context,
|
||||
testTimestamp,
|
||||
DateUtils.DAY_IN_MILLIS,
|
||||
DateUtils.WEEK_IN_MILLIS,
|
||||
0,
|
||||
false
|
||||
)
|
||||
assertEquals(expected, result)
|
||||
@Test
|
||||
fun getRelativeDateTimeStringDropsTimeOfDayForOneYearAgo() {
|
||||
assertDateWithoutTimeOfDay(System.currentTimeMillis() - ONE_YEAR, DateUtils.SECOND_IN_MILLIS)
|
||||
}
|
||||
|
||||
private fun assertRelativeDateTimeString(
|
||||
time: Long,
|
||||
expected: String,
|
||||
minResolution: Long = DateUtils.MINUTE_IN_MILLIS,
|
||||
transitionResolution: Long = DateUtils.WEEK_IN_MILLIS,
|
||||
showFuture: Boolean = false
|
||||
) {
|
||||
val result = DisplayUtils.getRelativeDateTimeString(
|
||||
context,
|
||||
time,
|
||||
minResolution,
|
||||
transitionResolution,
|
||||
DateUtils.WEEK_IN_MILLIS,
|
||||
0,
|
||||
showFuture
|
||||
)
|
||||
assertEquals(expected.normalizeResult(), result.toString().normalizeResult())
|
||||
|
||||
assertEquals(expected.normalizeSpaces(), result.toString().normalizeSpaces())
|
||||
}
|
||||
|
||||
private fun String.normalizeResult(): String = replace('\u202F', ' ').replace('\u00A0', ' ')
|
||||
private fun assertDateWithoutTimeOfDay(time: Long, minResolution: Long) = assertRelativeDateTimeString(
|
||||
time = time,
|
||||
expected = platformDateClause(time, minResolution),
|
||||
minResolution = minResolution
|
||||
)
|
||||
|
||||
private fun platformDateClause(time: Long, minResolution: Long): String {
|
||||
val platformString = DateUtils.getRelativeDateTimeString(
|
||||
context,
|
||||
time,
|
||||
minResolution,
|
||||
DateUtils.WEEK_IN_MILLIS,
|
||||
0
|
||||
).toString()
|
||||
|
||||
val parts = platformString.split(",").map(String::trim)
|
||||
if (parts.size != DATE_AND_TIME_PARTS) {
|
||||
return platformString
|
||||
}
|
||||
|
||||
val (date, timeOfDay) = parts
|
||||
return when {
|
||||
timeOfDay.hasTimeOfDay() && !date.hasTimeOfDay() -> date
|
||||
date.hasTimeOfDay() && !timeOfDay.hasTimeOfDay() -> timeOfDay
|
||||
else -> platformString
|
||||
}
|
||||
}
|
||||
|
||||
private fun Context.localized(locale: Locale): Context {
|
||||
val configuration = Configuration(resources.configuration).apply { setLocale(locale) }
|
||||
return createConfigurationContext(configuration)
|
||||
}
|
||||
|
||||
private fun String.hasTimeOfDay(): Boolean = contains(TIME_OF_DAY_SEPARATOR)
|
||||
|
||||
private fun String.normalizeSpaces(): String = replace(NARROW_NO_BREAK_SPACE, ' ').replace(NO_BREAK_SPACE, ' ')
|
||||
}
|
||||
@@ -26,8 +26,7 @@ import com.nextcloud.android.common.ui.theme.MaterialSchemesImpl;
|
||||
import com.nextcloud.client.account.User;
|
||||
import com.nextcloud.client.account.UserAccountManager;
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl;
|
||||
import com.nextcloud.client.device.BatteryStatus;
|
||||
import com.nextcloud.client.device.PowerManagementService;
|
||||
import com.nextcloud.utils.PowerManagementFactory;
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker;
|
||||
import com.nextcloud.client.network.ConnectivityManagerFactory;
|
||||
import com.nextcloud.client.network.ConnectivityService;
|
||||
@@ -73,7 +72,6 @@ import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.fragment.app.DialogFragment;
|
||||
import androidx.test.espresso.contrib.DrawerActions;
|
||||
import androidx.test.espresso.intent.rule.IntentsTestRule;
|
||||
@@ -367,24 +365,7 @@ public abstract class AbstractIT {
|
||||
}
|
||||
|
||||
public void uploadOCUpload(OCUpload ocUpload) {
|
||||
PowerManagementService powerManagementServiceMock = new PowerManagementService() {
|
||||
@Override
|
||||
public boolean isIgnoringOptimization() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public BatteryStatus getBattery() {
|
||||
return new BatteryStatus();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPowerSavingEnabled() {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
final var powerManagementServiceMock = PowerManagementFactory.getMock();
|
||||
UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
|
||||
UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(accountManager,
|
||||
targetContext.getContentResolver());
|
||||
|
||||
@@ -16,8 +16,7 @@ import android.os.Bundle;
|
||||
import com.nextcloud.client.account.User;
|
||||
import com.nextcloud.client.account.UserAccountManager;
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl;
|
||||
import com.nextcloud.client.device.BatteryStatus;
|
||||
import com.nextcloud.client.device.PowerManagementService;
|
||||
import com.nextcloud.utils.PowerManagementFactory;
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker;
|
||||
import com.owncloud.android.datamodel.OCFile;
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager;
|
||||
@@ -45,7 +44,6 @@ import java.io.IOException;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
@@ -205,24 +203,7 @@ public abstract class AbstractOnServerIT extends AbstractIT {
|
||||
}
|
||||
|
||||
public void uploadOCUpload(OCUpload ocUpload, int localBehaviour) {
|
||||
PowerManagementService powerManagementServiceMock = new PowerManagementService() {
|
||||
@Override
|
||||
public boolean isIgnoringOptimization() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public BatteryStatus getBattery() {
|
||||
return new BatteryStatus();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPowerSavingEnabled() {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
final var powerManagementServiceMock = PowerManagementFactory.getMock();
|
||||
UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
|
||||
UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(accountManager,
|
||||
targetContext.getContentResolver());
|
||||
|
||||
@@ -7,8 +7,7 @@
|
||||
package com.owncloud.android
|
||||
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl
|
||||
import com.nextcloud.client.device.BatteryStatus
|
||||
import com.nextcloud.client.device.PowerManagementService
|
||||
import com.nextcloud.utils.PowerManagementFactory
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager
|
||||
import com.owncloud.android.db.OCUpload
|
||||
@@ -21,6 +20,7 @@ import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import java.io.IOException
|
||||
@@ -36,11 +36,7 @@ class GrantFolderExistenceTests : AbstractOnServerIT() {
|
||||
targetContext.contentResolver
|
||||
)
|
||||
|
||||
private val powerManagementServiceMock = object : PowerManagementService {
|
||||
override val isPowerSavingEnabled = false
|
||||
override val isIgnoringOptimization = true
|
||||
override val battery = BatteryStatus(false, 0)
|
||||
}
|
||||
private val powerManagementServiceMock = PowerManagementFactory.mock
|
||||
|
||||
@Before
|
||||
@Throws(IOException::class)
|
||||
@@ -55,7 +51,7 @@ class GrantFolderExistenceTests : AbstractOnServerIT() {
|
||||
assertTrue("month folder should exist on server", existsOnServer(monthFolder))
|
||||
assertNotNull("month folder should be cached locally", storageManager.getFileByDecryptedRemotePath(monthFolder))
|
||||
|
||||
removeYearFolderOnServerOnly()
|
||||
removeOnServer(yearFolder)
|
||||
|
||||
assertFalse("month folder should be deleted", existsOnServer(monthFolder))
|
||||
assertNotNull(
|
||||
@@ -79,10 +75,7 @@ class GrantFolderExistenceTests : AbstractOnServerIT() {
|
||||
fun testUploadFileThenDeleteRootOnServerOnlyThenUploadAgainShouldRecreateAllFolderLevelsAndReturnOk() {
|
||||
uploadAndAssertSuccess("first.txt")
|
||||
|
||||
assertTrue(
|
||||
"root folder should be removed",
|
||||
RemoveFileRemoteOperation(root).execute(client).isSuccess
|
||||
)
|
||||
removeOnServer(root)
|
||||
assertFalse(existsOnServer(root))
|
||||
|
||||
val result = upload("nonEmpty.txt", monthFolder + "nonEmpty.txt")
|
||||
@@ -103,11 +96,18 @@ class GrantFolderExistenceTests : AbstractOnServerIT() {
|
||||
assertTrue("uploaded file should exist on server", existsOnServer(monthFolder + filename))
|
||||
}
|
||||
|
||||
private fun removeYearFolderOnServerOnly() {
|
||||
assertTrue(
|
||||
"year folder should be removed",
|
||||
RemoveFileRemoteOperation(yearFolder).execute(client).isSuccess
|
||||
)
|
||||
private fun removeOnServer(remotePath: String) {
|
||||
// the server keeps a transient lock on a just uploaded file, so a DELETE on one of its
|
||||
// parent folders answers 423 until that lock expires
|
||||
repeat(REMOVE_ATTEMPTS) {
|
||||
if (RemoveFileRemoteOperation(remotePath).execute(client).isSuccess) {
|
||||
return
|
||||
}
|
||||
|
||||
shortSleep()
|
||||
}
|
||||
|
||||
fail("$remotePath should be removed on server")
|
||||
}
|
||||
|
||||
private fun existsOnServer(remotePath: String): Boolean =
|
||||
@@ -144,5 +144,6 @@ class GrantFolderExistenceTests : AbstractOnServerIT() {
|
||||
|
||||
companion object {
|
||||
private const val FILE_LINE_COUNT = 100
|
||||
private const val REMOVE_ATTEMPTS = 5
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,12 @@
|
||||
package com.owncloud.android;
|
||||
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl;
|
||||
import com.nextcloud.client.device.BatteryStatus;
|
||||
import com.nextcloud.utils.PowerManagementFactory;
|
||||
import com.nextcloud.client.device.PowerManagementService;
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker;
|
||||
import com.nextcloud.client.network.ConnectivityManagerFactory;
|
||||
import com.nextcloud.client.network.ConnectivityService;
|
||||
import com.nextcloud.test.SinceServer;
|
||||
import com.owncloud.android.datamodel.OCFile;
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager;
|
||||
import com.owncloud.android.db.OCUpload;
|
||||
@@ -38,8 +39,6 @@ import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static junit.framework.TestCase.assertFalse;
|
||||
import static junit.framework.TestCase.assertNotNull;
|
||||
@@ -55,22 +54,7 @@ public class UploadIT extends AbstractOnServerIT {
|
||||
new UploadsStorageManager(UserAccountManagerImpl.fromContext(targetContext),
|
||||
targetContext.getContentResolver());
|
||||
|
||||
private PowerManagementService powerManagementServiceMock = new PowerManagementService() {
|
||||
@Override
|
||||
public boolean isIgnoringOptimization() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPowerSavingEnabled() {
|
||||
return false;
|
||||
}
|
||||
@NonNull
|
||||
@Override
|
||||
public BatteryStatus getBattery() {
|
||||
return new BatteryStatus(false, 0);
|
||||
}
|
||||
};
|
||||
private final PowerManagementService powerManagementServiceMock = PowerManagementFactory.getMock();
|
||||
|
||||
@Before
|
||||
public void before() throws IOException {
|
||||
@@ -208,24 +192,7 @@ public class UploadIT extends AbstractOnServerIT {
|
||||
|
||||
@Test
|
||||
public void testUploadOnChargingOnlyAndCharging() {
|
||||
PowerManagementService powerManagementServiceMock = new PowerManagementService() {
|
||||
@Override
|
||||
public boolean isIgnoringOptimization() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPowerSavingEnabled() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public BatteryStatus getBattery() {
|
||||
return new BatteryStatus(true, 100);
|
||||
}
|
||||
};
|
||||
|
||||
final var powerManagementServiceMock = PowerManagementFactory.getMockCharging();
|
||||
OCUpload ocUpload = new OCUpload(FileStorageUtils.getTemporalPath(account.name) + "/empty.txt",
|
||||
FOLDER + "charging.txt", account.name);
|
||||
ocUpload.setWhileChargingOnly(true);
|
||||
@@ -355,6 +322,7 @@ public class UploadIT extends AbstractOnServerIT {
|
||||
}
|
||||
|
||||
@Test
|
||||
@SinceServer(majorVersion = 27)
|
||||
public void testCreationAndUploadTimestamp() throws IOException, AccountUtils.AccountNotFoundException {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_27);
|
||||
|
||||
@@ -409,6 +377,7 @@ public class UploadIT extends AbstractOnServerIT {
|
||||
}
|
||||
|
||||
@Test
|
||||
@SinceServer(majorVersion = 27)
|
||||
public void testMetadata() throws IOException, AccountUtils.AccountNotFoundException {
|
||||
testOnlyOnServer(NextcloudVersion.nextcloud_27);
|
||||
|
||||
|
||||
@@ -69,6 +69,7 @@ class FileMenuFilterIT : AbstractIT() {
|
||||
every { mockComponentsGetter.operationsServiceBinder } returns mockOperationsServiceBinder
|
||||
every { mockStorageManager.getFileById(any()) } returns OCFile("/")
|
||||
every { mockStorageManager.getFolderContent(any(), any()) } returns ArrayList<OCFile>()
|
||||
every { mockStorageManager.isReadOnly(any()) } returns false
|
||||
every { mockArbitraryDataProvider.getValue(any<User>(), any()) } returns ""
|
||||
editorUtils = EditorUtils(mockArbitraryDataProvider)
|
||||
}
|
||||
@@ -363,6 +364,63 @@ class FileMenuFilterIT : AbstractIT() {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun filter_readOnlyFile_hidesModifyingActions() {
|
||||
configureCapability(
|
||||
OCCapability().apply {
|
||||
endToEndEncryption = CapabilityBooleanType.TRUE
|
||||
filesLockingVersion = "1.0"
|
||||
}
|
||||
)
|
||||
|
||||
every { mockStorageManager.isReadOnly(any()) } returns true
|
||||
|
||||
val file = OCFile("/readOnly.txt").apply {
|
||||
permissions = FULL_PERMISSIONS
|
||||
}
|
||||
|
||||
launchActivity<TestActivity>().use {
|
||||
it.onActivity { activity ->
|
||||
val filterFactory = FileMenuFilter.Factory(mockStorageManager, activity, editorUtils)
|
||||
|
||||
val toHide = filterFactory
|
||||
.newInstance(file, mockComponentsGetter, true, user)
|
||||
.getToHide(false)
|
||||
|
||||
READ_ONLY_HIDDEN_ACTIONS.forEach { action ->
|
||||
assertTrue(toHide.contains(action))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun filter_writableFile_keepsModifyingActions() {
|
||||
configureCapability(
|
||||
OCCapability().apply {
|
||||
filesLockingVersion = "1.0"
|
||||
}
|
||||
)
|
||||
|
||||
val file = OCFile("/writable.txt").apply {
|
||||
permissions = FULL_PERMISSIONS
|
||||
}
|
||||
|
||||
launchActivity<TestActivity>().use {
|
||||
it.onActivity { activity ->
|
||||
val filterFactory = FileMenuFilter.Factory(mockStorageManager, activity, editorUtils)
|
||||
|
||||
val toHide = filterFactory
|
||||
.newInstance(file, mockComponentsGetter, true, user)
|
||||
.getToHide(false)
|
||||
|
||||
WRITABLE_VISIBLE_ACTIONS.forEach { action ->
|
||||
assertFalse(toHide.contains(action))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private data class ExpectedLockVisibilities(val lockFile: Boolean, val unlockFile: Boolean)
|
||||
|
||||
private fun configureCapability(capability: OCCapability) {
|
||||
@@ -398,6 +456,29 @@ class FileMenuFilterIT : AbstractIT() {
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val FULL_PERMISSIONS = "RGDNVW"
|
||||
|
||||
private val READ_ONLY_HIDDEN_ACTIONS = listOf(
|
||||
R.id.action_remove_file,
|
||||
R.id.action_rename_file,
|
||||
R.id.action_move_or_copy,
|
||||
R.id.action_edit,
|
||||
R.id.action_encrypted,
|
||||
R.id.action_unset_encrypted,
|
||||
R.id.action_lock_file,
|
||||
R.id.action_unlock_file,
|
||||
R.id.action_favorite,
|
||||
R.id.action_unset_favorite
|
||||
)
|
||||
|
||||
private val WRITABLE_VISIBLE_ACTIONS = listOf(
|
||||
R.id.action_remove_file,
|
||||
R.id.action_rename_file,
|
||||
R.id.action_move_or_copy,
|
||||
R.id.action_lock_file,
|
||||
R.id.action_favorite
|
||||
)
|
||||
|
||||
private const val OFFICE_MIMETYPE =
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||
|
||||
|
||||
@@ -10,8 +10,7 @@
|
||||
package com.owncloud.android.files.services
|
||||
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl
|
||||
import com.nextcloud.client.device.BatteryStatus
|
||||
import com.nextcloud.client.device.PowerManagementService
|
||||
import com.nextcloud.utils.PowerManagementFactory
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker
|
||||
import com.owncloud.android.AbstractOnServerIT
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager
|
||||
@@ -30,11 +29,7 @@ class FileUploaderIT : AbstractOnServerIT() {
|
||||
|
||||
private lateinit var uploadsStorageManager: UploadsStorageManager
|
||||
|
||||
private val powerManagementServiceMock = object : PowerManagementService {
|
||||
override val isIgnoringOptimization = true
|
||||
override val isPowerSavingEnabled = false
|
||||
override val battery = BatteryStatus()
|
||||
}
|
||||
private val powerManagementServiceMock = PowerManagementFactory.mock
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
|
||||
+47
-10
@@ -8,10 +8,15 @@ package com.owncloud.android.providers
|
||||
|
||||
import android.provider.DocumentsContract
|
||||
import androidx.documentfile.provider.DocumentFile
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl
|
||||
import com.nextcloud.client.jobs.upload.FileUploadHelper
|
||||
import com.nextcloud.test.RandomStringGenerator
|
||||
import com.owncloud.android.AbstractOnServerIT
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.OCFile.ROOT_PATH
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager.UploadStatus
|
||||
import com.owncloud.android.db.OCUpload
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.providers.DocumentsProviderUtils.assertExistsOnServer
|
||||
import com.owncloud.android.providers.DocumentsProviderUtils.assertListFilesEquals
|
||||
@@ -31,12 +36,16 @@ import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import kotlin.random.Random
|
||||
|
||||
private const val MAX_FILE_NAME_LENGTH = 225
|
||||
|
||||
// the provider can only enqueue the upload worker, so give it a generous budget before giving up
|
||||
private const val UPLOAD_POLL_ATTEMPTS = 45
|
||||
|
||||
class DocumentsStorageProviderIT : AbstractOnServerIT() {
|
||||
|
||||
private val context = targetContext
|
||||
@@ -48,8 +57,17 @@ class DocumentsStorageProviderIT : AbstractOnServerIT() {
|
||||
private val uri = DocumentsContract.buildTreeDocumentUri(authority, documentId)
|
||||
private val rootDir get() = DocumentFile.fromTreeUri(context, uri)!!
|
||||
|
||||
private val uploadsStorageManager = UploadsStorageManager(
|
||||
UserAccountManagerImpl.fromContext(context),
|
||||
contentResolver
|
||||
)
|
||||
|
||||
@Before
|
||||
fun before() {
|
||||
// an upload left over by a previous test fails once its local file is gone, and WorkManager
|
||||
// then drops everything appended behind it in the upload chain, including our own uploads
|
||||
FileUploadHelper.instance().cancel(user.accountName)
|
||||
|
||||
// DocumentsProvider#onCreate() is called when the application is started
|
||||
// which is *after* AbstractOnServerIT adds the accounts (when the app is freshly installed).
|
||||
// So we need to query our roots here to ensure that the internal storage map is initialized.
|
||||
@@ -211,11 +229,7 @@ class DocumentsStorageProviderIT : AbstractOnServerIT() {
|
||||
it!!.write(content1)
|
||||
}
|
||||
|
||||
// refresh
|
||||
while (file1.getOCFile(storageManager)!!.etagOnServer == createdETag) {
|
||||
shortSleep()
|
||||
rootDir.listFiles()
|
||||
}
|
||||
awaitUploadedToServer(file1, createdETag)
|
||||
|
||||
val remotePath = file1.getOCFile(storageManager)!!.remotePath
|
||||
|
||||
@@ -250,11 +264,7 @@ class DocumentsStorageProviderIT : AbstractOnServerIT() {
|
||||
it!!.write(content1)
|
||||
}
|
||||
|
||||
// refresh
|
||||
while (file1.getOCFile(storageManager)!!.etagOnServer == createdETag) {
|
||||
shortSleep()
|
||||
rootDir.listFiles()
|
||||
}
|
||||
awaitUploadedToServer(file1, createdETag)
|
||||
|
||||
val content2 = "new content".toByteArray()
|
||||
|
||||
@@ -266,4 +276,31 @@ class DocumentsStorageProviderIT : AbstractOnServerIT() {
|
||||
val bytes = contentResolver.openInputStream(file1.uri)?.readBytes() ?: ByteArray(0)
|
||||
assertEquals(String(content2), String(bytes))
|
||||
}
|
||||
|
||||
private fun awaitUploadedToServer(file: DocumentFile, etagBeforeUpload: String) {
|
||||
val remotePath = file.getOCFile(storageManager)!!.remotePath
|
||||
|
||||
repeat(UPLOAD_POLL_ATTEMPTS) {
|
||||
if (file.getOCFile(storageManager)!!.etagOnServer != etagBeforeUpload) {
|
||||
return
|
||||
}
|
||||
|
||||
failedUpload(remotePath)?.let {
|
||||
fail("upload of $remotePath failed with ${it.lastResult}")
|
||||
}
|
||||
|
||||
shortSleep()
|
||||
rootDir.listFiles()
|
||||
}
|
||||
|
||||
fail("upload of $remotePath did not finish, stored uploads: ${describeUploads()}")
|
||||
}
|
||||
|
||||
private fun failedUpload(remotePath: String): OCUpload? = uploadsStorageManager
|
||||
.getUploadsForAccount(user.accountName)
|
||||
.firstOrNull { it.remotePath == remotePath && it.uploadStatus == UploadStatus.UPLOAD_FAILED }
|
||||
|
||||
private fun describeUploads(): String = uploadsStorageManager
|
||||
.getUploadsForAccount(user.accountName)
|
||||
.joinToString { "${it.remotePath} is ${it.uploadStatus} with ${it.lastResult}" }
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import androidx.test.filters.SdkSuppress
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.nextcloud.client.account.UserAccountManager
|
||||
import com.nextcloud.client.account.UserAccountManagerImpl
|
||||
import com.nextcloud.test.Flaky
|
||||
import com.nextcloud.test.GrantStoragePermissionRule
|
||||
import com.nextcloud.test.RetryTestRule
|
||||
import com.owncloud.android.AbstractIT
|
||||
@@ -28,7 +29,6 @@ import com.owncloud.android.authentication.AuthenticatorActivity
|
||||
import org.junit.AfterClass
|
||||
import org.junit.Assert
|
||||
import org.junit.Before
|
||||
import org.junit.Ignore
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
|
||||
@@ -54,7 +54,7 @@ class LoginIT : AbstractIT() {
|
||||
@Throws(InterruptedException::class)
|
||||
@Suppress("MagicNumber", "SwallowedException")
|
||||
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.Q)
|
||||
@Ignore("Login no longer uses an in-app WebView, so espresso-web (Espresso.onWebView) cannot drive it. ")
|
||||
@Flaky("Login no longer uses an in-app WebView, so espresso-web (Espresso.onWebView) cannot drive it. ")
|
||||
fun login() {
|
||||
val arguments = InstrumentationRegistry.getArguments()
|
||||
val baseUrl = arguments.getString("TEST_SERVER_URL")!!
|
||||
|
||||
+5
-5
@@ -25,10 +25,10 @@ import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.db.OCUpload
|
||||
import com.owncloud.android.ui.dialog.ConflictsResolveDialog
|
||||
import com.owncloud.android.ui.dialog.ConflictsResolveDialog.Companion.newInstance
|
||||
import com.owncloud.android.ui.dialog.ConflictsResolveDialog.Decision
|
||||
import com.owncloud.android.ui.dialog.ConflictsResolveDialog.OnConflictDecisionMadeListener
|
||||
import com.owncloud.android.ui.dialog.conflict.ConflictsResolveDialog
|
||||
import com.owncloud.android.ui.dialog.conflict.ConflictsResolveDialog.Decision
|
||||
import com.owncloud.android.ui.dialog.conflict.ConflictsResolveDialog.OnConflictDecisionMadeListener
|
||||
import com.owncloud.android.ui.dialog.conflict.ConflictResolveDialogFactory
|
||||
import com.owncloud.android.utils.EspressoIdlingResource
|
||||
import com.owncloud.android.utils.FileStorageUtils
|
||||
import com.owncloud.android.utils.ScreenshotTest
|
||||
@@ -69,7 +69,7 @@ class ConflictsResolveActivityIT : AbstractIT() {
|
||||
launchActivity<ConflictsResolveActivity>(intent).use { scenario ->
|
||||
var dialog: ConflictsResolveDialog? = null
|
||||
scenario.onActivity { sut ->
|
||||
dialog = newInstance(
|
||||
dialog = ConflictResolveDialogFactory.forNormal(
|
||||
storageManager.getDecryptedPath(existingFile),
|
||||
targetContext,
|
||||
newFile,
|
||||
|
||||
+2
-2
@@ -28,7 +28,7 @@ class SetupEncryptionDialogFragmentIT : AbstractIT() {
|
||||
launchActivity<TestActivity>().use { scenario ->
|
||||
var sut: SetupEncryptionDialogFragment? = null
|
||||
scenario.onActivity { activity ->
|
||||
sut = SetupEncryptionDialogFragment.newInstance(user, null)
|
||||
sut = SetupEncryptionDialogFragment.newInstance(user, null, null)
|
||||
sut.show(activity.supportFragmentManager, "1")
|
||||
val keyWords = arrayListOf(
|
||||
"ability",
|
||||
@@ -64,7 +64,7 @@ class SetupEncryptionDialogFragmentIT : AbstractIT() {
|
||||
launchActivity<TestActivity>().use { scenario ->
|
||||
var sut: SetupEncryptionDialogFragment? = null
|
||||
scenario.onActivity { activity ->
|
||||
sut = SetupEncryptionDialogFragment.newInstance(user, null)
|
||||
sut = SetupEncryptionDialogFragment.newInstance(user, null, null)
|
||||
sut.show(activity.supportFragmentManager, "1")
|
||||
sut.errorSavingKeys()
|
||||
}
|
||||
|
||||
@@ -67,6 +67,7 @@ class UnifiedSearchFragmentIT : AbstractIT() {
|
||||
scenario.onActivity { activity ->
|
||||
val sut = UnifiedSearchFragment.newInstance(null, null, "/")
|
||||
val testViewModel = UnifiedSearchViewModel(activity.application)
|
||||
testViewModel.setCurrentAccountProvider(activity.userAccountManager)
|
||||
testViewModel.setConnectivityService(activity.connectivityServiceMock)
|
||||
val localRepository = UnifiedSearchFakeRepository()
|
||||
testViewModel.setRepository(localRepository)
|
||||
|
||||
@@ -211,7 +211,7 @@ class PreviewImageActivityIT : AbstractOnServerIT() {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore(
|
||||
@Flaky(
|
||||
"Offline deletion is following a different UX and it is also brittle: Deletion might happen 10 minutes later"
|
||||
)
|
||||
fun deleteFromSlideshow_remote_offline() {
|
||||
|
||||
@@ -28,6 +28,7 @@ import com.owncloud.android.operations.RefreshFolderOperation
|
||||
import com.owncloud.android.util.EncryptionTestIT
|
||||
import junit.framework.TestCase.assertEquals
|
||||
import junit.framework.TestCase.assertTrue
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Test
|
||||
|
||||
@@ -645,76 +646,187 @@ class EncryptionUtilsV2IT : EncryptionIT() {
|
||||
assertEquals("this is a test.\n", gunzip)
|
||||
}
|
||||
|
||||
// @Test
|
||||
// fun validate() {
|
||||
// // ALEX
|
||||
// val metadata1 = """{
|
||||
// "metadata": {
|
||||
// "authenticationTag": "zMozev5R09UopLrq7Je1lw==",
|
||||
// "ciphertext": "j0OBtUrEt4IveGiexjmGK7eKEaWrY70ZkteA5KxHDaZT/t2wwGy9j2FPQGpqXnW6OO3iAYPNgwFikI1smnfNvqdxzVDvhavl/IXa9Kg2niWyqK3D9zpz0YD6mDvl0XsOgTNVyGXNVREdWgzGEERCQoyHI1xowt/swe3KCXw+lf+XPF/t1PfHv0DiDVk70AeWGpPPPu6yggAIxB4Az6PEZhaQWweTC0an48l2FHj2MtB2PiMHtW2v7RMuE8Al3PtE4gOA8CMFrB+Npy6rKcFCXOgTZm5bp7q+J1qkhBDbiBYtvdsYujJ52Xa5SifTpEhGeWWLFnLLgPAQ8o6bXcWOyCoYfLfp4Jpft/Y7H8qzHbPewNSyD6maEv+xljjfU7hxibbszz5A4JjMdQy2BDGoTmJx7Mas+g6l6ZuHLVbdmgQOvD3waJBy6rOg0euux0Cn4bB4bIFEF2KvbhdGbY1Uiq9DYa7kEmSEnlcAYaHyroTkDg4ew7ER0vIBBMzKM3r+UdPVKKS66uyXtZc=",
|
||||
// "nonce": "W+lxQJeGq7XAJiGfcDohkg=="
|
||||
// },
|
||||
// "users": [{
|
||||
// "certificate": "-----BEGIN CERTIFICATE-----\nMIIDkDCCAnigAwIBAgIBADANBgkqhkiG9w0BAQUFADBhMQswCQYDVQQGEwJERTEb\nMBkGA1UECAwSQmFkZW4tV3VlcnR0ZW1iZXJnMRIwEAYDVQQHDAlTdHV0dGdhcnQx\nEjAQBgNVBAoMCU5leHRjbG91ZDENMAsGA1UEAwwEam9objAeFw0yMzA3MTQwNzM0\nNTZaFw00MzA3MDkwNzM0NTZaMGExCzAJBgNVBAYTAkRFMRswGQYDVQQIDBJCYWRl\nbi1XdWVydHRlbWJlcmcxEjAQBgNVBAcMCVN0dXR0Z2FydDESMBAGA1UECgwJTmV4\ndGNsb3VkMQ0wCwYDVQQDDARqb2huMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\nCgKCAQEA7j3Er5YahJT0LAnSRLhpqbRo+E1AVnt98rvp3DmEfBHNzNB+DS9IBDkS\nSXM/YtfAci6Tcw8ujVBjrZX/WEmrf8ynQHxYmSaJSnP8uAT306/MceZpdpruEc9/\nS10a7vp54Zbld4NYdmfS71oVFVKgM7c/Vthx+rgu48fuxzbWAvVYLFcx47hz0DJT\nnjz2Za/R68uXpxfz7J9uEXYiqsAs/FobDsLZluT3RyywVRwKBed1EZxUeLIJiyxp\nUthhGfIb8b3Vf9jZoUVi3m5gmc4spJQHvYAkfZYHzd9ras8jBu1abQRxcu2CYnVo\n6Y0mTxhKhQS/n5gjv3ExiQF3wp/XYwIDAQABo1MwUTAdBgNVHQ4EFgQUmTeILVuB\ntv70fTGkXWGAueDp5kAwHwYDVR0jBBgwFoAUmTeILVuBtv70fTGkXWGAueDp5kAw\nDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAyVtq9XAvW7nxSW/8\nhp30z6xbzGiuviXhy/Jo91VEa8IRsWCCn3OmDFiVduTEowx76tf8clJP0gk7Pozi\n6dg/7Fin+FqQGXfCk8bLAh9gXKAikQ2GK8yRN3slRFwYC2mm23HrLdKXZHUqJcpB\nMz2zsSrOGPj1YsYOl/U8FU6KA7Yj7U3q7kDMYTAgzUPZAH+d1DISGWpZsMa0RYid\nvigCCLByiccmS/Co4Sb1esF58H+YtV5+nFBRwx881U2g2TgDKF1lPMK/y3d8B8mh\nUtW+lFxRpvyNUDpsMjOErOrtNFEYbgoUJLtqwBMmyGR+nmmh6xna331QWcRAmw0P\nnDO4ew==\n-----END CERTIFICATE-----\n",
|
||||
// "encryptedMetadataKey": "HVT49bYmwXbGs/dJ2avgU9unrKnPf03MYUI5ZysSR1Bz5pqz64gzH2GBAuUJ+Q4VmHtEfcMaWW7VXgzfCQv5xLBrk+RSgcLOKnlIya8jaDlfttWxbe8jJK+/0+QVPOc6ycA/t5HNCPg09hzj+gnb2L89UHxL5accZD0iEzb5cQbGrc/N6GthjgGrgFKtFf0HhDVplUr+DL9aTyKuKLBPjrjuZbv8M6ZfXO93mOMwSZH3c3rwDUHb/KEaTR/Og4pWQmrqr1VxGLqeV/+GKWhzMYThrOZAUz+5gsbckU2M5V9i+ph0yBI5BjOZVhNuDwW8yP8WtyRJwQc+UBRei/RGBQ==",
|
||||
// "userId": "john"
|
||||
// }],
|
||||
// "version": "2"
|
||||
// }
|
||||
//
|
||||
// """
|
||||
//
|
||||
// val signature1 =
|
||||
// "ewogICAgIm1ldGFkYXRhIjogewogICAgICAgICJhdXRoZW50aWNhdGlvblRhZyI6ICJ6TW96ZXY1UjA5VW9wTHJxN0plMWx3PT0iLAogICAgICAgICJjaXBoZXJ0ZXh0IjogImowT0J0VXJFdDRJdmVHaWV4am1HSzdlS0VhV3JZNzBaa3RlQTVLeEhEYVpUL3Qyd3dHeTlqMkZQUUdwcVhuVzZPTzNpQVlQTmd3RmlrSTFzbW5mTnZxZHh6VkR2aGF2bC9JWGE5S2cybmlXeXFLM0Q5enB6MFlENm1EdmwwWHNPZ1ROVnlHWE5WUkVkV2d6R0VFUkNRb3lISTF4b3d0L3N3ZTNLQ1h3K2xmK1hQRi90MVBmSHYwRGlEVms3MEFlV0dwUFBQdTZ5Z2dBSXhCNEF6NlBFWmhhUVd3ZVRDMGFuNDhsMkZIajJNdEIyUGlNSHRXMnY3Uk11RThBbDNQdEU0Z09BOENNRnJCK05weTZyS2NGQ1hPZ1RabTVicDdxK0oxcWtoQkRiaUJZdHZkc1l1ako1MlhhNVNpZlRwRWhHZVdXTEZuTExnUEFROG82YlhjV095Q29ZZkxmcDRKcGZ0L1k3SDhxekhiUGV3TlN5RDZtYUV2K3hsampmVTdoeGliYnN6ejVBNEpqTWRReTJCREdvVG1KeDdNYXMrZzZsNlp1SExWYmRtZ1FPdkQzd2FKQnk2ck9nMGV1dXgwQ240YkI0YklGRUYyS3ZiaGRHYlkxVWlxOURZYTdrRW1TRW5sY0FZYUh5cm9Ua0RnNGV3N0VSMHZJQkJNektNM3IrVWRQVktLUzY2dXlYdFpjPSIsCiAgICAgICAgIm5vbmNlIjogIlcrbHhRSmVHcTdYQUppR2ZjRG9oa2c9PSIKICAgIH0sCiAgICAidXNlcnMiOiB7CiAgICAgICAgImNlcnRpZmljYXRlIjogIi0tLS0tQkVHSU4gQ0VSVElGSUNBVEUtLS0tLVxuTUlJRGtEQ0NBbmlnQXdJQkFnSUJBREFOQmdrcWhraUc5dzBCQVFVRkFEQmhNUXN3Q1FZRFZRUUdFd0pFUlRFYlxuTUJrR0ExVUVDQXdTUW1Ga1pXNHRWM1ZsY25SMFpXMWlaWEpuTVJJd0VBWURWUVFIREFsVGRIVjBkR2RoY25ReFxuRWpBUUJnTlZCQW9NQ1U1bGVIUmpiRzkxWkRFTk1Bc0dBMVVFQXd3RWFtOW9iakFlRncweU16QTNNVFF3TnpNMFxuTlRaYUZ3MDBNekEzTURrd056TTBOVFphTUdFeEN6QUpCZ05WQkFZVEFrUkZNUnN3R1FZRFZRUUlEQkpDWVdSbFxuYmkxWGRXVnlkSFJsYldKbGNtY3hFakFRQmdOVkJBY01DVk4wZFhSMFoyRnlkREVTTUJBR0ExVUVDZ3dKVG1WNFxuZEdOc2IzVmtNUTB3Q3dZRFZRUUREQVJxYjJodU1JSUJJakFOQmdrcWhraUc5dzBCQVFFRkFBT0NBUThBTUlJQlxuQ2dLQ0FRRUE3ajNFcjVZYWhKVDBMQW5TUkxocHFiUm8rRTFBVm50OThydnAzRG1FZkJITnpOQitEUzlJQkRrU1xuU1hNL1l0ZkFjaTZUY3c4dWpWQmpyWlgvV0VtcmY4eW5RSHhZbVNhSlNuUDh1QVQzMDYvTWNlWnBkcHJ1RWM5L1xuUzEwYTd2cDU0WmJsZDROWWRtZlM3MW9WRlZLZ003Yy9WdGh4K3JndTQ4ZnV4emJXQXZWWUxGY3g0N2h6MERKVFxubmp6MlphL1I2OHVYcHhmejdKOXVFWFlpcXNBcy9Gb2JEc0xabHVUM1J5eXdWUndLQmVkMUVaeFVlTElKaXl4cFxuVXRoaEdmSWI4YjNWZjlqWm9VVmkzbTVnbWM0c3BKUUh2WUFrZlpZSHpkOXJhczhqQnUxYWJRUnhjdTJDWW5Wb1xuNlkwbVR4aEtoUVMvbjVnanYzRXhpUUYzd3AvWFl3SURBUUFCbzFNd1VUQWRCZ05WSFE0RUZnUVVtVGVJTFZ1QlxudHY3MGZUR2tYV0dBdWVEcDVrQXdId1lEVlIwakJCZ3dGb0FVbVRlSUxWdUJ0djcwZlRHa1hXR0F1ZURwNWtBd1xuRHdZRFZSMFRBUUgvQkFVd0F3RUIvekFOQmdrcWhraUc5dzBCQVFVRkFBT0NBUUVBeVZ0cTlYQXZXN254U1cvOFxuaHAzMHo2eGJ6R2l1dmlYaHkvSm85MVZFYThJUnNXQ0NuM09tREZpVmR1VEVvd3g3NnRmOGNsSlAwZ2s3UG96aVxuNmRnLzdGaW4rRnFRR1hmQ2s4YkxBaDlnWEtBaWtRMkdLOHlSTjNzbFJGd1lDMm1tMjNIckxkS1haSFVxSmNwQlxuTXoyenNTck9HUGoxWXNZT2wvVThGVTZLQTdZajdVM3E3a0RNWVRBZ3pVUFpBSCtkMURJU0dXcFpzTWEwUllpZFxudmlnQ0NMQnlpY2NtUy9DbzRTYjFlc0Y1OEgrWXRWNStuRkJSd3g4ODFVMmcyVGdES0YxbFBNSy95M2Q4QjhtaFxuVXRXK2xGeFJwdnlOVURwc01qT0VyT3J0TkZFWWJnb1VKTHRxd0JNbXlHUitubW1oNnhuYTMzMVFXY1JBbXcwUFxubkRPNGV3PT1cbi0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS1cbiIsCiAgICAgICAgImVuY3J5cHRlZE1ldGFkYXRhS2V5IjogIkhWVDQ5Ylltd1hiR3MvZEoyYXZnVTl1bnJLblBmMDNNWVVJNVp5c1NSMUJ6NXBxejY0Z3pIMkdCQXVVSitRNFZtSHRFZmNNYVdXN1ZYZ3pmQ1F2NXhMQnJrK1JTZ2NMT0tubEl5YThqYURsZnR0V3hiZThqSksrLzArUVZQT2M2eWNBL3Q1SE5DUGcwOWh6aitnbmIyTDg5VUh4TDVhY2NaRDBpRXpiNWNRYkdyYy9ONkd0aGpnR3JnRkt0RmYwSGhEVnBsVXIrREw5YVR5S3VLTEJQanJqdVpidjhNNlpmWE85M21PTXdTWkgzYzNyd0RVSGIvS0VhVFIvT2c0cFdRbXJxcjFWeEdMcWVWLytHS1doek1ZVGhyT1pBVXorNWdzYmNrVTJNNVY5aStwaDB5Qkk1QmpPWlZoTnVEd1c4eVA4V3R5Ukp3UWMrVUJSZWkvUkdCUT09IiwKICAgICAgICAidXNlcklkIjogImpvaG4iCiAgICB9LAogICAgInZlcnNpb24iOiAiMiIKfQo="
|
||||
//
|
||||
// // TOBI
|
||||
// val metadata =
|
||||
// """{"metadata":{"authenticationTag":"qDcJnAAGtGDlHWiQMBfXgw\u003d\u003d","ciphertext":"3zUhwIgJWMB7DvrbsDaMvh8MbJdoTxL0OMPCCdYSfBt7gB+V/hwqelL1IOaLto3avhHGSebnrotF06iEP/jZwWg9hApIPTHc8B4XTOY0/kezqYyVqTyquTUZpDpqgVAheQskZZ8I4Ir0seajUkt4KtVRfzO6v8CePRrEg6uKwdYsqDcJnAAGtGDlHWiQMBfXgw\u003d\u003d|4hbOyn1ykQL+9D6SnPY3cQ\u003d\u003d","nonce":"4hbOyn1ykQL+9D6SnPY3cQ\u003d\u003d"},"users":[{"certificate":"-----BEGIN CERTIFICATE-----\nMIIC6DCCAdCgAwIBAgIBADANBgkqhkiG9w0BAQUFADANMQswCQYDVQQDDAJ0MTAe\nFw0yMzA3MjUwNzU3MTJaFw00MzA3MjAwNzU3MTJaMA0xCzAJBgNVBAMMAnQxMIIB\nIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtafHmDBcBqIu4HmMxMDW3j0S\ny+S0YaKwHnBRt85KSwcEov0B5FOLuLknoBGx4Dn3u93ilThXXxacPMHeXL7WPuAs\n21/G7vsqwvrRRnCduf+FUO/AZeDCNErzpsQ8LmTa4PUloLPUcImpSjrHwhMs9Ekv\nEbLRjbeSmSp9XvM+1fV/3jkT5jkOSnCFx5TGwGN5uHqwUir4UWXasvg253NK2XmW\nipKCDCR9TmH1baP3pNdoiChdmErT1c6E4DbBXpTw8XgP5ZbYH+qg1UQ/hC8nRJ3D\nyCcHL+dg/GYraBMhDn4w2Vvq77xNNoNWQ9cT5Ay6cJbQLBQoJQirygQFrobYRQID\nAQABo1MwUTAdBgNVHQ4EFgQUE9zCeA9/QMAtVgLxD23X6ZcodhMwHwYDVR0jBBgw\nFoAUE9zCeA9/QMAtVgLxD23X6ZcodhMwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG\n9w0BAQUFAAOCAQEAZdy/YjJlvnz3FQwxp6oVtMJccpdxveEPfLzgaverhtd/vP8O\nAvDzOLgQJHmrDS91SG503eU4cYGyuNKwd77OyTnqMg+GUEmJhGfPpSVrEIdh65jv\nq61T4oqBdehevVmBq54rGiwL0DGv1DlXQlwiJZP4qni2KnOEFcnvL3gVtRnQjXQ+\nkHvlMshkK6w021EMV5NfjG2zg67wC65rLaej5f6Ssp2S7g2VtmE4aXq1bjAuEbqk\n4TiyZHLDdsJuqzyGyyOpMV7i9ucXDoaZt9cGS9hT2vRxTrSH63vKR8Xeig9+stLw\nt9ONcUqCKP7hd8rajtxM4JIIRExwD8OkgARWGg\u003d\u003d\n-----END CERTIFICATE-----\n","encryptedMetadataKey":"s4kDkkLpk1mSmXedP7huiCNC4DYmDAmA2VYGem5M8jIGPC6miVQoo4WXZrEBhdsLw7Msf5iT3A3fTaHhwsI8Jf4McsFyM9/FXT1mCEaGOEpNjbKOlJY1uPUFNOhLqUfFiBos6oBT53hWwoXWjytYvLBbXuXY5YLOysjgBh6URrgFUZAJAmcOJ6OFKgfIIthoqkQc7CQUY97VsRzAXzeYTANBc2yW1pSN51HqftvMzvewFRsJQLcu7a9NjpTdG9LiLhn5eLXOLymXEE/aaPHKXeprlXLzrdWU1xwZRJqV+to2FEiH6CQNsO4+9h5m0VjXekiNeAFrsXB5cJgUipGuzQ\u003d\u003d","userId":"t1"}],"version":"2.0"}"""
|
||||
//
|
||||
// val base = EncryptionUtils.encodeStringToBase64String(metadata)
|
||||
//
|
||||
// val signature =
|
||||
// "MIAGCSqGSIb3DQEHAqCAMIACAQExDTALBglghkgBZQMEAgEwCwYJKoZIhvcNAQcBoIAwggLoMIIB0KADAgECAgEAMA0GCSqGSIb3DQEBBQUAMA0xCzAJBgNVBAMMAnQxMB4XDTIzMDcyNTA3NTcxMloXDTQzMDcyMDA3NTcxMlowDTELMAkGA1UEAwwCdDEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC1p8eYMFwGoi7geYzEwNbePRLL5LRhorAecFG3zkpLBwSi/QHkU4u4uSegEbHgOfe73eKVOFdfFpw8wd5cvtY+4CzbX8bu+yrC+tFGcJ25/4VQ78Bl4MI0SvOmxDwuZNrg9SWgs9RwialKOsfCEyz0SS8RstGNt5KZKn1e8z7V9X/eORPmOQ5KcIXHlMbAY3m4erBSKvhRZdqy+Dbnc0rZeZaKkoIMJH1OYfVto/ek12iIKF2YStPVzoTgNsFelPDxeA/lltgf6qDVRD+ELydEncPIJwcv52D8ZitoEyEOfjDZW+rvvE02g1ZD1xPkDLpwltAsFCglCKvKBAWuhthFAgMBAAGjUzBRMB0GA1UdDgQWBBQT3MJ4D39AwC1WAvEPbdfplyh2EzAfBgNVHSMEGDAWgBQT3MJ4D39AwC1WAvEPbdfplyh2EzAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQBl3L9iMmW+fPcVDDGnqhW0wlxyl3G94Q98vOBq96uG13+8/w4C8PM4uBAkeasNL3VIbnTd5ThxgbK40rB3vs7JOeoyD4ZQSYmEZ8+lJWsQh2HrmO+rrVPiioF16F69WYGrnisaLAvQMa/UOVdCXCIlk/iqeLYqc4QVye8veBW1GdCNdD6Qe+UyyGQrrDTbUQxXk1+MbbODrvALrmstp6Pl/pKynZLuDZW2YThperVuMC4RuqThOLJkcsN2wm6rPIbLI6kxXuL25xcOhpm31wZL2FPa9HFOtIfre8pHxd6KD36y0vC3041xSoIo/uF3ytqO3EzgkghETHAPw6SABFYaAAAxggHUMIIB0AIBATASMA0xCzAJBgNVBAMMAnQxAgEAMAsGCWCGSAFlAwQCAaCBljAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0yMzA3MjgwNzMwMTJaMCsGCSqGSIb3DQEJNDEeMBwwCwYJYIZIAWUDBAIBoQ0GCSqGSIb3DQEBCwUAMC8GCSqGSIb3DQEJBDEiBCAx7RTJg7hbY5Mkzjw3f6qhX7k/J0FdVz2cL3ow0AmyYjANBgkqhkiG9w0BAQsFAASCAQAbUmb9e7eoIcPNzDSmnzbrueBzgT8YszNGEI+1YCq8XdWN4kDztvP1ZNV21VCO6BvcbfUAnXXgcX5BPeLZNsgXPj3c8TbD59GQl3oT/tIchgMsA20RdAtIwvItlZKh+X6sp0OHkRPYSk/mEYKCKPqrKdJicRWex8ItCwpDR91KSOiKJrN/+DKOGG0sVI9gjzbtrHsN8HmVKxOoNV+wwipcLsWsEmuV+wvPCQ9HJidLX9Q17Bgfc+qJg19aB6iKLWPhjgnfpKGbK5VJuQTdDWPUJ2O4G3W/iwxJ0hAJ7tks4zIATmgGzhgTWYx5LVXbKcuL04xhIOjqwedHeCSBZSSaAAAAAAAA"
|
||||
//
|
||||
// val metadataFile = EncryptionUtils.deserializeJSON(
|
||||
// metadata,
|
||||
// object : TypeToken<EncryptedFolderMetadataFile>() {}
|
||||
// )
|
||||
// assertNotNull(metadataFile)
|
||||
//
|
||||
// val certJohnString = metadataFile.users[0].certificate
|
||||
// val certJohn = EncryptionUtils.convertCertFromString(certJohnString)
|
||||
//
|
||||
// val t1String = """-----BEGIN CERTIFICATE-----
|
||||
// MIIC6DCCAdCgAwIBAgIBADANBgkqhkiG9w0BAQUFADANMQswCQYDVQQDDAJ0MTAe
|
||||
// Fw0yMzA3MjUwNzU3MTJaFw00MzA3MjAwNzU3MTJaMA0xCzAJBgNVBAMMAnQxMIIB
|
||||
// IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtafHmDBcBqIu4HmMxMDW3j0S
|
||||
// y+S0YaKwHnBRt85KSwcEov0B5FOLuLknoBGx4Dn3u93ilThXXxacPMHeXL7WPuAs
|
||||
// 21/G7vsqwvrRRnCduf+FUO/AZeDCNErzpsQ8LmTa4PUloLPUcImpSjrHwhMs9Ekv
|
||||
// EbLRjbeSmSp9XvM+1fV/3jkT5jkOSnCFx5TGwGN5uHqwUir4UWXasvg253NK2XmW
|
||||
// ipKCDCR9TmH1baP3pNdoiChdmErT1c6E4DbBXpTw8XgP5ZbYH+qg1UQ/hC8nRJ3D
|
||||
// yCcHL+dg/GYraBMhDn4w2Vvq77xNNoNWQ9cT5Ay6cJbQLBQoJQirygQFrobYRQID
|
||||
// AQABo1MwUTAdBgNVHQ4EFgQUE9zCeA9/QMAtVgLxD23X6ZcodhMwHwYDVR0jBBgw
|
||||
// FoAUE9zCeA9/QMAtVgLxD23X6ZcodhMwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG
|
||||
// 9w0BAQUFAAOCAQEAZdy/YjJlvnz3FQwxp6oVtMJccpdxveEPfLzgaverhtd/vP8O
|
||||
// AvDzOLgQJHmrDS91SG503eU4cYGyuNKwd77OyTnqMg+GUEmJhGfPpSVrEIdh65jv
|
||||
// q61T4oqBdehevVmBq54rGiwL0DGv1DlXQlwiJZP4qni2KnOEFcnvL3gVtRnQjXQ+
|
||||
// kHvlMshkK6w021EMV5NfjG2zg67wC65rLaej5f6Ssp2S7g2VtmE4aXq1bjAuEbqk
|
||||
// 4TiyZHLDdsJuqzyGyyOpMV7i9ucXDoaZt9cGS9hT2vRxTrSH63vKR8Xeig9+stLw
|
||||
// t9ONcUqCKP7hd8rajtxM4JIIRExwD8OkgARWGg==
|
||||
// -----END CERTIFICATE-----"""
|
||||
//
|
||||
// val t1cert = EncryptionUtils.convertCertFromString(t1String)
|
||||
// val t1PrivateKeyKey = EncryptionUtils.PEMtoPrivateKey(encryptionTestUtils.t1PrivateKey)
|
||||
//
|
||||
// // val signed = encryptionUtilsV2.getMessageSignature(
|
||||
// // t1cert,
|
||||
// // t1PrivateKeyKey,
|
||||
// // metadataFile
|
||||
// // )
|
||||
//
|
||||
// assertTrue(encryptionUtilsV2.verifySignedMessage(signature1, metadata1, listOf(certJohn, t1cert)))
|
||||
// }
|
||||
@Test
|
||||
fun verifyMetadataEmptyFolder() {
|
||||
val folder = OCFile("/e/")
|
||||
val enc1 = MockUser("enc1", "Nextcloud")
|
||||
|
||||
val metadataKey = EncryptionUtils.generateKey()
|
||||
val metadata = DecryptedMetadata(
|
||||
mutableListOf(),
|
||||
false,
|
||||
0,
|
||||
mutableMapOf(),
|
||||
mutableMapOf(),
|
||||
metadataKey
|
||||
)
|
||||
// checksum must be present before encrypting, otherwise verifyMetadata returns false
|
||||
metadata.keyChecksums.add(encryptionUtilsV2.hashMetadataKey(metadataKey))
|
||||
|
||||
val metadataFile = DecryptedFolderMetadataFile(
|
||||
metadata,
|
||||
mutableListOf(DecryptedUser(enc1.accountName, enc1Cert, null)),
|
||||
mutableMapOf(),
|
||||
E2EVersion.V2_1.value
|
||||
)
|
||||
|
||||
val encrypted = encryptionUtilsV2.encryptFolderMetadataFile(
|
||||
metadataFile,
|
||||
enc1UserId,
|
||||
folder,
|
||||
storageManager,
|
||||
client,
|
||||
enc1PrivateKey,
|
||||
user,
|
||||
targetContext,
|
||||
arbitraryDataProvider
|
||||
)
|
||||
val signature = encryptionUtilsV2.getMessageSignature(enc1Cert, enc1PrivateKey, encrypted)
|
||||
|
||||
val result = encryptionUtilsV2.verifyMetadata(encrypted, metadataFile, 0, signature)
|
||||
|
||||
assertTrue(result)
|
||||
assertEquals(0, metadataFile.metadata.files.size)
|
||||
assertEquals(0, metadataFile.metadata.folders.size)
|
||||
assertEquals(0, metadataFile.metadata.counter)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun verifyMetadataWithOneFile() {
|
||||
val folder = OCFile("/e/")
|
||||
val enc1 = MockUser("enc1", "Nextcloud")
|
||||
|
||||
val metadata = DecryptedMetadata(
|
||||
mutableListOf(),
|
||||
false,
|
||||
1,
|
||||
mutableMapOf(),
|
||||
mutableMapOf(
|
||||
Pair(
|
||||
EncryptionUtils.generateUid(),
|
||||
DecryptedFile(
|
||||
"document.pdf",
|
||||
"application/pdf",
|
||||
"initializationVector",
|
||||
"authenticationTag",
|
||||
"key1"
|
||||
)
|
||||
)
|
||||
),
|
||||
EncryptionUtils.generateKey()
|
||||
)
|
||||
metadata.keyChecksums.add(encryptionUtilsV2.hashMetadataKey(metadata.metadataKey))
|
||||
|
||||
val metadataFile = DecryptedFolderMetadataFile(
|
||||
metadata,
|
||||
mutableListOf(DecryptedUser(enc1.accountName, enc1Cert, null)),
|
||||
mutableMapOf(),
|
||||
E2EVersion.V2_1.value
|
||||
)
|
||||
|
||||
val encrypted = encryptionUtilsV2.encryptFolderMetadataFile(
|
||||
metadataFile,
|
||||
enc1UserId,
|
||||
folder,
|
||||
storageManager,
|
||||
client,
|
||||
enc1PrivateKey,
|
||||
user,
|
||||
targetContext,
|
||||
arbitraryDataProvider
|
||||
)
|
||||
|
||||
val signature = encryptionUtilsV2.getMessageSignature(enc1Cert, enc1PrivateKey, encrypted)
|
||||
|
||||
val result = encryptionUtilsV2.verifyMetadata(encrypted, metadataFile, 0, signature)
|
||||
|
||||
assertTrue(result)
|
||||
assertEquals(1, metadataFile.metadata.files.size)
|
||||
assertEquals("document.pdf", metadataFile.metadata.files.values.first().filename)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun verifyMetadataCounterTooOld() {
|
||||
val folder = OCFile("/e/")
|
||||
val enc1 = MockUser("enc1", "Nextcloud")
|
||||
val metadataFile = generateDecryptedFolderMetadataFile(enc1, enc1Cert)
|
||||
|
||||
val encrypted = encryptionUtilsV2.encryptFolderMetadataFile(
|
||||
metadataFile,
|
||||
enc1UserId,
|
||||
folder,
|
||||
storageManager,
|
||||
client,
|
||||
enc1PrivateKey,
|
||||
user,
|
||||
targetContext,
|
||||
arbitraryDataProvider
|
||||
)
|
||||
|
||||
val signature = encryptionUtilsV2.getMessageSignature(enc1Cert, enc1PrivateKey, encrypted)
|
||||
|
||||
// counter in metadata is 1, passing oldCounter=2 should fail
|
||||
val result = encryptionUtilsV2.verifyMetadata(encrypted, metadataFile, 2, signature)
|
||||
|
||||
assertFalse(result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun verifyMetadataInvalidSignature() {
|
||||
val folder = OCFile("/e/")
|
||||
val enc1 = MockUser("enc1", "Nextcloud")
|
||||
val metadataFile = generateDecryptedFolderMetadataFile(enc1, enc1Cert)
|
||||
|
||||
val encrypted = encryptionUtilsV2.encryptFolderMetadataFile(
|
||||
metadataFile,
|
||||
enc1UserId,
|
||||
folder,
|
||||
storageManager,
|
||||
client,
|
||||
enc1PrivateKey,
|
||||
user,
|
||||
targetContext,
|
||||
arbitraryDataProvider
|
||||
)
|
||||
|
||||
val signature = encryptionUtilsV2.getMessageSignature(enc1Cert, enc1PrivateKey, encrypted)
|
||||
|
||||
val tampered = encrypted.copy(
|
||||
metadata = encrypted.metadata.copy(ciphertext = encrypted.metadata.ciphertext.reversed())
|
||||
)
|
||||
|
||||
val result = encryptionUtilsV2.verifyMetadata(tampered, metadataFile, 0, signature)
|
||||
|
||||
assertFalse(result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun verifyMetadataChecksumMismatch() {
|
||||
val folder = OCFile("/e/")
|
||||
val enc1 = MockUser("enc1", "Nextcloud")
|
||||
val metadataFile = generateDecryptedFolderMetadataFile(enc1, enc1Cert)
|
||||
|
||||
val encrypted = encryptionUtilsV2.encryptFolderMetadataFile(
|
||||
metadataFile,
|
||||
enc1UserId,
|
||||
folder,
|
||||
storageManager,
|
||||
client,
|
||||
enc1PrivateKey,
|
||||
user,
|
||||
targetContext,
|
||||
arbitraryDataProvider
|
||||
)
|
||||
|
||||
// Replace the metadata key with a new one whose hash is NOT in keyChecksums
|
||||
metadataFile.metadata.metadataKey = EncryptionUtils.generateKey()
|
||||
|
||||
val signature = encryptionUtilsV2.getMessageSignature(enc1Cert, enc1PrivateKey, encrypted)
|
||||
|
||||
val result = encryptionUtilsV2.verifyMetadata(encrypted, metadataFile, 0, signature)
|
||||
|
||||
assertFalse(result)
|
||||
}
|
||||
|
||||
@Throws(Throwable::class)
|
||||
@Test
|
||||
|
||||
@@ -49,9 +49,10 @@
|
||||
-->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <!-- Runtime permissions introduced in Android 13 (API level 33) -->
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES"
|
||||
tools:ignore="PhotoAndVideoPolicy,SelectedPhotoAccess" />
|
||||
tools:ignore="PhotoAndVideoPolicy" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO"
|
||||
tools:ignore="PhotoAndVideoPolicy,SelectedPhotoAccess" /> <!-- Needed for Android 14 (API level 34) -->
|
||||
tools:ignore="PhotoAndVideoPolicy" /> <!-- Needed for Android 14 (API level 34) -->
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_VISUAL_USER_SELECTED" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<!--
|
||||
@@ -384,16 +385,20 @@
|
||||
android:theme="@style/PreferenceTheme" />
|
||||
<activity
|
||||
android:name=".ui.preview.PreviewImageActivity"
|
||||
android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation"
|
||||
android:exported="false"
|
||||
android:supportsPictureInPicture="true"
|
||||
android:launchMode="singleTask"
|
||||
android:theme="@style/Theme.ownCloud.Overlay" />
|
||||
<activity
|
||||
android:name=".ui.preview.PreviewMediaActivity"
|
||||
android:configChanges="orientation|screenLayout|screenSize|keyboardHidden"
|
||||
android:exported="false"
|
||||
android:theme="@style/Theme.ownCloud.Media" />
|
||||
android:name="com.nextcloud.client.player.ui.PlayerActivity"
|
||||
android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation"
|
||||
android:launchMode="singleTask"
|
||||
android:supportsPictureInPicture="true"
|
||||
android:theme="@style/Theme.ownCloud.NoActionBar" />
|
||||
|
||||
<service
|
||||
android:name="com.nextcloud.client.media.BackgroundPlayerService"
|
||||
android:name="com.nextcloud.client.player.media3.PlaybackService"
|
||||
android:exported="true"
|
||||
android:foregroundServiceType="mediaPlayback"
|
||||
tools:ignore="ExportedService">
|
||||
@@ -402,6 +407,13 @@
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<receiver android:name="androidx.media3.session.MediaButtonReceiver"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MEDIA_BUTTON" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<service
|
||||
android:name=".authentication.AccountAuthenticatorService"
|
||||
android:exported="false">
|
||||
@@ -555,11 +567,6 @@
|
||||
android:name="com.nextcloud.client.jobs.transfer.FileTransferService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync" />
|
||||
<service
|
||||
android:name="com.nextcloud.client.media.PlayerService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="mediaPlayback" />
|
||||
|
||||
<activity
|
||||
android:name=".ui.activity.PassCodeActivity"
|
||||
android:exported="false"
|
||||
|
||||
@@ -102,7 +102,10 @@ import com.owncloud.android.db.ProviderMeta
|
||||
// manual migration used for 99 to 100
|
||||
AutoMigration(from = 100, to = 101, spec = DatabaseMigrationUtil.ResetCapabilitiesPostMigration::class),
|
||||
AutoMigration(from = 101, to = 102, spec = DatabaseMigrationUtil.ResetCapabilitiesPostMigration::class),
|
||||
AutoMigration(from = 102, to = 103, spec = DatabaseMigrationUtil.ResetCapabilitiesPostMigration::class)
|
||||
AutoMigration(from = 102, to = 103, spec = DatabaseMigrationUtil.ResetCapabilitiesPostMigration::class),
|
||||
AutoMigration(from = 103, to = 104),
|
||||
AutoMigration(from = 104, to = 105),
|
||||
AutoMigration(from = 105, to = 106, spec = DatabaseMigrationUtil.ResetCapabilitiesPostMigration::class)
|
||||
],
|
||||
exportSchema = true
|
||||
)
|
||||
|
||||
@@ -71,7 +71,7 @@ interface FileDao {
|
||||
" AND file_owner = :fileOwner" +
|
||||
" AND path LIKE :pathPrefix || '%'" +
|
||||
" AND (:mimeFilter IS NULL OR content_type LIKE :mimeFilter)" +
|
||||
" ORDER BY modified DESC" +
|
||||
" ORDER BY modified DESC, ${ProviderTableMeta._ID} DESC" +
|
||||
" LIMIT :limit OFFSET :offset"
|
||||
)
|
||||
suspend fun getGalleryItemsPageSuspended(
|
||||
@@ -169,6 +169,17 @@ interface FileDao {
|
||||
)
|
||||
suspend fun getFavoriteFiles(fileOwner: String): List<FileEntity>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT *
|
||||
FROM filelist
|
||||
WHERE file_owner = :fileOwner
|
||||
AND favorite = 1
|
||||
ORDER BY ${ProviderTableMeta.FILE_DEFAULT_SORT_ORDER}
|
||||
"""
|
||||
)
|
||||
fun getFavoriteFilesNonBlocking(fileOwner: String): List<FileEntity>
|
||||
|
||||
@Query("SELECT remote_id FROM filelist WHERE file_owner = :accountName AND remote_id IS NOT NULL")
|
||||
fun getAllRemoteIds(accountName: String): List<String>
|
||||
|
||||
@@ -188,4 +199,10 @@ interface FileDao {
|
||||
|
||||
@Query("DELETE FROM filelist WHERE file_owner = :fileOwner AND path = :remotePath")
|
||||
fun deleteFileByRemotePath(fileOwner: String, remotePath: String): Int
|
||||
|
||||
@Query("UPDATE filelist SET is_read_only = :readOnly WHERE file_owner = :fileOwner AND path = :path")
|
||||
fun setReadOnly(fileOwner: String, path: String, readOnly: Int): Int
|
||||
|
||||
@Update
|
||||
fun updateAll(entities: List<FileEntity>)
|
||||
}
|
||||
@@ -95,9 +95,11 @@ interface UploadDao {
|
||||
SELECT * FROM ${ProviderTableMeta.UPLOADS_TABLE_NAME}
|
||||
WHERE ${ProviderTableMeta.UPLOADS_STATUS} = :status
|
||||
AND (:nameCollisionPolicy IS NULL OR ${ProviderTableMeta.UPLOADS_NAME_COLLISION_POLICY} = :nameCollisionPolicy)
|
||||
ORDER BY ${ProviderTableMeta._ID} DESC
|
||||
LIMIT :limit
|
||||
"""
|
||||
)
|
||||
suspend fun getUploadsByStatus(status: Int, nameCollisionPolicy: Int? = null): List<UploadEntity>
|
||||
suspend fun getUploadsByStatus(status: Int, nameCollisionPolicy: Int? = null, limit: Int): List<UploadEntity>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
@@ -105,11 +107,14 @@ interface UploadDao {
|
||||
WHERE ${ProviderTableMeta.UPLOADS_ACCOUNT_NAME} = :accountName
|
||||
AND ${ProviderTableMeta.UPLOADS_STATUS} = :status
|
||||
AND (:nameCollisionPolicy IS NULL OR ${ProviderTableMeta.UPLOADS_NAME_COLLISION_POLICY} = :nameCollisionPolicy)
|
||||
ORDER BY ${ProviderTableMeta._ID} DESC
|
||||
LIMIT :limit
|
||||
"""
|
||||
)
|
||||
suspend fun getUploadsByAccountNameAndStatus(
|
||||
accountName: String,
|
||||
status: Int,
|
||||
nameCollisionPolicy: Int? = null
|
||||
nameCollisionPolicy: Int? = null,
|
||||
limit: Int
|
||||
): List<UploadEntity>
|
||||
}
|
||||
@@ -157,7 +157,9 @@ data class CapabilityEntity(
|
||||
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_MOD_REWRITE_WORKING)
|
||||
val modRewriteWorking: Int?,
|
||||
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_CHUNKED_UPLOAD_MAX_SIZE)
|
||||
val chunkedUploadMaxSize: Long?
|
||||
val chunkedUploadMaxSize: Long?,
|
||||
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_JSON)
|
||||
val sharingJson: String?
|
||||
)
|
||||
|
||||
@Suppress("LongMethod", "ReturnCount")
|
||||
|
||||
@@ -121,5 +121,7 @@ data class FileEntity(
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_INTERNAL_TWO_WAY_SYNC_RESULT)
|
||||
val internalTwoWaySyncResult: String?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_UPLOADED)
|
||||
val uploaded: Long?
|
||||
val uploaded: Long?,
|
||||
@ColumnInfo(name = ProviderTableMeta.FILE_IS_READ_ONLY)
|
||||
val isReadOnly: Int?
|
||||
)
|
||||
@@ -9,10 +9,28 @@ package com.nextcloud.client.database.entity
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
|
||||
|
||||
@Entity(tableName = ProviderTableMeta.FILESYSTEM_TABLE_NAME)
|
||||
@Entity(
|
||||
tableName = ProviderTableMeta.FILESYSTEM_TABLE_NAME,
|
||||
indices = [
|
||||
Index(
|
||||
value = [
|
||||
ProviderTableMeta.FILESYSTEM_FILE_LOCAL_PATH,
|
||||
ProviderTableMeta.FILESYSTEM_SYNCED_FOLDER_ID
|
||||
]
|
||||
),
|
||||
Index(
|
||||
value = [
|
||||
ProviderTableMeta.FILESYSTEM_SYNCED_FOLDER_ID,
|
||||
ProviderTableMeta.FILESYSTEM_FILE_SENT_FOR_UPLOAD,
|
||||
ProviderTableMeta.FILESYSTEM_FILE_IS_FOLDER
|
||||
]
|
||||
)
|
||||
]
|
||||
)
|
||||
data class FilesystemEntity(
|
||||
@PrimaryKey(autoGenerate = true)
|
||||
@ColumnInfo(name = ProviderTableMeta._ID)
|
||||
|
||||
@@ -10,6 +10,7 @@ package com.nextcloud.client.database.entity
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
import com.nextcloud.utils.autoRename.AutoRename
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager
|
||||
@@ -21,7 +22,14 @@ import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.lib.resources.status.OCCapability
|
||||
import java.lang.IllegalArgumentException
|
||||
|
||||
@Entity(tableName = ProviderTableMeta.UPLOADS_TABLE_NAME)
|
||||
@Entity(
|
||||
tableName = ProviderTableMeta.UPLOADS_TABLE_NAME,
|
||||
indices = [
|
||||
Index(value = [ProviderTableMeta.UPLOADS_ACCOUNT_NAME, ProviderTableMeta.UPLOADS_STATUS]),
|
||||
Index(value = [ProviderTableMeta.UPLOADS_REMOTE_PATH, ProviderTableMeta.UPLOADS_ACCOUNT_NAME]),
|
||||
Index(value = [ProviderTableMeta.UPLOADS_ACCOUNT_NAME, ProviderTableMeta.UPLOADS_LOCAL_PATH])
|
||||
]
|
||||
)
|
||||
data class UploadEntity(
|
||||
@PrimaryKey(autoGenerate = true)
|
||||
@ColumnInfo(name = ProviderTableMeta._ID)
|
||||
|
||||
@@ -30,4 +30,6 @@ interface PowerManagementService {
|
||||
* Checks current battery status using platform [android.os.BatteryManager]
|
||||
*/
|
||||
val battery: BatteryStatus
|
||||
|
||||
val blocksAutoUpload: Boolean
|
||||
}
|
||||
@@ -38,10 +38,13 @@ internal class PowerManagementServiceImpl(
|
||||
return platformPowerManager.isPowerSaveMode
|
||||
}
|
||||
|
||||
override val blocksAutoUpload: Boolean
|
||||
get() = isPowerSavingEnabled && !isIgnoringOptimization
|
||||
|
||||
@Suppress("MagicNumber") // 100% is 100, we're not doing Cobol
|
||||
override val battery: BatteryStatus
|
||||
get() {
|
||||
val intent: Intent? = context.registerBroadcastReceiver(
|
||||
val intent = context.registerBroadcastReceiver(
|
||||
null,
|
||||
IntentFilter(Intent.ACTION_BATTERY_CHANGED),
|
||||
ReceiverFlag.NotExported
|
||||
@@ -54,7 +57,7 @@ internal class PowerManagementServiceImpl(
|
||||
else -> false
|
||||
}
|
||||
} ?: false
|
||||
val level = intent?.let { it ->
|
||||
val level = intent?.let {
|
||||
val level: Int = it.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
|
||||
val scale: Int = it.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
|
||||
(level * 100 / scale.toFloat()).toInt()
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2019 Chris Narkiewicz <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
|
||||
package com.nextcloud.client.di;
|
||||
|
||||
import android.app.Application;
|
||||
|
||||
import com.nextcloud.appReview.InAppReviewModule;
|
||||
import com.nextcloud.client.appinfo.AppInfoModule;
|
||||
import com.nextcloud.client.database.DatabaseModule;
|
||||
import com.nextcloud.client.device.DeviceModule;
|
||||
import com.nextcloud.client.integrations.IntegrationsModule;
|
||||
import com.nextcloud.client.jobs.JobsModule;
|
||||
import com.nextcloud.client.jobs.download.FileDownloadHelper;
|
||||
import com.nextcloud.client.jobs.offlineOperations.receiver.OfflineOperationReceiver;
|
||||
import com.nextcloud.client.jobs.folderDownload.FolderDownloadWorkerReceiver;
|
||||
import com.nextcloud.client.jobs.upload.FileUploadBroadcastReceiver;
|
||||
import com.nextcloud.client.jobs.upload.FileUploadHelper;
|
||||
import com.nextcloud.client.media.BackgroundPlayerService;
|
||||
import com.nextcloud.client.network.NetworkModule;
|
||||
import com.nextcloud.client.onboarding.OnboardingModule;
|
||||
import com.nextcloud.client.preferences.PreferencesModule;
|
||||
import com.owncloud.android.MainApp;
|
||||
import com.owncloud.android.media.MediaControlView;
|
||||
import com.owncloud.android.ui.ThemeableSwitchPreference;
|
||||
import com.owncloud.android.ui.whatsnew.ProgressIndicator;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import androidx.annotation.OptIn;
|
||||
import androidx.media3.common.util.UnstableApi;
|
||||
import dagger.BindsInstance;
|
||||
import dagger.Component;
|
||||
import dagger.android.support.AndroidSupportInjectionModule;
|
||||
|
||||
@Component(modules = {
|
||||
AndroidSupportInjectionModule.class,
|
||||
AppModule.class,
|
||||
PreferencesModule.class,
|
||||
AppInfoModule.class,
|
||||
NetworkModule.class,
|
||||
DeviceModule.class,
|
||||
OnboardingModule.class,
|
||||
ViewModelModule.class,
|
||||
JobsModule.class,
|
||||
IntegrationsModule.class,
|
||||
InAppReviewModule.class,
|
||||
ThemeModule.class,
|
||||
DatabaseModule.class,
|
||||
DispatcherModule.class,
|
||||
VariantModule.class,
|
||||
})
|
||||
@Singleton
|
||||
public interface AppComponent {
|
||||
|
||||
void inject(MainApp app);
|
||||
|
||||
void inject(MediaControlView mediaControlView);
|
||||
|
||||
@OptIn(markerClass = UnstableApi.class)
|
||||
void inject(BackgroundPlayerService backgroundPlayerService);
|
||||
|
||||
void inject(ThemeableSwitchPreference switchPreference);
|
||||
|
||||
void inject(FileUploadHelper fileUploadHelper);
|
||||
|
||||
void inject(FileDownloadHelper fileDownloadHelper);
|
||||
|
||||
void inject(ProgressIndicator progressIndicator);
|
||||
|
||||
void inject(FileUploadBroadcastReceiver fileUploadBroadcastReceiver);
|
||||
|
||||
void inject(OfflineOperationReceiver offlineOperationReceiver);
|
||||
|
||||
void inject(FolderDownloadWorkerReceiver folderDownloadWorkerReceiver);
|
||||
|
||||
@Component.Builder
|
||||
interface Builder {
|
||||
@BindsInstance
|
||||
Builder application(Application application);
|
||||
|
||||
AppComponent build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2019 Chris Narkiewicz <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.nextcloud.client.di
|
||||
|
||||
import android.app.Application
|
||||
import com.nextcloud.appReview.InAppReviewModule
|
||||
import com.nextcloud.client.appinfo.AppInfoModule
|
||||
import com.nextcloud.client.database.DatabaseModule
|
||||
import com.nextcloud.client.device.DeviceModule
|
||||
import com.nextcloud.client.integrations.IntegrationsModule
|
||||
import com.nextcloud.client.jobs.JobsModule
|
||||
import com.nextcloud.client.jobs.download.FileDownloadHelper
|
||||
import com.nextcloud.client.jobs.folderDownload.FolderDownloadWorkerReceiver
|
||||
import com.nextcloud.client.jobs.offlineOperations.receiver.OfflineOperationReceiver
|
||||
import com.nextcloud.client.jobs.upload.FileUploadBroadcastReceiver
|
||||
import com.nextcloud.client.jobs.upload.FileUploadHelper
|
||||
import com.nextcloud.client.network.NetworkModule
|
||||
import com.nextcloud.client.onboarding.OnboardingModule
|
||||
import com.nextcloud.client.player.PlayerModule
|
||||
import com.nextcloud.client.preferences.PreferencesModule
|
||||
import com.owncloud.android.MainApp
|
||||
import com.owncloud.android.ui.ThemeableSwitchPreference
|
||||
import com.owncloud.android.ui.whatsnew.ProgressIndicator
|
||||
import dagger.BindsInstance
|
||||
import dagger.Component
|
||||
import dagger.android.support.AndroidSupportInjectionModule
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Component(
|
||||
modules = [
|
||||
AndroidSupportInjectionModule::class,
|
||||
AppModule::class,
|
||||
PreferencesModule::class,
|
||||
AppInfoModule::class,
|
||||
NetworkModule::class,
|
||||
DeviceModule::class,
|
||||
OnboardingModule::class,
|
||||
ViewModelModule::class,
|
||||
JobsModule::class,
|
||||
IntegrationsModule::class,
|
||||
InAppReviewModule::class,
|
||||
ThemeModule::class,
|
||||
DatabaseModule::class,
|
||||
DispatcherModule::class,
|
||||
VariantModule::class,
|
||||
PlayerModule::class
|
||||
]
|
||||
)
|
||||
@Singleton
|
||||
interface AppComponent {
|
||||
fun inject(app: MainApp)
|
||||
|
||||
fun inject(switchPreference: ThemeableSwitchPreference)
|
||||
|
||||
fun inject(fileUploadHelper: FileUploadHelper)
|
||||
|
||||
fun inject(fileDownloadHelper: FileDownloadHelper)
|
||||
|
||||
fun inject(progressIndicator: ProgressIndicator)
|
||||
|
||||
fun inject(fileUploadBroadcastReceiver: FileUploadBroadcastReceiver)
|
||||
|
||||
fun inject(offlineOperationReceiver: OfflineOperationReceiver)
|
||||
|
||||
fun inject(folderDownloadWorkerReceiver: FolderDownloadWorkerReceiver)
|
||||
|
||||
@Component.Builder
|
||||
interface Builder {
|
||||
@BindsInstance
|
||||
fun application(application: Application): Builder
|
||||
|
||||
fun build(): AppComponent
|
||||
}
|
||||
}
|
||||
@@ -38,17 +38,21 @@ import com.nextcloud.client.migrations.MigrationsDb;
|
||||
import com.nextcloud.client.migrations.MigrationsManager;
|
||||
import com.nextcloud.client.migrations.MigrationsManagerImpl;
|
||||
import com.nextcloud.client.network.ClientFactory;
|
||||
import com.nextcloud.client.network.ConnectivityService;
|
||||
import com.nextcloud.client.notifications.AppNotificationManager;
|
||||
import com.nextcloud.client.notifications.AppNotificationManagerImpl;
|
||||
import com.nextcloud.client.preferences.AppPreferences;
|
||||
import com.nextcloud.client.utils.Throttler;
|
||||
import com.owncloud.android.providers.UsersAndGroupsSearchConfig;
|
||||
import com.nextcloud.utils.e2ee.E2EEActionResolver;
|
||||
import com.nextcloud.utils.e2ee.E2EEKeyInspector;
|
||||
import com.nextcloud.utils.thumbnail.FolderThumbnailGenerator;
|
||||
import com.owncloud.android.authentication.PassCodeManager;
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProvider;
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProviderImpl;
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager;
|
||||
import com.owncloud.android.datamodel.SyncedFolderProvider;
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager;
|
||||
import com.owncloud.android.providers.UsersAndGroupsSearchConfig;
|
||||
import com.owncloud.android.ui.activities.data.activities.ActivitiesRepository;
|
||||
import com.owncloud.android.ui.activities.data.activities.ActivitiesServiceApi;
|
||||
import com.owncloud.android.ui.activities.data.activities.ActivitiesServiceApiImpl;
|
||||
@@ -57,7 +61,6 @@ import com.owncloud.android.ui.activities.data.files.FilesRepository;
|
||||
import com.owncloud.android.ui.activities.data.files.FilesServiceApiImpl;
|
||||
import com.owncloud.android.ui.activities.data.files.RemoteFilesRepository;
|
||||
import com.owncloud.android.ui.dialog.setupEncryption.CertificateValidator;
|
||||
import com.nextcloud.utils.thumbnail.FolderThumbnailGenerator;
|
||||
import com.owncloud.android.utils.theme.ViewThemeUtils;
|
||||
|
||||
import org.greenrobot.eventbus.EventBus;
|
||||
@@ -280,4 +283,23 @@ class AppModule {
|
||||
return new FolderThumbnailGenerator(appPreferences, viewThemeUtils, context, accountManager);
|
||||
}
|
||||
|
||||
@Provides
|
||||
E2EEKeyInspector e2eeKeyInspector(
|
||||
Context context,
|
||||
FileDataStorageManager fileDataStorageManager,
|
||||
CertificateValidator certificateValidator,
|
||||
ArbitraryDataProvider arbitraryDataProvider,
|
||||
UserAccountManager accountManager) {
|
||||
return new E2EEKeyInspector(context, fileDataStorageManager, certificateValidator, arbitraryDataProvider, accountManager);
|
||||
}
|
||||
|
||||
@Provides
|
||||
E2EEActionResolver e2eeActionResolver(
|
||||
FileDataStorageManager fileDataStorageManager,
|
||||
ArbitraryDataProvider arbitraryDataProvider,
|
||||
UserAccountManager accountManager,
|
||||
ConnectivityService connectivityService,
|
||||
E2EEKeyInspector e2eeKeyInspector) {
|
||||
return new E2EEActionResolver(fileDataStorageManager, arbitraryDataProvider, accountManager, connectivityService, e2eeKeyInspector);
|
||||
}
|
||||
}
|
||||
@@ -18,8 +18,6 @@ import com.nextcloud.client.jobs.transfer.FileTransferService;
|
||||
import com.nextcloud.client.jobs.upload.FileUploadHelper;
|
||||
import com.nextcloud.client.logger.ui.LogsActivity;
|
||||
import com.nextcloud.client.logger.ui.LogsViewModel;
|
||||
import com.nextcloud.client.media.BackgroundPlayerService;
|
||||
import com.nextcloud.client.media.PlayerService;
|
||||
import com.nextcloud.client.migrations.Migrations;
|
||||
import com.nextcloud.client.onboarding.FirstRunActivity;
|
||||
import com.nextcloud.client.onboarding.WhatsNewActivity;
|
||||
@@ -81,7 +79,7 @@ import com.owncloud.android.ui.dialog.AppPassCodeDialog;
|
||||
import com.owncloud.android.ui.dialog.ChooseRichDocumentsTemplateDialogFragment;
|
||||
import com.owncloud.android.ui.dialog.ChooseTemplateDialogFragment;
|
||||
import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
|
||||
import com.owncloud.android.ui.dialog.ConflictsResolveDialog;
|
||||
import com.owncloud.android.ui.dialog.conflict.ConflictsResolveDialog;
|
||||
import com.owncloud.android.ui.dialog.CreateAlbumDialogFragment;
|
||||
import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
|
||||
import com.owncloud.android.ui.dialog.ExpirationDatePickerDialogFragment;
|
||||
@@ -129,8 +127,7 @@ import com.owncloud.android.ui.preview.FileDownloadFragment;
|
||||
import com.owncloud.android.ui.preview.PreviewBitmapActivity;
|
||||
import com.owncloud.android.ui.preview.PreviewImageActivity;
|
||||
import com.owncloud.android.ui.preview.PreviewImageFragment;
|
||||
import com.owncloud.android.ui.preview.PreviewMediaActivity;
|
||||
import com.owncloud.android.ui.preview.PreviewMediaFragment;
|
||||
import com.owncloud.android.ui.preview.PreviewPlaybackFragment;
|
||||
import com.owncloud.android.ui.preview.PreviewTextFileFragment;
|
||||
import com.owncloud.android.ui.preview.PreviewTextFragment;
|
||||
import com.owncloud.android.ui.preview.PreviewTextStringFragment;
|
||||
@@ -213,9 +210,6 @@ abstract class ComponentsModule {
|
||||
@ContributesAndroidInjector
|
||||
abstract PreviewImageActivity previewImageActivity();
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract PreviewMediaActivity previewMediaActivity();
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract ReceiveExternalFilesActivity receiveExternalFilesActivity();
|
||||
|
||||
@@ -297,9 +291,6 @@ abstract class ComponentsModule {
|
||||
@ContributesAndroidInjector
|
||||
abstract BackupListFragment chooseContactListFragment();
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract PreviewMediaFragment previewMediaFragment();
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract PreviewTextFragment previewTextFragment();
|
||||
|
||||
@@ -309,6 +300,9 @@ abstract class ComponentsModule {
|
||||
@ContributesAndroidInjector
|
||||
abstract SetOnlineStatusBottomSheet setOnlineStatusBottomSheet();
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract PreviewPlaybackFragment previewPlaybackFragment();
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract PreviewTextFileFragment previewTextFileFragment();
|
||||
|
||||
@@ -351,9 +345,6 @@ abstract class ComponentsModule {
|
||||
@ContributesAndroidInjector
|
||||
abstract OperationsService operationsService();
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract PlayerService playerService();
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract FileTransferService fileDownloaderService();
|
||||
|
||||
@@ -505,9 +496,6 @@ abstract class ComponentsModule {
|
||||
abstract InternalTwoWaySyncActivity internalTwoWaySyncActivity();
|
||||
|
||||
@OptIn(markerClass = UnstableApi.class)
|
||||
@ContributesAndroidInjector
|
||||
abstract BackgroundPlayerService backgroundPlayerService();
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract TermsOfServiceDialog termsOfServiceDialog();
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import androidx.lifecycle.ViewModelProvider
|
||||
import com.nextcloud.client.documentscan.DocumentScanViewModel
|
||||
import com.nextcloud.client.etm.EtmViewModel
|
||||
import com.nextcloud.client.logger.ui.LogsViewModel
|
||||
import com.nextcloud.client.player.ui.PlayerViewModel
|
||||
import com.nextcloud.ui.fileactions.FileActionsViewModel
|
||||
import com.nextcloud.ui.tags.TagManagementViewModel
|
||||
import com.nextcloud.ui.trashbinFileActions.TrashbinFileActionsViewModel
|
||||
@@ -63,6 +64,11 @@ abstract class ViewModelModule {
|
||||
@ViewModelKey(TagManagementViewModel::class)
|
||||
abstract fun tagManagementViewModel(vm: TagManagementViewModel): ViewModel
|
||||
|
||||
@Binds
|
||||
@IntoMap
|
||||
@ViewModelKey(PlayerViewModel::class)
|
||||
abstract fun playerViewModel(vm: PlayerViewModel): ViewModel
|
||||
|
||||
@Binds
|
||||
abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory
|
||||
}
|
||||
@@ -24,6 +24,8 @@ import com.nextcloud.client.documentscan.GeneratePDFUseCase
|
||||
import com.nextcloud.client.documentscan.GeneratePdfFromImagesWork
|
||||
import com.nextcloud.client.integrations.deck.DeckApi
|
||||
import com.nextcloud.client.jobs.autoUpload.AutoUploadHelper
|
||||
import com.nextcloud.client.jobs.autoUpload.AutoUploadLocalDeletionWorker
|
||||
import com.nextcloud.client.jobs.autoUpload.AutoUploadRescanWorker
|
||||
import com.nextcloud.client.jobs.autoUpload.AutoUploadWorker
|
||||
import com.nextcloud.client.jobs.autoUpload.FileSystemRepository
|
||||
import com.nextcloud.client.jobs.download.FileDownloadWorker
|
||||
@@ -93,6 +95,7 @@ class BackgroundJobFactory @Inject constructor(
|
||||
ContactsBackupWork::class -> createContactsBackupWork(context, workerParameters)
|
||||
ContactsImportWork::class -> createContactsImportWork(context, workerParameters)
|
||||
AutoUploadWorker::class -> createAutoUploadWorker(context, workerParameters)
|
||||
AutoUploadRescanWorker::class -> createAutoUploadRescanWorker(context, workerParameters)
|
||||
OfflineSyncWork::class -> createOfflineSyncWork(context, workerParameters)
|
||||
MediaFoldersDetectionWork::class -> createMediaFoldersDetectionWork(context, workerParameters)
|
||||
NotificationWork::class -> createNotificationWork(context, workerParameters)
|
||||
@@ -110,6 +113,7 @@ class BackgroundJobFactory @Inject constructor(
|
||||
InternalTwoWaySyncWork::class -> createInternalTwoWaySyncWork(context, workerParameters)
|
||||
MetadataWorker::class -> createMetadataWorker(context, workerParameters)
|
||||
FolderDownloadWorker::class -> createFolderDownloadWorker(context, workerParameters)
|
||||
AutoUploadLocalDeletionWorker::class -> createAutoUploadLocalDeletionWorker(context, workerParameters)
|
||||
else -> null // caller falls back to default factory
|
||||
}
|
||||
}
|
||||
@@ -192,9 +196,18 @@ class BackgroundJobFactory @Inject constructor(
|
||||
localBroadcastManager = localBroadcastManager.get(),
|
||||
autoUploadHelper = AutoUploadHelper(
|
||||
FileSystemRepository(dao = database.fileSystemDao(), uploadsStorageManager, context)
|
||||
)
|
||||
),
|
||||
preferences = preferences
|
||||
)
|
||||
|
||||
private fun createAutoUploadRescanWorker(context: Context, params: WorkerParameters): AutoUploadRescanWorker =
|
||||
AutoUploadRescanWorker(
|
||||
context = context,
|
||||
params = params,
|
||||
syncedFolderProvider = syncedFolderProvider,
|
||||
backgroundJobManager = backgroundJobManager.get()
|
||||
)
|
||||
|
||||
private fun createOfflineSyncWork(context: Context, params: WorkerParameters): OfflineSyncWork = OfflineSyncWork(
|
||||
context = context,
|
||||
params = params,
|
||||
@@ -328,4 +341,15 @@ class BackgroundJobFactory @Inject constructor(
|
||||
localBroadcastManager.get(),
|
||||
params
|
||||
)
|
||||
|
||||
private fun createAutoUploadLocalDeletionWorker(
|
||||
context: Context,
|
||||
params: WorkerParameters
|
||||
): AutoUploadLocalDeletionWorker = AutoUploadLocalDeletionWorker(
|
||||
context = context,
|
||||
params = params,
|
||||
userAccountManager = accountManager,
|
||||
syncedFolderProvider = syncedFolderProvider,
|
||||
viewThemeUtils = viewThemeUtils.get()
|
||||
)
|
||||
}
|
||||
@@ -147,6 +147,7 @@ interface BackgroundJobManager {
|
||||
fun cancelFilesUploadJob(user: User)
|
||||
fun isStartFileUploadJobScheduled(accountName: String): Boolean
|
||||
fun isAutoUploadIgnoringPowerSavingScheduled(syncedFolderID: Long): Boolean
|
||||
fun schedulePeriodicAutoUpload()
|
||||
fun cancelFilesDownloadJob(accountName: String, fileId: Long)
|
||||
|
||||
@Suppress("LongParameterList")
|
||||
@@ -177,4 +178,5 @@ interface BackgroundJobManager {
|
||||
fun startMetadataSyncJob(currentDirPath: String)
|
||||
fun downloadFolder(folder: OCFile, accountName: String)
|
||||
fun cancelFolderDownload()
|
||||
fun locallyDeleteAutoUploadedFiles(syncedFolders: List<SyncedFolder>)
|
||||
}
|
||||
@@ -28,6 +28,8 @@ import com.nextcloud.client.account.User
|
||||
import com.nextcloud.client.core.Clock
|
||||
import com.nextcloud.client.di.Injectable
|
||||
import com.nextcloud.client.documentscan.GeneratePdfFromImagesWork
|
||||
import com.nextcloud.client.jobs.autoUpload.AutoUploadLocalDeletionWorker
|
||||
import com.nextcloud.client.jobs.autoUpload.AutoUploadRescanWorker
|
||||
import com.nextcloud.client.jobs.autoUpload.AutoUploadWorker
|
||||
import com.nextcloud.client.jobs.download.FileDownloadWorker
|
||||
import com.nextcloud.client.jobs.folderDownload.FolderDownloadWorker
|
||||
@@ -37,6 +39,7 @@ import com.nextcloud.client.jobs.upload.AlbumFileUploadWorker
|
||||
import com.nextcloud.client.jobs.upload.FileUploadHelper
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker
|
||||
import com.nextcloud.client.jobs.worker.WorkerFilesPayload
|
||||
import com.nextcloud.client.network.SupportedNetworkTransports
|
||||
import com.nextcloud.client.preferences.AppPreferences
|
||||
import com.nextcloud.utils.extensions.isWorkScheduled
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
@@ -104,6 +107,7 @@ internal class BackgroundJobManagerImpl(
|
||||
const val JOB_DOWNLOAD_FOLDER = "download_folder"
|
||||
const val JOB_METADATA_SYNC = "metadata_sync"
|
||||
const val JOB_INTERNAL_TWO_WAY_SYNC = "internal_two_way_sync"
|
||||
const val JOB_AUTO_UPLOAD_LOCAL_DELETION = "auto_upload_local_deletion"
|
||||
|
||||
const val JOB_TEST = "test_job"
|
||||
|
||||
@@ -494,6 +498,16 @@ internal class BackgroundJobManagerImpl(
|
||||
override fun isAutoUploadIgnoringPowerSavingScheduled(syncedFolderID: Long): Boolean =
|
||||
workManager.isWorkScheduled(autoUploadIgnorePowerSavingTag(syncedFolderID))
|
||||
|
||||
override fun schedulePeriodicAutoUpload() {
|
||||
val request = periodicRequestBuilder(
|
||||
jobClass = AutoUploadRescanWorker::class,
|
||||
jobName = JOB_PERIODIC_FILES_SYNC,
|
||||
constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
|
||||
).build()
|
||||
|
||||
workManager.enqueueUniquePeriodicWork(JOB_PERIODIC_FILES_SYNC, ExistingPeriodicWorkPolicy.KEEP, request)
|
||||
}
|
||||
|
||||
override fun startAutoUpload(syncedFolder: SyncedFolder, overridePowerSaving: Boolean) {
|
||||
val syncedFolderID = syncedFolder.id
|
||||
|
||||
@@ -509,10 +523,7 @@ internal class BackgroundJobManagerImpl(
|
||||
.putLong(AutoUploadWorker.SYNCED_FOLDER_ID, syncedFolderID)
|
||||
.build()
|
||||
|
||||
val constraints = Constraints.Builder()
|
||||
.setRequiredNetworkType(NetworkType.CONNECTED)
|
||||
.setRequiresCharging(syncedFolder.isChargingOnly)
|
||||
.build()
|
||||
val constraints = SupportedNetworkTransports.getConstraints(requiresCharging = syncedFolder.isChargingOnly)
|
||||
|
||||
val requestBuilder = oneTimeRequestBuilder(
|
||||
jobClass = AutoUploadWorker::class,
|
||||
@@ -659,9 +670,7 @@ internal class BackgroundJobManagerImpl(
|
||||
val batches = uploadIds.toList().chunked(batchSize)
|
||||
val tag = startFileUploadJobTag(user.accountName)
|
||||
|
||||
val constraints = Constraints.Builder()
|
||||
.setRequiredNetworkType(NetworkType.CONNECTED)
|
||||
.build()
|
||||
val constraints = SupportedNetworkTransports.getConstraints()
|
||||
|
||||
val dataBuilder = Data.Builder()
|
||||
.putBoolean(
|
||||
@@ -905,4 +914,33 @@ internal class BackgroundJobManagerImpl(
|
||||
override fun cancelFolderDownload() {
|
||||
workManager.cancelAllWorkByTag(JOB_DOWNLOAD_FOLDER)
|
||||
}
|
||||
|
||||
override fun locallyDeleteAutoUploadedFiles(syncedFolders: List<SyncedFolder>) {
|
||||
val syncedFolderIDs = syncedFolders
|
||||
.filter { it.isEnabled }
|
||||
.map { it.id }
|
||||
|
||||
val arguments = Data.Builder()
|
||||
.putLongArray(AutoUploadLocalDeletionWorker.SYNCED_FOLDER_IDS, syncedFolderIDs.toLongArray())
|
||||
.build()
|
||||
|
||||
val constraints = Constraints.Builder()
|
||||
.setRequiredNetworkType(NetworkType.CONNECTED)
|
||||
.build()
|
||||
|
||||
val jobName = JOB_AUTO_UPLOAD_LOCAL_DELETION + "_" + syncedFolderIDs.joinToString("-")
|
||||
val request = oneTimeRequestBuilder(
|
||||
jobClass = AutoUploadLocalDeletionWorker::class,
|
||||
jobName = jobName
|
||||
)
|
||||
.setInputData(arguments)
|
||||
.setConstraints(constraints)
|
||||
.build()
|
||||
|
||||
workManager.enqueueUniqueWork(
|
||||
jobName,
|
||||
ExistingWorkPolicy.KEEP,
|
||||
request
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -72,7 +72,7 @@ class ContentObserverWork(
|
||||
}
|
||||
|
||||
private suspend fun checkAndTriggerAutoUpload() = withContext(Dispatchers.IO) {
|
||||
if (powerManagementService.isPowerSavingEnabled) {
|
||||
if (powerManagementService.blocksAutoUpload) {
|
||||
Log_OC.w(TAG, "⚡ Power saving mode active — skipping file sync.")
|
||||
return@withContext
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import android.util.Base64
|
||||
import androidx.core.app.ActivityCompat
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.net.toUri
|
||||
import androidx.work.Worker
|
||||
import androidx.work.WorkerParameters
|
||||
import com.google.gson.Gson
|
||||
@@ -314,7 +315,7 @@ class NotificationWork constructor(
|
||||
val actionType = intent.getStringExtra(KEY_NOTIFICATION_ACTION_TYPE)
|
||||
val actionLink = intent.getStringExtra(KEY_NOTIFICATION_ACTION_LINK)
|
||||
val success: Boolean = if (!actionType.isNullOrEmpty() && !actionLink.isNullOrEmpty()) {
|
||||
val resultCode = executeAction(actionType, actionLink, client)
|
||||
val resultCode = executeAction(actionType, actionLink, client, context)
|
||||
resultCode == HttpStatus.SC_OK || resultCode == HttpStatus.SC_ACCEPTED
|
||||
} else {
|
||||
DeleteNotificationRemoteOperation(numericNotificationId)
|
||||
@@ -341,9 +342,21 @@ class NotificationWork constructor(
|
||||
}
|
||||
|
||||
@Suppress("ReturnCount") // legacy code
|
||||
private fun executeAction(actionType: String, actionLink: String, client: OwnCloudClient): Int {
|
||||
val method: HttpMethod
|
||||
method = when (actionType) {
|
||||
private fun executeAction(
|
||||
actionType: String,
|
||||
actionLink: String,
|
||||
client: OwnCloudClient,
|
||||
context: Context
|
||||
): Int {
|
||||
if (actionType == "WEB") {
|
||||
val browserIntent = Intent(Intent.ACTION_VIEW, actionLink.toUri()).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}
|
||||
context.startActivity(browserIntent)
|
||||
return HttpStatus.SC_OK
|
||||
}
|
||||
|
||||
val method: HttpMethod = when (actionType) {
|
||||
"GET" -> GetMethod(actionLink)
|
||||
"POST" -> Utf8PostMethod(actionLink)
|
||||
"DELETE" -> DeleteMethod(actionLink)
|
||||
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Daniele Verducci <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.client.jobs.autoUpload
|
||||
|
||||
import android.app.Notification
|
||||
import android.content.Context
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import com.nextcloud.client.account.UserAccountManager
|
||||
import com.nextcloud.client.jobs.notification.WorkerNotificationManager
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager
|
||||
import com.owncloud.android.datamodel.SyncedFolderProvider
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.operations.upload.DeleteUploadedFileOperation
|
||||
import com.owncloud.android.ui.notifications.NotificationUtils
|
||||
import com.owncloud.android.utils.DisplayUtils
|
||||
import com.owncloud.android.utils.FileUtil
|
||||
import com.owncloud.android.utils.theme.ViewThemeUtils
|
||||
import java.io.File
|
||||
|
||||
class AutoUploadLocalDeletionWorker(
|
||||
private val context: Context,
|
||||
params: WorkerParameters,
|
||||
private val userAccountManager: UserAccountManager,
|
||||
private val syncedFolderProvider: SyncedFolderProvider,
|
||||
val viewThemeUtils: ViewThemeUtils
|
||||
) : CoroutineWorker(context, params) {
|
||||
|
||||
companion object {
|
||||
const val SYNCED_FOLDER_IDS = "synced_folder_IDs"
|
||||
const val NOTIFICATION_ID = 267
|
||||
const val MS_IN_SECOND = 1000
|
||||
|
||||
private const val TAG = "AutoUploadLocalDeletionWorker"
|
||||
}
|
||||
|
||||
private val notificationManager = WorkerNotificationManager(
|
||||
NOTIFICATION_ID,
|
||||
context,
|
||||
viewThemeUtils,
|
||||
R.string.autoupload_delete_uploaded_notif_ticker,
|
||||
NotificationUtils.NOTIFICATION_CHANNEL_BACKGROUND_OPERATIONS
|
||||
)
|
||||
|
||||
override suspend fun doWork(): Result {
|
||||
showNotification(
|
||||
createNotification(context.getString(R.string.autoupload_delete_uploaded_notif_started_title))
|
||||
)
|
||||
Log_OC.d(TAG, "Started")
|
||||
|
||||
val syncedFolderIDs = inputData.getLongArray(SYNCED_FOLDER_IDS)
|
||||
?: throw IllegalArgumentException("$SYNCED_FOLDER_IDS param is mandatory")
|
||||
val syncedFolders = syncedFolderIDs
|
||||
.map { syncedFolderProvider.getSyncedFolderByID(it) }
|
||||
|
||||
var users = HashSet<String>()
|
||||
var filesPreserved = 0L
|
||||
var foldersAnalyzed = 0L
|
||||
var filesRemoved = 0L
|
||||
var spaceFreed = 0L
|
||||
val timeStarted = System.currentTimeMillis()
|
||||
syncedFolders
|
||||
.filterNotNull()
|
||||
.filter { it.isEnabled }
|
||||
.filter { FileUtil.isFolderWritable(File(it.localPath)) }
|
||||
.forEach {
|
||||
val sharedFolderOwner = userAccountManager.getUser(it.account).get()
|
||||
users.add(sharedFolderOwner.accountName)
|
||||
val fileDataStorageManager = FileDataStorageManager(sharedFolderOwner, context.contentResolver)
|
||||
val op = DeleteUploadedFileOperation(
|
||||
it,
|
||||
context,
|
||||
fileDataStorageManager
|
||||
)
|
||||
val res = op.run()
|
||||
if (res.code != RemoteOperationResult.ResultCode.OK) {
|
||||
Log_OC.d(TAG, "Failed")
|
||||
showNotification(
|
||||
createNotification(context.getString(R.string.autoupload_delete_uploaded_notif_error_title))
|
||||
)
|
||||
return Result.failure()
|
||||
}
|
||||
foldersAnalyzed++
|
||||
filesPreserved += res.resultData.filesPreserved
|
||||
filesRemoved += res.resultData.filesRemoved
|
||||
spaceFreed += res.resultData.spaceFreed
|
||||
}
|
||||
|
||||
val runTimeMs = System.currentTimeMillis() - timeStarted
|
||||
showNotification(
|
||||
createSuccessNotification(
|
||||
users.size,
|
||||
foldersAnalyzed,
|
||||
filesRemoved,
|
||||
filesPreserved,
|
||||
spaceFreed,
|
||||
runTimeMs
|
||||
)
|
||||
)
|
||||
Log_OC.d(
|
||||
TAG,
|
||||
"Success: users=$users, foldersAnalyzed=$foldersAnalyzed, filesPreserved=$filesPreserved, " +
|
||||
"filesRemoved=$filesRemoved, spaceFreed=$spaceFreed bytes, runTime=${runTimeMs / MS_IN_SECOND} seconds"
|
||||
)
|
||||
return Result.success()
|
||||
}
|
||||
|
||||
private fun createSuccessNotification(
|
||||
users: Int,
|
||||
foldersRemoved: Long,
|
||||
filesRemoved: Long,
|
||||
filesPreserved: Long,
|
||||
spaceFreed: Long,
|
||||
timeElapsed: Long
|
||||
): Notification {
|
||||
val notificationContent = context.getString(
|
||||
R.string.autoupload_delete_uploaded_notif_ended_content,
|
||||
DisplayUtils.bytesToHumanReadable(spaceFreed),
|
||||
context.resources.getQuantityString(
|
||||
R.plurals.autoupload_delete_uploaded_notif_ended_content_files,
|
||||
filesRemoved.toInt(),
|
||||
filesRemoved
|
||||
),
|
||||
context.resources.getQuantityString(
|
||||
R.plurals.autoupload_delete_uploaded_notif_ended_content_folders,
|
||||
foldersRemoved.toInt(),
|
||||
foldersRemoved
|
||||
),
|
||||
context.resources.getQuantityString(
|
||||
R.plurals.autoupload_delete_uploaded_notif_ended_content_users,
|
||||
users,
|
||||
users
|
||||
)
|
||||
)
|
||||
return createNotification(
|
||||
title = context.getString(R.string.autoupload_delete_uploaded_notif_ended_title),
|
||||
content = notificationContent
|
||||
)
|
||||
}
|
||||
|
||||
private fun createNotification(title: String, content: String? = null): Notification =
|
||||
notificationManager.notificationBuilder
|
||||
.setContentTitle(title)
|
||||
.setContentText(content)
|
||||
.setSmallIcon(R.drawable.ic_delete)
|
||||
.setSound(null)
|
||||
.setVibrate(null)
|
||||
.setOnlyAlertOnce(true)
|
||||
.setSilent(true)
|
||||
.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_BACKGROUND_OPERATIONS)
|
||||
.build()
|
||||
|
||||
private fun showNotification(notification: Notification) = notificationManager.showNotification()
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.client.jobs.autoUpload
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import com.nextcloud.client.jobs.BackgroundJobManager
|
||||
import com.owncloud.android.datamodel.SyncedFolderProvider
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.utils.FilesSyncHelper
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class AutoUploadRescanWorker(
|
||||
context: Context,
|
||||
params: WorkerParameters,
|
||||
private val syncedFolderProvider: SyncedFolderProvider,
|
||||
private val backgroundJobManager: BackgroundJobManager
|
||||
) : CoroutineWorker(context, params) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "🔄📤" + "AutoUploadRescan"
|
||||
}
|
||||
|
||||
override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
|
||||
val requestedFolders = FilesSyncHelper.startAutoUploadForEnabledSyncedFolders(
|
||||
syncedFolderProvider,
|
||||
backgroundJobManager,
|
||||
false
|
||||
)
|
||||
|
||||
Log_OC.d(TAG, "requested auto upload for $requestedFolders folder(s)")
|
||||
|
||||
Result.success()
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import com.nextcloud.client.jobs.upload.FileUploadWorker
|
||||
import com.nextcloud.client.jobs.upload.UploadDelayPolicy
|
||||
import com.nextcloud.client.jobs.utils.UploadErrorNotificationManager
|
||||
import com.nextcloud.client.network.ConnectivityService
|
||||
import com.nextcloud.client.preferences.AppPreferences
|
||||
import com.nextcloud.utils.extensions.getLog
|
||||
import com.nextcloud.utils.extensions.isConflict
|
||||
import com.nextcloud.utils.extensions.isNonRetryable
|
||||
@@ -54,6 +55,7 @@ import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import kotlin.coroutines.cancellation.CancellationException
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
|
||||
@Suppress("LongParameterList", "TooManyFunctions", "TooGenericExceptionCaught")
|
||||
class AutoUploadWorker(
|
||||
@@ -67,7 +69,8 @@ class AutoUploadWorker(
|
||||
private val repository: FileSystemRepository,
|
||||
val viewThemeUtils: ViewThemeUtils,
|
||||
localBroadcastManager: LocalBroadcastManager,
|
||||
private val autoUploadHelper: AutoUploadHelper
|
||||
private val autoUploadHelper: AutoUploadHelper,
|
||||
private val preferences: AppPreferences
|
||||
) : CoroutineWorker(context, params) {
|
||||
|
||||
companion object {
|
||||
@@ -98,7 +101,7 @@ class AutoUploadWorker(
|
||||
|
||||
Log_OC.d(TAG, syncedFolder.getLog())
|
||||
|
||||
if (canExitEarly(syncFolderId)) {
|
||||
if (isBlocked(syncFolderId)) {
|
||||
return Result.success()
|
||||
}
|
||||
|
||||
@@ -106,8 +109,14 @@ class AutoUploadWorker(
|
||||
Log_OC.w(TAG, "power saving mode enabled - override power saving: $overridePowerSaving")
|
||||
}
|
||||
|
||||
// insert entries based on selected local storage path
|
||||
// The scan has to run before the scan interval decides there is nothing to do, otherwise files added
|
||||
// since the previous run stay invisible until some other trigger happens to scan them in.
|
||||
autoUploadHelper.insertEntries(syncedFolder)
|
||||
|
||||
if (hasNothingToDo()) {
|
||||
return Result.success()
|
||||
}
|
||||
|
||||
uploadFiles(syncedFolder)
|
||||
|
||||
// only update last scan time after uploading files
|
||||
@@ -187,38 +196,44 @@ class AutoUploadWorker(
|
||||
}
|
||||
|
||||
@Suppress("ReturnCount")
|
||||
private suspend fun canExitEarly(syncedFolderID: Long): Boolean {
|
||||
if ((powerManagementService.isPowerSavingEnabled && !overridePowerSaving)) {
|
||||
private fun isBlocked(syncedFolderID: Long): Boolean {
|
||||
if (powerManagementService.blocksAutoUpload && !overridePowerSaving) {
|
||||
Log_OC.w(TAG, "⚡ Skipping: device is in power saving mode")
|
||||
return true
|
||||
}
|
||||
|
||||
if (preferences.isGlobalUploadPaused) {
|
||||
Log_OC.w(TAG, "⏸️ Skipping: uploads are paused")
|
||||
return true
|
||||
}
|
||||
|
||||
if (syncedFolderID < 0) {
|
||||
Log_OC.e(TAG, "invalid sync folder id")
|
||||
return true
|
||||
}
|
||||
|
||||
val hasPendingFiles = repository.hasPendingFiles(syncedFolder)
|
||||
if (hasPendingFiles) {
|
||||
return false
|
||||
}
|
||||
|
||||
private suspend fun hasNothingToDo(): Boolean {
|
||||
if (repository.hasPendingFiles(syncedFolder)) {
|
||||
Log_OC.d(TAG, "pending files found, starting...")
|
||||
return false
|
||||
}
|
||||
|
||||
val totalScanInterval = syncedFolder.getTotalScanInterval(connectivityService, powerManagementService)
|
||||
val currentTime = System.currentTimeMillis()
|
||||
val passedScanInterval = totalScanInterval <= currentTime
|
||||
val waitingForScanInterval = totalScanInterval > System.currentTimeMillis() && !overridePowerSaving
|
||||
|
||||
if (!passedScanInterval && !overridePowerSaving) {
|
||||
if (waitingForScanInterval) {
|
||||
Log_OC.w(
|
||||
TAG,
|
||||
"skipped since started before scan interval and nothing todo: " + syncedFolder.localPath
|
||||
)
|
||||
return true
|
||||
} else {
|
||||
Log_OC.d(TAG, "starting ...")
|
||||
}
|
||||
|
||||
Log_OC.d(TAG, "starting ...")
|
||||
|
||||
return false
|
||||
return waitingForScanInterval
|
||||
}
|
||||
|
||||
private fun getUserOrReturn(syncedFolder: SyncedFolder): User? {
|
||||
@@ -277,18 +292,29 @@ class AutoUploadWorker(
|
||||
filePathsWithIds.forEachIndexed { batchIndex, (path, id) ->
|
||||
ensureActive()
|
||||
|
||||
delay(retryPolicy.getDelay())
|
||||
if (preferences.isGlobalUploadPaused) {
|
||||
Log_OC.w(TAG, "⏸️ uploads paused, stopping auto upload")
|
||||
return@withContext
|
||||
}
|
||||
|
||||
delay(retryPolicy.getDelay().milliseconds)
|
||||
|
||||
val file = File(path)
|
||||
val localPath = file.absolutePath
|
||||
val remotePath = syncFolderHelper.getAutoUploadRemotePath(syncedFolder, file)
|
||||
|
||||
try {
|
||||
// A camera app can register the file with MediaStore before it finished writing it.
|
||||
if (file.isFile && file.length() == 0L) {
|
||||
Log_OC.w(TAG, "skipping empty file, still being written: $localPath")
|
||||
return@forEachIndexed
|
||||
}
|
||||
|
||||
val entityResult = getEntityResult(user, localPath, remotePath, capability)
|
||||
if (entityResult !is AutoUploadEntityResult.Success) {
|
||||
repository.markFileAsHandled(localPath, syncedFolder)
|
||||
Log_OC.d(TAG, "marked file as handled: $localPath")
|
||||
continue
|
||||
return@forEachIndexed
|
||||
}
|
||||
|
||||
var (uploadEntity, upload) = entityResult.data
|
||||
@@ -297,7 +323,7 @@ class AutoUploadWorker(
|
||||
if (path.isEmpty() || !file.exists()) {
|
||||
Log_OC.w(TAG, "detected non-existing local file, removing entity")
|
||||
deleteNonExistingFile(path, id, upload)
|
||||
continue
|
||||
return@forEachIndexed
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -311,7 +337,12 @@ class AutoUploadWorker(
|
||||
val operation = createUploadFileOperation(upload, user)
|
||||
Log_OC.d(TAG, "🕒 uploading: $localPath, id: $generatedId")
|
||||
|
||||
val result = operation.execute(client)
|
||||
FileUploadWorker.registerActiveUpload(operation)
|
||||
val result = try {
|
||||
operation.execute(client)
|
||||
} finally {
|
||||
FileUploadWorker.unregisterActiveUpload(operation.ocUploadId)
|
||||
}
|
||||
fileUploadEventBroadcaster.sendUploadStarted(operation, context)
|
||||
|
||||
UploadErrorNotificationManager.handleResult(
|
||||
@@ -363,7 +394,7 @@ class AutoUploadWorker(
|
||||
if (path.isEmpty() || !file.exists()) {
|
||||
Log_OC.w(TAG, "detected non-existing local file, removing entity")
|
||||
deleteNonExistingFile(path, id, upload)
|
||||
continue
|
||||
return@forEachIndexed
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
@@ -385,6 +416,15 @@ class AutoUploadWorker(
|
||||
uploadsStorageManager.removeUpload(upload)
|
||||
}
|
||||
|
||||
private fun isResolvedByCurrentCollisionPolicy(lastUploadResult: UploadResult): Boolean {
|
||||
val conflictResults = setOf(
|
||||
UploadResult.SYNC_CONFLICT,
|
||||
UploadResult.CONFLICT_ERROR
|
||||
)
|
||||
|
||||
return lastUploadResult in conflictResults && syncedFolder.nameCollisionPolicy != NameCollisionPolicy.ASK_USER
|
||||
}
|
||||
|
||||
@Suppress("ReturnCount")
|
||||
private fun getEntityResult(
|
||||
user: User,
|
||||
@@ -403,7 +443,7 @@ class AutoUploadWorker(
|
||||
)
|
||||
|
||||
val lastUploadResult = uploadEntity?.lastResult?.let { UploadResult.fromValue(it) }
|
||||
if (lastUploadResult?.isNonRetryable() == true) {
|
||||
if (lastUploadResult?.isNonRetryable() == true && !isResolvedByCurrentCollisionPolicy(lastUploadResult)) {
|
||||
Log_OC.w(
|
||||
TAG,
|
||||
"last upload failed with ${lastUploadResult.value}, skipping auto-upload: $localPath"
|
||||
@@ -458,7 +498,7 @@ class AutoUploadWorker(
|
||||
true,
|
||||
FileDataStorageManager(user, context.contentResolver)
|
||||
).apply {
|
||||
if (overridePowerSaving) {
|
||||
if (overridePowerSaving || !powerManagementService.blocksAutoUpload) {
|
||||
isIgnoringPowerSaveMode = true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,14 @@ class SyncFolderHelper(private val context: Context) {
|
||||
private const val TAG = "SyncFolderHelper"
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the auto upload remote path for a given file based on the current syncedFolder folder settings.
|
||||
* Note that if the user changed the syncedFolder's settings after the file was already uploaded,
|
||||
* this may not reflect the actual uploaded file's path.
|
||||
* @param syncedFolder containing the file
|
||||
* @param file contained in the syncedFolder
|
||||
* @return the remote path based on the current syncedFolder folder settings
|
||||
*/
|
||||
fun getAutoUploadRemotePath(syncedFolder: SyncedFolder, file: File): String {
|
||||
val resources = context.resources
|
||||
val isLightVersion = resources.getBoolean(R.bool.syncedFolder_light)
|
||||
|
||||
@@ -15,15 +15,14 @@ import android.provider.MediaStore
|
||||
import android.util.Size
|
||||
import android.view.WindowManager
|
||||
import android.widget.ImageView
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.nextcloud.client.account.User
|
||||
import com.nextcloud.utils.extensions.getBigThumbnail
|
||||
import com.nextcloud.utils.extensions.getBigThumbnailKey
|
||||
import com.nextcloud.utils.extensions.getSmallThumbnail
|
||||
import com.nextcloud.utils.extensions.isPNG
|
||||
import com.nextcloud.utils.extensions.setMediaThumbnail
|
||||
import com.nextcloud.utils.extensions.toFile
|
||||
import com.owncloud.android.MainApp
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.datamodel.ThumbnailsCacheManager
|
||||
@@ -98,43 +97,40 @@ class GalleryImageGenerationJob(private val user: User, private val storageManag
|
||||
return
|
||||
}
|
||||
|
||||
var newImage = false
|
||||
val bitmap: Bitmap? = getBitmap(file, onNewThumbnail = { newImage = true })
|
||||
val bitmap: Bitmap? = getBitmap(file)
|
||||
|
||||
if (bitmap == null) {
|
||||
withContext(Dispatchers.Main) { listener.onError() }
|
||||
return
|
||||
}
|
||||
|
||||
setThumbnail(bitmap, file, imageView, newImage, listener)
|
||||
setThumbnail(bitmap, file, imageView, listener)
|
||||
} catch (_: Exception) {
|
||||
withContext(Dispatchers.Main) { listener.onError() }
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun getBitmap(file: OCFile, onNewThumbnail: () -> Unit): Bitmap? = withContext(Dispatchers.IO) {
|
||||
private suspend fun getBitmap(file: OCFile): Bitmap? = withContext(Dispatchers.IO) {
|
||||
val cached = file.getBigThumbnail()
|
||||
if (cached != null && !file.isUpdateThumbnailNeeded) {
|
||||
return@withContext applyVideoOverlayIfNeeded(file, cached)
|
||||
return@withContext cached
|
||||
}
|
||||
|
||||
if (file.isDown) {
|
||||
val local = decodeLocalThumbnail(file)
|
||||
if (local != null) {
|
||||
ThumbnailsCacheManager.addBitmapToCache(file.getBigThumbnailKey(), local)
|
||||
onNewThumbnail()
|
||||
return@withContext applyVideoOverlayIfNeeded(file, local)
|
||||
return@withContext local
|
||||
}
|
||||
}
|
||||
|
||||
val remote = semaphore.withPermit { fetchFromServer(file) }
|
||||
if (remote != null) {
|
||||
onNewThumbnail()
|
||||
return@withContext applyVideoOverlayIfNeeded(file, remote)
|
||||
return@withContext remote
|
||||
}
|
||||
|
||||
file.getSmallThumbnail()?.let { small ->
|
||||
return@withContext applyVideoOverlayIfNeeded(file, small)
|
||||
return@withContext small
|
||||
}
|
||||
|
||||
null
|
||||
@@ -196,34 +192,16 @@ class GalleryImageGenerationJob(private val user: User, private val storageManag
|
||||
null
|
||||
}
|
||||
|
||||
private fun applyVideoOverlayIfNeeded(file: OCFile, bitmap: Bitmap): Bitmap = if (MimeTypeUtil.isVideo(file)) {
|
||||
ThumbnailsCacheManager.addVideoOverlay(bitmap, MainApp.getAppContext())
|
||||
} else {
|
||||
bitmap
|
||||
}
|
||||
|
||||
private suspend fun setThumbnail(
|
||||
bitmap: Bitmap,
|
||||
file: OCFile,
|
||||
imageView: ImageView,
|
||||
newImage: Boolean,
|
||||
listener: GalleryImageGenerationListener
|
||||
) = withContext(Dispatchers.Main) {
|
||||
val tagId = file.fileId.toString()
|
||||
|
||||
if (imageView.tag.toString() == tagId) {
|
||||
if (file.isPNG()) {
|
||||
imageView.setBackgroundColor(
|
||||
ContextCompat.getColor(MainApp.getAppContext(), R.color.bg_default)
|
||||
)
|
||||
}
|
||||
|
||||
if (newImage) listener.onNewGalleryImage()
|
||||
|
||||
if (imageView.isAttachedToWindow) {
|
||||
imageView.setImageBitmap(bitmap)
|
||||
imageView.invalidate()
|
||||
}
|
||||
if (imageView.tag.toString() == tagId && imageView.isAttachedToWindow) {
|
||||
imageView.setMediaThumbnail(file, bitmap)
|
||||
}
|
||||
|
||||
listener.onSuccess()
|
||||
|
||||
@@ -9,6 +9,5 @@ package com.nextcloud.client.jobs.gallery
|
||||
|
||||
interface GalleryImageGenerationListener {
|
||||
fun onSuccess()
|
||||
fun onNewGalleryImage()
|
||||
fun onError()
|
||||
}
|
||||
+2
-9
@@ -18,6 +18,7 @@ import com.nextcloud.client.network.ConnectivityService
|
||||
import com.nextcloud.model.OfflineOperationType
|
||||
import com.nextcloud.model.WorkerState
|
||||
import com.nextcloud.model.WorkerStateObserver
|
||||
import com.nextcloud.utils.extensions.isNetworkAndServerAvailableSuspended
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.lib.common.OwnCloudClient
|
||||
@@ -35,8 +36,6 @@ import com.owncloud.android.utils.MimeTypeUtil
|
||||
import com.owncloud.android.utils.theme.ViewThemeUtils
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.suspendCoroutine
|
||||
|
||||
private typealias OfflineOperationResult = Pair<RemoteOperationResult<*>?, RemoteOperation<*>?>?
|
||||
|
||||
@@ -67,7 +66,7 @@ class OfflineOperationsWorker(
|
||||
Log_OC.d(TAG, "[$jobName] OfflineOperationsWorker started for user: ${user.accountName}")
|
||||
|
||||
// check network connection
|
||||
if (!isNetworkAndServerAvailable()) {
|
||||
if (!connectivityService.isNetworkAndServerAvailableSuspended()) {
|
||||
Log_OC.w(TAG, "⚠️ No internet/server connection. Retrying later...")
|
||||
return@withContext Result.retry()
|
||||
}
|
||||
@@ -161,12 +160,6 @@ class OfflineOperationsWorker(
|
||||
}
|
||||
// endregion
|
||||
|
||||
private suspend fun isNetworkAndServerAvailable(): Boolean = suspendCoroutine { continuation ->
|
||||
connectivityService.isNetworkAndServerAvailable { result ->
|
||||
continuation.resume(result)
|
||||
}
|
||||
}
|
||||
|
||||
// region Operation Execution
|
||||
@Suppress("ComplexCondition", "LongMethod")
|
||||
private suspend fun executeOperation(
|
||||
|
||||
@@ -104,6 +104,14 @@ class AlbumFileUploadWorker(
|
||||
}
|
||||
}
|
||||
|
||||
fun pauseActiveUploads() {
|
||||
activeOperations.values.forEach {
|
||||
Log_OC.d(TAG, "upload operation is paused: ${it.remotePath}")
|
||||
it.pause()
|
||||
}
|
||||
activeOperations.clear()
|
||||
}
|
||||
|
||||
fun getCurrentUpload(id: Long?): UploadFileOperation? = activeOperations[id]
|
||||
|
||||
fun isUploading(remotePath: String?, accountName: String?): Boolean = activeOperations.values.any {
|
||||
|
||||
@@ -90,6 +90,8 @@ class FileUploadHelper {
|
||||
|
||||
const val MAX_FILE_COUNT = 500
|
||||
|
||||
const val MAX_UPLOADS_PER_QUERY = 500
|
||||
|
||||
val mBoundListeners = HashMap<String, OnDatatransferProgressListener>()
|
||||
|
||||
private val retryInProgress = AtomicBoolean(false)
|
||||
@@ -377,6 +379,10 @@ class FileUploadHelper {
|
||||
* If `null`, uploads matching the given [status] from all accounts are returned.
|
||||
* @param status The [UploadStatus] to filter uploads by (e.g., `UPLOAD_FAILED`).
|
||||
* @param nameCollisionPolicy The [NameCollisionPolicy] to filter uploads by (e.g., `SKIP`).
|
||||
*
|
||||
* At most [MAX_UPLOADS_PER_QUERY] of the newest uploads are returned. A history that grew into the tens of
|
||||
* thousands of rows cannot be held in memory at once, and neither the upload list nor a retry pass needs more
|
||||
* than a page of it.
|
||||
*/
|
||||
suspend fun getUploadsByStatus(
|
||||
accountName: String?,
|
||||
@@ -386,9 +392,14 @@ class FileUploadHelper {
|
||||
): List<OCUpload> {
|
||||
val dao = uploadsStorageManager.uploadDao
|
||||
return if (accountName != null) {
|
||||
dao.getUploadsByAccountNameAndStatus(accountName, status.value, nameCollisionPolicy?.serialize())
|
||||
dao.getUploadsByAccountNameAndStatus(
|
||||
accountName,
|
||||
status.value,
|
||||
nameCollisionPolicy?.serialize(),
|
||||
MAX_UPLOADS_PER_QUERY
|
||||
)
|
||||
} else {
|
||||
dao.getUploadsByStatus(status.value, nameCollisionPolicy?.serialize())
|
||||
dao.getUploadsByStatus(status.value, nameCollisionPolicy?.serialize(), MAX_UPLOADS_PER_QUERY)
|
||||
}.mapNotNull {
|
||||
it.toOCUpload(capability)
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ import com.nextcloud.client.preferences.AppPreferences
|
||||
import com.nextcloud.utils.ForegroundServiceHelper
|
||||
import com.nextcloud.utils.extensions.getPercent
|
||||
import com.nextcloud.utils.extensions.isNonRetryable
|
||||
import com.nextcloud.utils.extensions.isUserCancellation
|
||||
import com.nextcloud.utils.extensions.toFile
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.ForegroundServiceType
|
||||
@@ -119,12 +120,33 @@ class FileUploadWorker(
|
||||
}
|
||||
}
|
||||
|
||||
fun pauseActiveUploads() {
|
||||
activeOperations.values.forEach {
|
||||
Log_OC.d(TAG, "upload operation is paused: ${it.remotePath}")
|
||||
it.pause()
|
||||
}
|
||||
activeOperations.clear()
|
||||
}
|
||||
|
||||
fun getCurrentUpload(id: Long?): UploadFileOperation? = activeOperations[id]
|
||||
|
||||
fun isUploading(remotePath: String?, accountName: String?): Boolean = activeOperations.values.any {
|
||||
it.remotePath == remotePath && it.user.accountName == accountName
|
||||
}
|
||||
|
||||
/**
|
||||
* [activeOperations] tracks every upload running in this process, not only the ones this worker started.
|
||||
* Auto upload has to register here too, otherwise a retry pass sees its in-progress row as abandoned and
|
||||
* reschedules it, and the cancel action in the upload list has nothing to cancel.
|
||||
*/
|
||||
fun registerActiveUpload(operation: UploadFileOperation) {
|
||||
activeOperations[operation.ocUploadId] = operation
|
||||
}
|
||||
|
||||
fun unregisterActiveUpload(uploadId: Long) {
|
||||
activeOperations.remove(uploadId)
|
||||
}
|
||||
|
||||
fun getUploadAction(action: String): Int = when (action) {
|
||||
"LOCAL_BEHAVIOUR_FORGET" -> LOCAL_BEHAVIOUR_FORGET
|
||||
"LOCAL_BEHAVIOUR_MOVE" -> LOCAL_BEHAVIOUR_MOVE
|
||||
@@ -277,6 +299,11 @@ class FileUploadWorker(
|
||||
continue
|
||||
}
|
||||
|
||||
if (isUploading(upload.remotePath, accountName)) {
|
||||
Log_OC.d(TAG, "skipping upload, another worker is still transferring it: ${upload.remotePath}")
|
||||
continue
|
||||
}
|
||||
|
||||
delay(retryPolicy.getDelay().milliseconds)
|
||||
|
||||
if (!skipAutoUploadCheck && isBelongToAnySyncedFolder(upload, syncFolderHelper, syncedFolders)) {
|
||||
@@ -326,11 +353,9 @@ class FileUploadWorker(
|
||||
break
|
||||
}
|
||||
|
||||
// check upload result for worker
|
||||
val uploadResult = UploadResult.fromOperationResult(result)
|
||||
if (!result.isSuccess) {
|
||||
if (!result.isSuccess && !result.code.isUserCancellation()) {
|
||||
Log_OC.e(TAG, "upload failed for ${upload.remotePath}: ${result.code}")
|
||||
if (uploadResult.isNonRetryable()) {
|
||||
if (UploadResult.fromOperationResult(result).isNonRetryable()) {
|
||||
hasNonRetryableFailure = true
|
||||
} else {
|
||||
hasRetryableFailure = true
|
||||
@@ -355,7 +380,7 @@ class FileUploadWorker(
|
||||
}
|
||||
|
||||
private fun skip(upload: OCUpload): Boolean = when (upload.uploadStatus) {
|
||||
UploadStatus.UPLOAD_SUCCEEDED -> true
|
||||
UploadStatus.UPLOAD_SUCCEEDED, UploadStatus.UPLOAD_CANCELLED -> true
|
||||
UploadStatus.UPLOAD_FAILED -> upload.lastResult.isNonRetryable()
|
||||
else -> false
|
||||
}
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2019 Chris Narkiewicz <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.nextcloud.client.media
|
||||
|
||||
import android.media.AudioManager
|
||||
|
||||
/**
|
||||
* Simplified audio focus values, relevant to application's media player experience.
|
||||
*/
|
||||
internal enum class AudioFocus {
|
||||
|
||||
LOST,
|
||||
DUCK,
|
||||
FOCUS;
|
||||
|
||||
companion object {
|
||||
fun fromPlatformFocus(audioFocus: Int): AudioFocus? = when (audioFocus) {
|
||||
AudioManager.AUDIOFOCUS_GAIN -> FOCUS
|
||||
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT -> FOCUS
|
||||
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK -> FOCUS
|
||||
AudioManager.AUDIOFOCUS_LOSS -> LOST
|
||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> LOST
|
||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> DUCK
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2019 Chris Narkiewicz <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.nextcloud.client.media
|
||||
|
||||
import android.media.AudioFocusRequest
|
||||
import android.media.AudioManager
|
||||
|
||||
/**
|
||||
* Wrapper around audio manager exposing simplified audio focus API and
|
||||
* hiding platform API level differences.
|
||||
*
|
||||
* @param audioManger Platform audio manager
|
||||
* @param onFocusChange Called when audio focus changes, including acquired and released focus states
|
||||
*/
|
||||
internal class AudioFocusManager(
|
||||
private val audioManger: AudioManager,
|
||||
private val onFocusChange: (AudioFocus) -> Unit,
|
||||
requestBuilder: AudioFocusRequest.Builder = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
|
||||
) {
|
||||
private val focusListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
|
||||
val focus = when (focusChange) {
|
||||
AudioManager.AUDIOFOCUS_GAIN,
|
||||
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT,
|
||||
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK -> AudioFocus.FOCUS
|
||||
|
||||
AudioManager.AUDIOFOCUS_LOSS,
|
||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> AudioFocus.LOST
|
||||
|
||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> AudioFocus.DUCK
|
||||
|
||||
else -> null
|
||||
}
|
||||
focus?.let { onFocusChange(it) }
|
||||
}
|
||||
|
||||
private val focusRequest = requestBuilder
|
||||
.setWillPauseWhenDucked(true)
|
||||
.setOnAudioFocusChangeListener(focusListener)
|
||||
.build()
|
||||
|
||||
fun requestFocus() {
|
||||
val requestResult = audioManger.requestAudioFocus(focusRequest)
|
||||
if (requestResult == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
|
||||
focusListener.onAudioFocusChange(AudioManager.AUDIOFOCUS_GAIN)
|
||||
} else {
|
||||
focusListener.onAudioFocusChange(AudioManager.AUDIOFOCUS_LOSS)
|
||||
}
|
||||
}
|
||||
|
||||
fun releaseFocus() {
|
||||
audioManger.abandonAudioFocusRequest(focusRequest)
|
||||
focusListener.onAudioFocusChange(AudioManager.AUDIOFOCUS_LOSS)
|
||||
}
|
||||
}
|
||||
@@ -1,298 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2024 Parneet Singh <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.client.media
|
||||
|
||||
import android.app.NotificationManager
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.ServiceCompat
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.common.Player.COMMAND_PLAY_PAUSE
|
||||
import androidx.media3.common.Player.COMMAND_SEEK_TO_NEXT
|
||||
import androidx.media3.common.Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM
|
||||
import androidx.media3.common.Player.COMMAND_SEEK_TO_PREVIOUS
|
||||
import androidx.media3.common.Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.session.CommandButton
|
||||
import androidx.media3.session.DefaultMediaNotificationProvider
|
||||
import androidx.media3.session.DefaultMediaNotificationProvider.COMMAND_KEY_COMPACT_VIEW_INDEX
|
||||
import androidx.media3.session.MediaSession
|
||||
import androidx.media3.session.MediaSession.ConnectionResult
|
||||
import androidx.media3.session.MediaSession.ConnectionResult.AcceptedResultBuilder
|
||||
import androidx.media3.session.MediaSessionService
|
||||
import androidx.media3.session.SessionCommand
|
||||
import androidx.media3.session.SessionResult
|
||||
import com.google.common.collect.ImmutableList
|
||||
import com.google.common.util.concurrent.Futures
|
||||
import com.google.common.util.concurrent.ListenableFuture
|
||||
import com.nextcloud.client.account.UserAccountManager
|
||||
import com.nextcloud.client.di.Injectable
|
||||
import com.nextcloud.client.media.NextcloudExoPlayer.createNextcloudExoplayer
|
||||
import com.nextcloud.client.network.ClientFactory
|
||||
import com.nextcloud.common.NextcloudClient
|
||||
import com.nextcloud.utils.extensions.registerBroadcastReceiver
|
||||
import com.owncloud.android.MainApp
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.ReceiverFlag
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.ui.notifications.NotificationUtils
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import javax.inject.Inject
|
||||
|
||||
@OptIn(UnstableApi::class)
|
||||
class BackgroundPlayerService :
|
||||
MediaSessionService(),
|
||||
Injectable {
|
||||
|
||||
private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||
|
||||
private val seekBackSessionCommand = SessionCommand(SESSION_COMMAND_ACTION_SEEK_BACK, Bundle.EMPTY)
|
||||
private val seekForwardSessionCommand = SessionCommand(SESSION_COMMAND_ACTION_SEEK_FORWARD, Bundle.EMPTY)
|
||||
|
||||
private lateinit var seekForward: CommandButton
|
||||
private lateinit var seekBackward: CommandButton
|
||||
|
||||
@Inject
|
||||
lateinit var clientFactory: ClientFactory
|
||||
|
||||
@Inject
|
||||
lateinit var userAccountManager: UserAccountManager
|
||||
|
||||
private lateinit var exoPlayer: ExoPlayer
|
||||
private var mediaSession: MediaSession? = null
|
||||
private var isPlayerReady = false
|
||||
|
||||
private val stopReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) {
|
||||
when (intent?.action) {
|
||||
RELEASE_MEDIA_SESSION_BROADCAST_ACTION -> release()
|
||||
|
||||
STOP_MEDIA_SESSION_BROADCAST_ACTION -> {
|
||||
if (isPlayerReady) {
|
||||
exoPlayer.stop()
|
||||
} else {
|
||||
stopSelf()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
val notification = NotificationCompat.Builder(this, NotificationUtils.NOTIFICATION_CHANNEL_MEDIA)
|
||||
.setSmallIcon(R.drawable.logo)
|
||||
.setContentTitle(getString(R.string.media_player_playing))
|
||||
.setSilent(true)
|
||||
.build()
|
||||
|
||||
ServiceCompat.startForeground(
|
||||
this,
|
||||
DefaultMediaNotificationProvider.DEFAULT_NOTIFICATION_ID,
|
||||
notification,
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
|
||||
} else {
|
||||
0
|
||||
}
|
||||
)
|
||||
|
||||
return super.onStartCommand(intent, flags, startId)
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
|
||||
MainApp.getAppComponent().inject(this)
|
||||
|
||||
if (userAccountManager.allUsers.isEmpty()) {
|
||||
return
|
||||
}
|
||||
|
||||
seekForward = CommandButton.Builder()
|
||||
.setDisplayName(getString(R.string.media_player_seek_forward))
|
||||
.setIconResId(R.drawable.ic_skip_next)
|
||||
.setSessionCommand(seekForwardSessionCommand)
|
||||
.setExtras(Bundle().apply { putInt(COMMAND_KEY_COMPACT_VIEW_INDEX, 2) })
|
||||
.build()
|
||||
|
||||
seekBackward = CommandButton.Builder()
|
||||
.setDisplayName(getString(R.string.media_player_seek_backward))
|
||||
.setIconResId(R.drawable.ic_skip_previous)
|
||||
.setSessionCommand(seekBackSessionCommand)
|
||||
.setExtras(Bundle().apply { putInt(COMMAND_KEY_COMPACT_VIEW_INDEX, 0) })
|
||||
.build()
|
||||
|
||||
exoPlayer = ExoPlayer.Builder(this).build()
|
||||
mediaSession = buildMediaSession(exoPlayer)
|
||||
|
||||
setMediaNotificationProvider(buildNotificationProvider())
|
||||
|
||||
registerBroadcastReceiver(
|
||||
stopReceiver,
|
||||
IntentFilter().apply {
|
||||
addAction(RELEASE_MEDIA_SESSION_BROADCAST_ACTION)
|
||||
addAction(STOP_MEDIA_SESSION_BROADCAST_ACTION)
|
||||
},
|
||||
ReceiverFlag.NotExported
|
||||
)
|
||||
|
||||
initExoPlayer()
|
||||
}
|
||||
|
||||
@Suppress("TooGenericExceptionCaught")
|
||||
private fun initExoPlayer() {
|
||||
serviceScope.launch {
|
||||
try {
|
||||
val nextcloudClient: NextcloudClient = withContext(Dispatchers.IO) {
|
||||
clientFactory.createNextcloudClient(userAccountManager.user)
|
||||
}
|
||||
|
||||
val realPlayer = createNextcloudExoplayer(this@BackgroundPlayerService, nextcloudClient)
|
||||
exoPlayer.release()
|
||||
exoPlayer = realPlayer
|
||||
isPlayerReady = true
|
||||
|
||||
// Update the session to use the real player
|
||||
mediaSession?.player = realPlayer
|
||||
} catch (e: Exception) {
|
||||
Log_OC.e(TAG, "Failed to initialise Nextcloud ExoPlayer: ${e.message}")
|
||||
stopSelf()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildMediaSession(player: ExoPlayer): MediaSession = MediaSession.Builder(applicationContext, player)
|
||||
.setId(BACKGROUND_MEDIA_SESSION_ID)
|
||||
.setCustomLayout(listOf(seekBackward, seekForward))
|
||||
.setCallback(object : MediaSession.Callback {
|
||||
override fun onConnect(session: MediaSession, controller: MediaSession.ControllerInfo): ConnectionResult =
|
||||
AcceptedResultBuilder(mediaSession ?: session)
|
||||
.setAvailablePlayerCommands(
|
||||
ConnectionResult.DEFAULT_PLAYER_COMMANDS.buildUpon()
|
||||
.remove(COMMAND_SEEK_TO_NEXT)
|
||||
.remove(COMMAND_SEEK_TO_NEXT_MEDIA_ITEM)
|
||||
.remove(COMMAND_SEEK_TO_PREVIOUS)
|
||||
.remove(COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM)
|
||||
.build()
|
||||
)
|
||||
.setAvailableSessionCommands(
|
||||
ConnectionResult.DEFAULT_SESSION_COMMANDS.buildUpon()
|
||||
.addSessionCommands(
|
||||
listOf(seekBackSessionCommand, seekForwardSessionCommand)
|
||||
).build()
|
||||
)
|
||||
.build()
|
||||
|
||||
override fun onPostConnect(session: MediaSession, controller: MediaSession.ControllerInfo) {
|
||||
session.setCustomLayout(listOf(seekBackward, seekForward))
|
||||
}
|
||||
|
||||
override fun onCustomCommand(
|
||||
session: MediaSession,
|
||||
controller: MediaSession.ControllerInfo,
|
||||
customCommand: SessionCommand,
|
||||
args: Bundle
|
||||
): ListenableFuture<SessionResult> = when (customCommand.customAction) {
|
||||
SESSION_COMMAND_ACTION_SEEK_FORWARD -> {
|
||||
session.player.seekForward()
|
||||
Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS))
|
||||
}
|
||||
|
||||
SESSION_COMMAND_ACTION_SEEK_BACK -> {
|
||||
session.player.seekBack()
|
||||
Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS))
|
||||
}
|
||||
|
||||
else -> super.onCustomCommand(session, controller, customCommand, args)
|
||||
}
|
||||
})
|
||||
.build()
|
||||
|
||||
private fun buildNotificationProvider() = object : DefaultMediaNotificationProvider(this) {
|
||||
@Suppress("DEPRECATION")
|
||||
override fun getMediaButtons(
|
||||
session: MediaSession,
|
||||
playerCommands: Player.Commands,
|
||||
customLayout: ImmutableList<CommandButton>,
|
||||
showPauseButton: Boolean
|
||||
): ImmutableList<CommandButton> {
|
||||
val isPlaying = mediaSession?.player?.isPlaying == true
|
||||
val playPauseButton = CommandButton.Builder()
|
||||
.setDisplayName(
|
||||
if (isPlaying) {
|
||||
getString(R.string.media_player_pause)
|
||||
} else {
|
||||
getString(R.string.media_player_play)
|
||||
}
|
||||
)
|
||||
.setIconResId(if (isPlaying) R.drawable.ic_pause else R.drawable.ic_play_arrow)
|
||||
.setPlayerCommand(COMMAND_PLAY_PAUSE)
|
||||
.setExtras(Bundle().apply { putInt(COMMAND_KEY_COMPACT_VIEW_INDEX, 1) })
|
||||
.build()
|
||||
|
||||
return ImmutableList.of(seekBackward, playPauseButton, seekForward)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||
release()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
unregisterReceiver(stopReceiver)
|
||||
serviceScope.cancel()
|
||||
mediaSession?.run {
|
||||
player.release()
|
||||
release()
|
||||
mediaSession = null
|
||||
}
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun release() {
|
||||
val player = mediaSession?.player
|
||||
if (player?.playWhenReady == true) {
|
||||
player.pause()
|
||||
}
|
||||
val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
|
||||
nm.cancel(DefaultMediaNotificationProvider.DEFAULT_NOTIFICATION_ID)
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = mediaSession
|
||||
|
||||
companion object {
|
||||
private val TAG = BackgroundPlayerService::class.java.simpleName
|
||||
|
||||
private const val SESSION_COMMAND_ACTION_SEEK_BACK = "SESSION_COMMAND_ACTION_SEEK_BACK"
|
||||
private const val SESSION_COMMAND_ACTION_SEEK_FORWARD = "SESSION_COMMAND_ACTION_SEEK_FORWARD"
|
||||
private const val BACKGROUND_MEDIA_SESSION_ID =
|
||||
"com.nextcloud.client.media.BACKGROUND_MEDIA_SESSION_ID"
|
||||
|
||||
const val RELEASE_MEDIA_SESSION_BROADCAST_ACTION =
|
||||
"com.nextcloud.client.media.RELEASE_MEDIA_SESSION"
|
||||
const val STOP_MEDIA_SESSION_BROADCAST_ACTION =
|
||||
"com.nextcloud.client.media.STOP_MEDIA_SESSION"
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2022 Álvaro Brey <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2019 Chris Narkiewicz <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.nextcloud.client.media
|
||||
|
||||
import android.content.Context
|
||||
import android.media.MediaPlayer
|
||||
import androidx.media3.common.PlaybackException
|
||||
import com.owncloud.android.R
|
||||
|
||||
/**
|
||||
* This code has been moved from legacy media player service.
|
||||
*/
|
||||
@Deprecated("This legacy helper should be refactored")
|
||||
@Suppress("ComplexMethod") // it's legacy code
|
||||
object ErrorFormat {
|
||||
|
||||
/** Error code for specific messages - see regular error codes at [MediaPlayer] */
|
||||
const val OC_MEDIA_ERROR = 0
|
||||
|
||||
@JvmStatic
|
||||
fun toString(context: Context?, what: Int, extra: Int): String {
|
||||
val messageId: Int
|
||||
|
||||
if (what == OC_MEDIA_ERROR) {
|
||||
messageId = extra
|
||||
} else if (extra == MediaPlayer.MEDIA_ERROR_UNSUPPORTED) {
|
||||
/* Added in API level 17
|
||||
Bitstream is conforming to the related coding standard or file spec,
|
||||
but the media framework does not support the feature.
|
||||
Constant Value: -1010 (0xfffffc0e)
|
||||
*/
|
||||
messageId = R.string.media_err_unsupported
|
||||
} else if (extra == MediaPlayer.MEDIA_ERROR_IO) {
|
||||
/* Added in API level 17
|
||||
File or network related operation errors.
|
||||
Constant Value: -1004 (0xfffffc14)
|
||||
*/
|
||||
messageId = R.string.media_err_io
|
||||
} else if (extra == MediaPlayer.MEDIA_ERROR_MALFORMED) {
|
||||
/* Added in API level 17
|
||||
Bitstream is not conforming to the related coding standard or file spec.
|
||||
Constant Value: -1007 (0xfffffc11)
|
||||
*/
|
||||
messageId = R.string.media_err_malformed
|
||||
} else if (extra == MediaPlayer.MEDIA_ERROR_TIMED_OUT) {
|
||||
/* Added in API level 17
|
||||
Some operation takes too long to complete, usually more than 3-5 seconds.
|
||||
Constant Value: -110 (0xffffff92)
|
||||
*/
|
||||
messageId = R.string.media_err_timeout
|
||||
} else if (what == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) {
|
||||
/* Added in API level 3
|
||||
The video is streamed and its container is not valid for progressive playback i.e the video's index
|
||||
(e.g moov atom) is not at the start of the file.
|
||||
Constant Value: 200 (0x000000c8)
|
||||
*/
|
||||
messageId = R.string.media_err_invalid_progressive_playback
|
||||
} else {
|
||||
/* MediaPlayer.MEDIA_ERROR_UNKNOWN
|
||||
Added in API level 1
|
||||
Unspecified media player error.
|
||||
Constant Value: 1 (0x00000001)
|
||||
*/
|
||||
/* MediaPlayer.MEDIA_ERROR_SERVER_DIED)
|
||||
Added in API level 1
|
||||
Media server died. In this case, the application must release the MediaPlayer
|
||||
object and instantiate a new one.
|
||||
Constant Value: 100 (0x00000064)
|
||||
*/
|
||||
messageId = R.string.media_err_unknown
|
||||
}
|
||||
return context?.getString(messageId) ?: "Media error"
|
||||
}
|
||||
|
||||
fun toString(context: Context, exception: PlaybackException): String {
|
||||
val messageId = when (exception.errorCode) {
|
||||
PlaybackException.ERROR_CODE_DECODING_FORMAT_UNSUPPORTED,
|
||||
PlaybackException.ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES -> {
|
||||
R.string.media_err_unsupported
|
||||
}
|
||||
|
||||
PlaybackException.ERROR_CODE_IO_UNSPECIFIED,
|
||||
PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED,
|
||||
PlaybackException.ERROR_CODE_IO_INVALID_HTTP_CONTENT_TYPE,
|
||||
PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS,
|
||||
PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND,
|
||||
PlaybackException.ERROR_CODE_IO_NO_PERMISSION,
|
||||
PlaybackException.ERROR_CODE_IO_CLEARTEXT_NOT_PERMITTED,
|
||||
PlaybackException.ERROR_CODE_IO_READ_POSITION_OUT_OF_RANGE -> {
|
||||
R.string.media_err_io
|
||||
}
|
||||
|
||||
PlaybackException.ERROR_CODE_TIMEOUT -> {
|
||||
R.string.media_err_timeout
|
||||
}
|
||||
|
||||
PlaybackException.ERROR_CODE_PARSING_CONTAINER_MALFORMED,
|
||||
PlaybackException.ERROR_CODE_PARSING_MANIFEST_MALFORMED -> {
|
||||
R.string.media_err_malformed
|
||||
}
|
||||
|
||||
else -> {
|
||||
R.string.media_err_invalid_progressive_playback
|
||||
}
|
||||
}
|
||||
return context.getString(messageId)
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2022 Álvaro Brey <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2022 Nextcloud GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.nextcloud.client.media
|
||||
|
||||
import android.content.Context
|
||||
import android.content.DialogInterface
|
||||
import android.view.View
|
||||
import androidx.media3.common.PlaybackException
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import com.google.android.material.dialog.MaterialAlertDialogBuilder
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
|
||||
class ExoplayerListener(
|
||||
private val context: Context,
|
||||
private val playerView: View,
|
||||
private val exoPlayer: ExoPlayer,
|
||||
private val onCompleted: () -> Unit = { }
|
||||
) : Player.Listener {
|
||||
|
||||
override fun onPlaybackStateChanged(playbackState: Int) {
|
||||
super.onPlaybackStateChanged(playbackState)
|
||||
if (playbackState == Player.STATE_ENDED) {
|
||||
onCompletion()
|
||||
onCompleted()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onIsPlayingChanged(isPlaying: Boolean) {
|
||||
super.onIsPlayingChanged(isPlaying)
|
||||
Log_OC.d(TAG, "Exoplayer keep screen on: $isPlaying")
|
||||
playerView.keepScreenOn = isPlaying
|
||||
}
|
||||
|
||||
private fun onCompletion() {
|
||||
exoPlayer.let {
|
||||
it.seekToDefaultPosition()
|
||||
it.pause()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPlayerError(error: PlaybackException) {
|
||||
super.onPlayerError(error)
|
||||
Log_OC.e(TAG, "Exoplayer error", error)
|
||||
val message = ErrorFormat.toString(context, error)
|
||||
MaterialAlertDialogBuilder(context)
|
||||
.setMessage(message)
|
||||
.setPositiveButton(R.string.common_ok) { _: DialogInterface?, _: Int ->
|
||||
onCompletion()
|
||||
}
|
||||
.setCancelable(false)
|
||||
.show()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ExoplayerListener"
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2019 Chris Narkiewicz <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2018 Tobias Kaminsky <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.nextcloud.client.media
|
||||
|
||||
import android.os.AsyncTask
|
||||
import com.owncloud.android.files.StreamMediaFileOperation
|
||||
import com.owncloud.android.lib.common.OwnCloudClient
|
||||
|
||||
internal class LoadUrlTask(
|
||||
private val client: OwnCloudClient,
|
||||
private val fileId: Long,
|
||||
private val onResult: (String?) -> Unit
|
||||
) : AsyncTask<Void, Void, String>() {
|
||||
|
||||
override fun doInBackground(vararg args: Void): String? {
|
||||
val operation = StreamMediaFileOperation(fileId)
|
||||
val result = operation.execute(client)
|
||||
return when (result.isSuccess) {
|
||||
true -> result.data[0] as String
|
||||
false -> null
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPostExecute(url: String?) {
|
||||
if (!isCancelled) {
|
||||
onResult(url)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2022 Álvaro Brey <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2022 Nextcloud GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.nextcloud.client.media
|
||||
|
||||
import android.content.Context
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.AudioAttributes
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.datasource.DefaultDataSource
|
||||
import androidx.media3.datasource.okhttp.OkHttpDataSource
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
|
||||
import com.nextcloud.common.NextcloudClient
|
||||
import com.owncloud.android.MainApp
|
||||
|
||||
object NextcloudExoPlayer {
|
||||
private const val FIVE_SECONDS_IN_MILLIS = 5000L
|
||||
|
||||
/**
|
||||
* Creates an [ExoPlayer] that uses [NextcloudClient] for HTTP connections, thus respecting redirections,
|
||||
* IP versions and certificates.
|
||||
*
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
@JvmStatic
|
||||
fun createNextcloudExoplayer(context: Context, nextcloudClient: NextcloudClient): ExoPlayer {
|
||||
val okHttpDataSourceFactory = OkHttpDataSource.Factory(nextcloudClient.client)
|
||||
okHttpDataSourceFactory.setUserAgent(MainApp.getUserAgent())
|
||||
val mediaSourceFactory = DefaultMediaSourceFactory(
|
||||
DefaultDataSource.Factory(
|
||||
context,
|
||||
okHttpDataSourceFactory
|
||||
)
|
||||
)
|
||||
return ExoPlayer
|
||||
.Builder(context)
|
||||
.setMediaSourceFactory(mediaSourceFactory)
|
||||
.setAudioAttributes(AudioAttributes.DEFAULT, true)
|
||||
.setHandleAudioBecomingNoisy(true)
|
||||
.setSeekForwardIncrementMs(FIVE_SECONDS_IN_MILLIS)
|
||||
.build()
|
||||
}
|
||||
}
|
||||
@@ -1,272 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2019 Chris Narkiewicz <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.nextcloud.client.media
|
||||
|
||||
import android.content.Context
|
||||
import android.media.AudioManager
|
||||
import android.media.MediaPlayer
|
||||
import android.os.PowerManager
|
||||
import android.widget.MediaController
|
||||
import com.nextcloud.client.account.User
|
||||
import com.nextcloud.client.media.PlayerStateMachine.Event
|
||||
import com.nextcloud.client.media.PlayerStateMachine.State
|
||||
import com.nextcloud.client.network.ClientFactory
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
|
||||
@Suppress("TooManyFunctions")
|
||||
internal class Player(
|
||||
private val context: Context,
|
||||
private val clientFactory: ClientFactory,
|
||||
private val listener: Listener? = null,
|
||||
audioManager: AudioManager,
|
||||
private val mediaPlayerCreator: () -> MediaPlayer = { MediaPlayer() }
|
||||
) : MediaController.MediaPlayerControl {
|
||||
|
||||
private companion object {
|
||||
const val DEFAULT_VOLUME = 1.0f
|
||||
const val DUCK_VOLUME = 0.1f
|
||||
const val MIN_DURATION_ALLOWING_SEEK = 3000
|
||||
}
|
||||
|
||||
interface Listener {
|
||||
fun onRunning(file: OCFile)
|
||||
fun onStart()
|
||||
fun onPause()
|
||||
fun onStop()
|
||||
fun onError(error: PlayerError)
|
||||
}
|
||||
|
||||
private var stateMachine: PlayerStateMachine
|
||||
private var loadUrlTask: LoadUrlTask? = null
|
||||
|
||||
private var enqueuedFile: PlaylistItem? = null
|
||||
|
||||
private var playedFile: OCFile? = null
|
||||
private var startPositionMs: Long = 0
|
||||
private var autoPlay = true
|
||||
private var user: User? = null
|
||||
private var dataSource: String? = null
|
||||
private var lastError: PlayerError? = null
|
||||
private var mediaPlayer: MediaPlayer? = null
|
||||
private val focusManager = AudioFocusManager(audioManager, this::onAudioFocusChange)
|
||||
|
||||
private val delegate = object : PlayerStateMachine.Delegate {
|
||||
override val isDownloaded: Boolean get() = playedFile?.isDown ?: false
|
||||
override val isAutoplayEnabled: Boolean get() = autoPlay
|
||||
override val hasEnqueuedFile: Boolean get() = enqueuedFile != null
|
||||
|
||||
override fun onStartRunning() {
|
||||
trace("onStartRunning()")
|
||||
enqueuedFile.let {
|
||||
if (it != null) {
|
||||
playedFile = it.file
|
||||
startPositionMs = it.startPositionMs
|
||||
autoPlay = it.autoPlay
|
||||
user = it.user
|
||||
dataSource = if (it.file.isDown) it.file.storagePath else null
|
||||
listener?.onRunning(it.file)
|
||||
} else {
|
||||
throw IllegalStateException("Player started without enqueued file.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStartDownloading() {
|
||||
trace("onStartDownloading()")
|
||||
checkNotNull(playedFile) { "File not set." }
|
||||
checkNotNull(user)
|
||||
playedFile?.let {
|
||||
val client = clientFactory.create(user)
|
||||
val task = LoadUrlTask(client, it.localId, this@Player::onDownloaded)
|
||||
task.execute()
|
||||
loadUrlTask = task
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPrepare() {
|
||||
trace("onPrepare()")
|
||||
mediaPlayer = mediaPlayerCreator.invoke()
|
||||
mediaPlayer?.setOnErrorListener(this@Player::onMediaPlayerError)
|
||||
mediaPlayer?.setOnPreparedListener(this@Player::onMediaPlayerPrepared)
|
||||
mediaPlayer?.setOnCompletionListener(this@Player::onMediaPlayerCompleted)
|
||||
mediaPlayer?.setOnBufferingUpdateListener(this@Player::onMediaPlayerBufferingUpdate)
|
||||
mediaPlayer?.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK)
|
||||
mediaPlayer?.setDataSource(dataSource)
|
||||
mediaPlayer?.setAudioStreamType(AudioManager.STREAM_MUSIC)
|
||||
mediaPlayer?.setVolume(DEFAULT_VOLUME, DEFAULT_VOLUME)
|
||||
mediaPlayer?.prepareAsync()
|
||||
}
|
||||
|
||||
override fun onStopped() {
|
||||
trace("onStoppped()")
|
||||
mediaPlayer?.stop()
|
||||
mediaPlayer?.reset()
|
||||
mediaPlayer?.release()
|
||||
mediaPlayer = null
|
||||
|
||||
playedFile = null
|
||||
startPositionMs = 0
|
||||
user = null
|
||||
autoPlay = true
|
||||
dataSource = null
|
||||
loadUrlTask?.cancel(true)
|
||||
loadUrlTask = null
|
||||
listener?.onStop()
|
||||
}
|
||||
|
||||
override fun onError() {
|
||||
trace("onError()")
|
||||
this.onStopped()
|
||||
lastError?.let {
|
||||
this@Player.listener?.onError(it)
|
||||
}
|
||||
if (lastError == null) {
|
||||
this@Player.listener?.onError(PlayerError("Unknown"))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStartPlayback() {
|
||||
trace("onStartPlayback()")
|
||||
mediaPlayer?.start()
|
||||
listener?.onStart()
|
||||
}
|
||||
|
||||
override fun onPausePlayback() {
|
||||
trace("onPausePlayback()")
|
||||
if (mediaPlayer?.isPlaying == true) {
|
||||
mediaPlayer?.pause()
|
||||
listener?.onPause()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onRequestFocus() {
|
||||
trace("onRequestFocus()")
|
||||
focusManager.requestFocus()
|
||||
}
|
||||
|
||||
override fun onReleaseFocus() {
|
||||
trace("onReleaseFocus()")
|
||||
focusManager.releaseFocus()
|
||||
}
|
||||
|
||||
override fun onAudioDuck(enabled: Boolean) {
|
||||
trace("onAudioDuck(): $enabled")
|
||||
if (enabled) {
|
||||
mediaPlayer?.setVolume(DUCK_VOLUME, DUCK_VOLUME)
|
||||
} else {
|
||||
mediaPlayer?.setVolume(DEFAULT_VOLUME, DEFAULT_VOLUME)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
stateMachine = PlayerStateMachine(delegate)
|
||||
}
|
||||
|
||||
fun play(item: PlaylistItem) {
|
||||
if (item.file != playedFile) {
|
||||
stateMachine.post(Event.STOP)
|
||||
this.enqueuedFile = item
|
||||
stateMachine.post(Event.PLAY)
|
||||
}
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
stateMachine.post(Event.STOP)
|
||||
}
|
||||
|
||||
fun stop(file: OCFile) {
|
||||
if (playedFile == file) {
|
||||
stateMachine.post(Event.STOP)
|
||||
}
|
||||
}
|
||||
|
||||
private fun onMediaPlayerError(mp: MediaPlayer, what: Int, extra: Int): Boolean {
|
||||
lastError = PlayerError(ErrorFormat.toString(context, what, extra))
|
||||
stateMachine.post(Event.ERROR)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun onMediaPlayerPrepared(mp: MediaPlayer) {
|
||||
trace("onMediaPlayerPrepared()")
|
||||
stateMachine.post(Event.PREPARED)
|
||||
}
|
||||
|
||||
private fun onMediaPlayerCompleted(mp: MediaPlayer) {
|
||||
stateMachine.post(Event.STOP)
|
||||
}
|
||||
|
||||
private fun onMediaPlayerBufferingUpdate(mp: MediaPlayer, percent: Int) {
|
||||
trace("onMediaPlayerBufferingUpdate(): $percent")
|
||||
}
|
||||
|
||||
private fun onDownloaded(url: String?) {
|
||||
if (url != null) {
|
||||
dataSource = url
|
||||
stateMachine.post(Event.DOWNLOADED)
|
||||
} else {
|
||||
lastError = PlayerError(context.getString(R.string.media_err_io))
|
||||
stateMachine.post(Event.ERROR)
|
||||
}
|
||||
}
|
||||
|
||||
private fun onAudioFocusChange(focus: AudioFocus) {
|
||||
when (focus) {
|
||||
AudioFocus.FOCUS -> stateMachine.post(Event.FOCUS_GAIN)
|
||||
AudioFocus.DUCK -> stateMachine.post(Event.FOCUS_DUCK)
|
||||
AudioFocus.LOST -> stateMachine.post(Event.FOCUS_LOST)
|
||||
}
|
||||
}
|
||||
|
||||
private fun trace(fmt: String, vararg args: Any?) {
|
||||
Log_OC.v(javaClass.simpleName, fmt.format(args))
|
||||
}
|
||||
|
||||
// region Media player controls
|
||||
|
||||
override fun isPlaying(): Boolean = stateMachine.isInState(State.PLAYING)
|
||||
|
||||
override fun canSeekForward(): Boolean = duration > MIN_DURATION_ALLOWING_SEEK
|
||||
|
||||
override fun canSeekBackward(): Boolean = duration > MIN_DURATION_ALLOWING_SEEK
|
||||
|
||||
override fun getDuration(): Int {
|
||||
val hasDuration = setOf(State.PLAYING, State.PAUSED)
|
||||
.find { stateMachine.isInState(it) } != null
|
||||
return if (hasDuration) {
|
||||
mediaPlayer?.duration ?: 0
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
override fun pause() {
|
||||
stateMachine.post(Event.PAUSE)
|
||||
}
|
||||
|
||||
override fun getBufferPercentage(): Int = 0
|
||||
|
||||
override fun seekTo(pos: Int) {
|
||||
if (stateMachine.isInState(State.PLAYING)) {
|
||||
mediaPlayer?.seekTo(pos)
|
||||
}
|
||||
}
|
||||
|
||||
override fun getCurrentPosition(): Int = mediaPlayer?.currentPosition ?: 0
|
||||
|
||||
override fun start() {
|
||||
stateMachine.post(Event.PLAY)
|
||||
}
|
||||
|
||||
override fun getAudioSessionId(): Int = 0
|
||||
|
||||
override fun canPause(): Boolean = stateMachine.isInState(State.PLAYING)
|
||||
|
||||
// endregion
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2019 Chris Narkiewicz <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.nextcloud.client.media
|
||||
|
||||
data class PlayerError(val message: String)
|
||||
@@ -1,239 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2019 Chris Narkiewicz <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.nextcloud.client.media
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Intent
|
||||
import android.media.AudioManager
|
||||
import android.os.Bundle
|
||||
import android.os.IBinder
|
||||
import android.widget.MediaController
|
||||
import android.widget.Toast
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.localbroadcastmanager.content.LocalBroadcastManager
|
||||
import com.nextcloud.client.account.User
|
||||
import com.nextcloud.client.network.ClientFactory
|
||||
import com.nextcloud.utils.ForegroundServiceHelper
|
||||
import com.nextcloud.utils.extensions.getParcelableArgument
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.ForegroundServiceType
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.ui.notifications.NotificationUtils
|
||||
import com.owncloud.android.ui.preview.PreviewMediaActivity
|
||||
import com.owncloud.android.utils.theme.ViewThemeUtils
|
||||
import dagger.android.AndroidInjection
|
||||
import java.util.Locale
|
||||
import javax.inject.Inject
|
||||
|
||||
class PlayerService : Service() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "PlayerService"
|
||||
|
||||
const val EXTRA_USER = "USER"
|
||||
const val EXTRA_FILE = "FILE"
|
||||
const val EXTRA_AUTO_PLAY = "EXTRA_AUTO_PLAY"
|
||||
const val EXTRA_START_POSITION_MS = "START_POSITION_MS"
|
||||
const val ACTION_PLAY = "PLAY"
|
||||
const val ACTION_STOP = "STOP"
|
||||
const val ACTION_TOGGLE = "TOGGLE"
|
||||
const val ACTION_STOP_FILE = "STOP_FILE"
|
||||
|
||||
const val IS_MEDIA_CONTROL_LAYOUT_READY = "IS_MEDIA_CONTROL_LAYOUT_READY"
|
||||
}
|
||||
|
||||
class Binder(val service: PlayerService) : android.os.Binder() {
|
||||
|
||||
/**
|
||||
* This property returns current instance of media player interface.
|
||||
* It is not cached and it is suitable for polling.
|
||||
*/
|
||||
val player: MediaController.MediaPlayerControl get() = service.player
|
||||
}
|
||||
|
||||
private val playerListener = object : Player.Listener {
|
||||
override fun onRunning(file: OCFile) {
|
||||
Log_OC.d(TAG, "PlayerService.onRunning()")
|
||||
val intent = Intent(PreviewMediaActivity.MEDIA_CONTROL_READY_RECEIVER).apply {
|
||||
putExtra(IS_MEDIA_CONTROL_LAYOUT_READY, false)
|
||||
}
|
||||
LocalBroadcastManager.getInstance(applicationContext).sendBroadcast(intent)
|
||||
}
|
||||
|
||||
override fun onStart() {
|
||||
Log_OC.d(TAG, "PlayerService.onStart()")
|
||||
val intent = Intent(PreviewMediaActivity.MEDIA_CONTROL_READY_RECEIVER).apply {
|
||||
putExtra(IS_MEDIA_CONTROL_LAYOUT_READY, true)
|
||||
}
|
||||
LocalBroadcastManager.getInstance(applicationContext).sendBroadcast(intent)
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
Log_OC.d(TAG, "PlayerService.onPause()")
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
Log_OC.d(TAG, "PlayerService.onStop()")
|
||||
stopServiceAndRemoveNotification(null)
|
||||
}
|
||||
|
||||
override fun onError(error: PlayerError) {
|
||||
Log_OC.d(TAG, "PlayerService.onError()")
|
||||
Toast.makeText(this@PlayerService, error.message, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
|
||||
@Inject
|
||||
lateinit var audioManager: AudioManager
|
||||
|
||||
@Inject
|
||||
lateinit var clientFactory: ClientFactory
|
||||
|
||||
@Inject
|
||||
lateinit var viewThemeUtils: ViewThemeUtils
|
||||
|
||||
private lateinit var player: Player
|
||||
private lateinit var notificationBuilder: NotificationCompat.Builder
|
||||
private var isRunning = false
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
|
||||
AndroidInjection.inject(this)
|
||||
player = Player(applicationContext, clientFactory, playerListener, audioManager)
|
||||
notificationBuilder = NotificationCompat.Builder(this)
|
||||
viewThemeUtils.androidx.themeNotificationCompatBuilder(this, notificationBuilder)
|
||||
|
||||
val stop = Intent(this, PlayerService::class.java).apply {
|
||||
action = ACTION_STOP
|
||||
}
|
||||
|
||||
val pendingStop = PendingIntent.getService(this, 0, stop, PendingIntent.FLAG_IMMUTABLE)
|
||||
notificationBuilder.addAction(0, getString(R.string.player_stop).lowercase(Locale.getDefault()), pendingStop)
|
||||
|
||||
val toggle = Intent(this, PlayerService::class.java).apply {
|
||||
action = ACTION_TOGGLE
|
||||
}
|
||||
|
||||
val pendingToggle = PendingIntent.getService(this, 0, toggle, PendingIntent.FLAG_IMMUTABLE)
|
||||
notificationBuilder.addAction(
|
||||
0,
|
||||
getString(R.string.player_toggle).lowercase(Locale.getDefault()),
|
||||
pendingToggle
|
||||
)
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = Binder(this)
|
||||
|
||||
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
|
||||
Log_OC.d(TAG, "player service started")
|
||||
if (!isRunning) {
|
||||
val file = intent.getParcelableArgument(EXTRA_FILE, OCFile::class.java)
|
||||
if (file != null) {
|
||||
startForeground(file)
|
||||
} else {
|
||||
startForegroundWithPlaceholder()
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
}
|
||||
|
||||
when (intent.action) {
|
||||
ACTION_PLAY -> onActionPlay(intent)
|
||||
ACTION_STOP -> onActionStop()
|
||||
ACTION_STOP_FILE -> onActionStopFile(intent.extras)
|
||||
ACTION_TOGGLE -> onActionToggle()
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
private fun startForegroundWithPlaceholder() {
|
||||
val ticker = String.format(getString(R.string.media_notif_ticker), getString(R.string.app_name))
|
||||
notificationBuilder.run {
|
||||
setSmallIcon(R.drawable.ic_play_arrow)
|
||||
setWhen(System.currentTimeMillis())
|
||||
setOngoing(false)
|
||||
setContentTitle(ticker)
|
||||
setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_MEDIA)
|
||||
}
|
||||
ForegroundServiceHelper.startService(
|
||||
this,
|
||||
R.string.media_notif_ticker,
|
||||
notificationBuilder.build(),
|
||||
ForegroundServiceType.MediaPlayback
|
||||
)
|
||||
}
|
||||
|
||||
private fun onActionToggle() {
|
||||
player.run {
|
||||
if (isPlaying) {
|
||||
pause()
|
||||
} else {
|
||||
start()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun onActionPlay(intent: Intent) {
|
||||
val user: User = intent.getParcelableArgument(EXTRA_USER, User::class.java)!!
|
||||
val file: OCFile = intent.getParcelableArgument(EXTRA_FILE, OCFile::class.java)!!
|
||||
val startPos = intent.getLongExtra(EXTRA_START_POSITION_MS, 0)
|
||||
val autoPlay = intent.getBooleanExtra(EXTRA_AUTO_PLAY, true)
|
||||
val item = PlaylistItem(file = file, startPositionMs = startPos, autoPlay = autoPlay, user = user)
|
||||
player.play(item)
|
||||
}
|
||||
|
||||
private fun onActionStop() {
|
||||
stopServiceAndRemoveNotification(null)
|
||||
}
|
||||
|
||||
private fun onActionStopFile(args: Bundle?) {
|
||||
val file: OCFile = args?.getParcelableArgument(EXTRA_FILE, OCFile::class.java)
|
||||
?: throw IllegalArgumentException("Missing file argument")
|
||||
stopServiceAndRemoveNotification(file)
|
||||
}
|
||||
|
||||
private fun startForeground(currentFile: OCFile) {
|
||||
val ticker = String.format(getString(R.string.media_notif_ticker), getString(R.string.app_name))
|
||||
val content = getString(R.string.media_state_playing, currentFile.getFileName())
|
||||
|
||||
notificationBuilder.run {
|
||||
setSmallIcon(R.drawable.ic_play_arrow)
|
||||
setWhen(System.currentTimeMillis())
|
||||
setOngoing(true)
|
||||
setContentTitle(ticker)
|
||||
setContentText(content)
|
||||
setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_MEDIA)
|
||||
}
|
||||
|
||||
ForegroundServiceHelper.startService(
|
||||
this,
|
||||
R.string.media_notif_ticker,
|
||||
notificationBuilder.build(),
|
||||
ForegroundServiceType.MediaPlayback
|
||||
)
|
||||
|
||||
isRunning = true
|
||||
}
|
||||
|
||||
private fun stopServiceAndRemoveNotification(file: OCFile?) {
|
||||
if (file == null) {
|
||||
player.stop()
|
||||
} else {
|
||||
player.stop(file)
|
||||
}
|
||||
|
||||
if (isRunning) {
|
||||
stopForeground(true)
|
||||
stopSelf()
|
||||
isRunning = false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2019 Chris Narkiewicz <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.nextcloud.client.media
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.ServiceConnection
|
||||
import android.os.IBinder
|
||||
import android.widget.MediaController
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.nextcloud.client.account.User
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
|
||||
@Suppress("TooManyFunctions") // implementing large interface
|
||||
class PlayerServiceConnection(private val context: Context) : MediaController.MediaPlayerControl {
|
||||
|
||||
var isConnected: Boolean = false
|
||||
private set
|
||||
|
||||
private var binder: PlayerService.Binder? = null
|
||||
|
||||
fun bind() {
|
||||
val intent = Intent(context, PlayerService::class.java)
|
||||
context.bindService(intent, connection, Context.BIND_AUTO_CREATE)
|
||||
}
|
||||
|
||||
fun unbind() {
|
||||
if (isConnected) {
|
||||
binder = null
|
||||
isConnected = false
|
||||
context.unbindService(connection)
|
||||
}
|
||||
}
|
||||
|
||||
fun start(user: User, file: OCFile, playImmediately: Boolean, position: Long) {
|
||||
val i = Intent(context, PlayerService::class.java).apply {
|
||||
putExtra(PlayerService.EXTRA_USER, user)
|
||||
putExtra(PlayerService.EXTRA_FILE, file)
|
||||
putExtra(PlayerService.EXTRA_AUTO_PLAY, playImmediately)
|
||||
putExtra(PlayerService.EXTRA_START_POSITION_MS, position)
|
||||
action = PlayerService.ACTION_PLAY
|
||||
}
|
||||
|
||||
startForegroundService(i)
|
||||
}
|
||||
|
||||
fun stop(file: OCFile) {
|
||||
val i = Intent(context, PlayerService::class.java)
|
||||
i.putExtra(PlayerService.EXTRA_FILE, file)
|
||||
i.action = PlayerService.ACTION_STOP_FILE
|
||||
try {
|
||||
context.startService(i)
|
||||
} catch (ex: IllegalStateException) {
|
||||
// https://developer.android.com/about/versions/oreo/android-8.0-changes#back-all
|
||||
// ignore it - the service is not running and does not need to be stopped
|
||||
}
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
val i = Intent(context, PlayerService::class.java)
|
||||
i.action = PlayerService.ACTION_STOP
|
||||
try {
|
||||
context.startService(i)
|
||||
} catch (ex: IllegalStateException) {
|
||||
// https://developer.android.com/about/versions/oreo/android-8.0-changes#back-all
|
||||
// ignore it - the service is not running and does not need to be stopped
|
||||
}
|
||||
}
|
||||
|
||||
private val connection = object : ServiceConnection {
|
||||
override fun onServiceDisconnected(name: ComponentName?) {
|
||||
isConnected = false
|
||||
binder = null
|
||||
}
|
||||
|
||||
override fun onServiceConnected(name: ComponentName?, localBinder: IBinder?) {
|
||||
binder = localBinder as PlayerService.Binder
|
||||
isConnected = true
|
||||
}
|
||||
}
|
||||
|
||||
// region Media controller
|
||||
|
||||
override fun isPlaying(): Boolean = binder?.player?.isPlaying ?: false
|
||||
|
||||
override fun canSeekForward(): Boolean = binder?.player?.canSeekForward() ?: false
|
||||
|
||||
override fun getDuration(): Int = binder?.player?.duration ?: 0
|
||||
|
||||
override fun pause() {
|
||||
binder?.player?.pause()
|
||||
}
|
||||
|
||||
override fun getBufferPercentage(): Int = binder?.player?.bufferPercentage ?: 0
|
||||
|
||||
override fun seekTo(pos: Int) {
|
||||
binder?.player?.seekTo(pos)
|
||||
}
|
||||
|
||||
override fun getCurrentPosition(): Int = binder?.player?.currentPosition ?: 0
|
||||
|
||||
override fun canSeekBackward(): Boolean = binder?.player?.canSeekBackward() ?: false
|
||||
|
||||
override fun start() {
|
||||
binder?.player?.start()
|
||||
}
|
||||
|
||||
override fun getAudioSessionId(): Int = 0
|
||||
|
||||
override fun canPause(): Boolean = binder?.player?.canPause() ?: false
|
||||
|
||||
// endregion
|
||||
|
||||
private fun startForegroundService(i: Intent) {
|
||||
ContextCompat.startForegroundService(context, i)
|
||||
}
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2019 Chris Narkiewicz <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.nextcloud.client.media
|
||||
|
||||
import com.github.oxo42.stateless4j.StateMachine
|
||||
import com.github.oxo42.stateless4j.StateMachineConfig
|
||||
import com.github.oxo42.stateless4j.delegates.Action
|
||||
import com.github.oxo42.stateless4j.transitions.Transition
|
||||
import java.util.ArrayDeque
|
||||
|
||||
/**
|
||||
* To see visual representation of the state machine, install PlanUml plugin.
|
||||
* http://plantuml.com/
|
||||
*
|
||||
* @startuml
|
||||
*
|
||||
* note "> - entry action\n< - exit action\n[exp] - transition guard\nfunction() - transition action" as README
|
||||
*
|
||||
* [*] --> STOPPED
|
||||
* STOPPED --> RUNNING: PLAY\n[hasEnqueuedFile]
|
||||
* RUNNING --> STOPPED: STOP\nonStop
|
||||
* RUNNING --> STOPPED: ERROR\nonError
|
||||
* RUNNING: >onStartRunning
|
||||
*
|
||||
* state RUNNING {
|
||||
* [*] --> DOWNLOADING: [!isDownloaded]
|
||||
* [*] --> PREPARING: [isDownloaded]
|
||||
* DOWNLOADING: >onStartDownloading
|
||||
* DOWNLOADING --> PREPARING: DOWNLOADED
|
||||
*
|
||||
* PREPARING: >onPrepare
|
||||
* PREPARING --> PLAYING: PREPARED\n[autoPlay]
|
||||
* PREPARING --> PAUSED: PREPARED\n[!autoPlay]
|
||||
* PLAYING --> PAUSED: PAUSE\nFOCUS_LOST
|
||||
*
|
||||
* PAUSED: >onPausePlayback
|
||||
* PAUSED --> PLAYING: PLAY
|
||||
*
|
||||
* PLAYING: >onRequestFocus
|
||||
* PLAYING: <onReleaseFocus
|
||||
* state PLAYING {
|
||||
* [*] -r-> AWAIT_FOCUS
|
||||
* AWAIT_FOCUS --> FOCUSED: FOCUS_GAIN\nonStartPlayback()
|
||||
* FOCUSED -l-> DUCKED: FOCUS_DUCK
|
||||
* DUCKED: >onAudioDuck(true)\n<onAudioDuck(false)
|
||||
* DUCKED -r-> FOCUSED: FOCUS_GAIN
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* @enduml
|
||||
*/
|
||||
internal class PlayerStateMachine(initialState: State, private val delegate: Delegate) {
|
||||
|
||||
constructor(delegate: Delegate) : this(State.STOPPED, delegate)
|
||||
|
||||
interface Delegate {
|
||||
val isDownloaded: Boolean
|
||||
val isAutoplayEnabled: Boolean
|
||||
val hasEnqueuedFile: Boolean
|
||||
|
||||
fun onStartRunning()
|
||||
fun onStartDownloading()
|
||||
fun onPrepare()
|
||||
fun onStopped()
|
||||
fun onError()
|
||||
fun onStartPlayback()
|
||||
fun onPausePlayback()
|
||||
fun onRequestFocus()
|
||||
fun onReleaseFocus()
|
||||
fun onAudioDuck(enabled: Boolean)
|
||||
}
|
||||
|
||||
enum class State {
|
||||
STOPPED,
|
||||
RUNNING,
|
||||
RUNNING_INITIAL,
|
||||
DOWNLOADING,
|
||||
PREPARING,
|
||||
PAUSED,
|
||||
PLAYING,
|
||||
AWAIT_FOCUS,
|
||||
FOCUSED,
|
||||
DUCKED
|
||||
}
|
||||
|
||||
enum class Event {
|
||||
PLAY,
|
||||
DOWNLOADED,
|
||||
PREPARED,
|
||||
STOP,
|
||||
PAUSE,
|
||||
ERROR,
|
||||
FOCUS_LOST,
|
||||
FOCUS_GAIN,
|
||||
FOCUS_DUCK,
|
||||
IMMEDIATE_TRANSITION
|
||||
}
|
||||
|
||||
private var pendingEvents = ArrayDeque<Event>()
|
||||
private var isProcessing = false
|
||||
private val stateMachine: StateMachine<State, Event>
|
||||
|
||||
/**
|
||||
* Immediate state machine state. This attribute provides innermost active state.
|
||||
* For checking parent states, use [PlayerStateMachine.isInState].
|
||||
*/
|
||||
val state: State
|
||||
get() {
|
||||
return stateMachine.state
|
||||
}
|
||||
|
||||
init {
|
||||
val config = StateMachineConfig<State, Event>()
|
||||
|
||||
config.configure(State.STOPPED)
|
||||
.permitIf(Event.PLAY, State.RUNNING_INITIAL) { delegate.hasEnqueuedFile }
|
||||
.onEntryFrom(Event.STOP, delegate::onStopped)
|
||||
.onEntryFrom(Event.ERROR, delegate::onError)
|
||||
|
||||
config.configure(State.RUNNING)
|
||||
.permit(Event.STOP, State.STOPPED)
|
||||
.permit(Event.ERROR, State.STOPPED)
|
||||
.onEntry(delegate::onStartRunning)
|
||||
|
||||
config.configure(State.RUNNING_INITIAL)
|
||||
.substateOf(State.RUNNING)
|
||||
.permitIf(Event.IMMEDIATE_TRANSITION, State.DOWNLOADING, { !delegate.isDownloaded })
|
||||
.permitIf(Event.IMMEDIATE_TRANSITION, State.PREPARING, { delegate.isDownloaded })
|
||||
.onEntry(this::immediateTransition)
|
||||
|
||||
config.configure(State.DOWNLOADING)
|
||||
.substateOf(State.RUNNING)
|
||||
.permit(Event.DOWNLOADED, State.PREPARING)
|
||||
.onEntry(delegate::onStartDownloading)
|
||||
|
||||
config.configure(State.PREPARING)
|
||||
.substateOf(State.RUNNING)
|
||||
.permitIf(Event.PREPARED, State.AWAIT_FOCUS) { delegate.isAutoplayEnabled }
|
||||
.permitIf(Event.PREPARED, State.PAUSED) { !delegate.isAutoplayEnabled }
|
||||
.onEntry(delegate::onPrepare)
|
||||
|
||||
config.configure(State.PLAYING)
|
||||
.substateOf(State.RUNNING)
|
||||
.permit(Event.PAUSE, State.PAUSED)
|
||||
.permit(Event.FOCUS_LOST, State.PAUSED)
|
||||
.onEntry(delegate::onRequestFocus)
|
||||
.onExit(delegate::onReleaseFocus)
|
||||
|
||||
config.configure(State.PAUSED)
|
||||
.substateOf(State.RUNNING)
|
||||
.permit(Event.PLAY, State.AWAIT_FOCUS)
|
||||
.onEntry(delegate::onPausePlayback)
|
||||
|
||||
config.configure(State.AWAIT_FOCUS)
|
||||
.substateOf(State.PLAYING)
|
||||
.permit(Event.FOCUS_GAIN, State.FOCUSED)
|
||||
|
||||
config.configure(State.FOCUSED)
|
||||
.substateOf(State.PLAYING)
|
||||
.permit(Event.FOCUS_DUCK, State.DUCKED)
|
||||
.onEntry(this::onAudioFocusGain)
|
||||
|
||||
config.configure(State.DUCKED)
|
||||
.substateOf(State.PLAYING)
|
||||
.permit(Event.FOCUS_GAIN, State.FOCUSED)
|
||||
.onEntry(Action { delegate.onAudioDuck(true) })
|
||||
.onExit(Action { delegate.onAudioDuck(false) })
|
||||
|
||||
stateMachine = StateMachine(initialState, config)
|
||||
stateMachine.onUnhandledTrigger { _, _ ->
|
||||
/* ignore unhandled event */
|
||||
}
|
||||
}
|
||||
|
||||
private fun immediateTransition() {
|
||||
stateMachine.fire(Event.IMMEDIATE_TRANSITION)
|
||||
}
|
||||
|
||||
private fun onAudioFocusGain(t: Transition<State, Event>) {
|
||||
if (t.source == State.AWAIT_FOCUS) {
|
||||
delegate.onStartPlayback()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if state machine is in a given state.
|
||||
* Contrary to [PlayerStateMachine.state] attribute, this method checks for
|
||||
* parent states.
|
||||
*/
|
||||
fun isInState(state: State): Boolean = stateMachine.isInState(state)
|
||||
|
||||
/**
|
||||
* Post state machine event to internal queue.
|
||||
*
|
||||
* This design ensures that we're not triggering multiple events
|
||||
* from state machines callbacks before the transition is fully
|
||||
* completed.
|
||||
*
|
||||
* Method is re-entrant.
|
||||
*/
|
||||
fun post(event: Event) {
|
||||
pendingEvents.addLast(event)
|
||||
if (!isProcessing) {
|
||||
isProcessing = true
|
||||
while (pendingEvents.isNotEmpty()) {
|
||||
val processedEvent = pendingEvents.removeFirst()
|
||||
stateMachine.fire(processedEvent)
|
||||
}
|
||||
isProcessing = false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2021 Tobias Kaminsky <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2019 Chris Narkiewicz <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
*/
|
||||
package com.nextcloud.client.media
|
||||
|
||||
import com.nextcloud.client.account.User
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
|
||||
data class PlaylistItem(val file: OCFile, val startPositionMs: Long, val autoPlay: Boolean, val user: User)
|
||||
@@ -10,7 +10,7 @@ import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.Network
|
||||
import android.net.NetworkCapabilities
|
||||
import android.os.Build
|
||||
import android.os.SystemClock
|
||||
import com.nextcloud.client.account.UserAccountManager
|
||||
import com.nextcloud.operations.GetMethod
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
@@ -25,6 +25,7 @@ import java.net.ConnectException
|
||||
import java.net.SocketTimeoutException
|
||||
import java.net.UnknownHostException
|
||||
import javax.net.ssl.SSLException
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
@Suppress("TooGenericExceptionCaught", "ReturnCount")
|
||||
class ConnectivityServiceImpl(
|
||||
@@ -38,6 +39,8 @@ class ConnectivityServiceImpl(
|
||||
companion object {
|
||||
private const val TAG = "ConnectivityServiceImpl"
|
||||
private const val CONNECTIVITY_CHECK_ROUTE = "/index.php/204"
|
||||
|
||||
private val CAPABILITY_CHANGE_DEBOUNCE = 15.seconds
|
||||
}
|
||||
|
||||
// region private values
|
||||
@@ -46,6 +49,7 @@ class ConnectivityServiceImpl(
|
||||
private var notifyJob: Job? = null
|
||||
private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
private val listeners = mutableSetOf<NetworkChangeListener>()
|
||||
private var lastCapabilityCheckMs: Long? = null
|
||||
|
||||
@Volatile
|
||||
private var currentConnectivity: Connectivity = Connectivity.DISCONNECTED
|
||||
@@ -60,7 +64,11 @@ class ConnectivityServiceImpl(
|
||||
}
|
||||
|
||||
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
|
||||
Log_OC.d(TAG, "capability changed")
|
||||
if (!shouldHandleCapabilityChange()) {
|
||||
return
|
||||
}
|
||||
|
||||
Log_OC.d(TAG, "resolving network capabilities to compare")
|
||||
updateConnectivity()
|
||||
}
|
||||
}
|
||||
@@ -101,7 +109,7 @@ class ConnectivityServiceImpl(
|
||||
}
|
||||
|
||||
val resolvedCapabilities = resolveNetworkCapabilities()
|
||||
if (resolvedCapabilities == null || !isSupportedTransport(resolvedCapabilities)) {
|
||||
if (resolvedCapabilities == null || !SupportedNetworkTransports.isSupportedTransport(resolvedCapabilities)) {
|
||||
Log_OC.e(TAG, "no usable network transport at check time, treating as walled")
|
||||
return true
|
||||
}
|
||||
@@ -148,14 +156,12 @@ class ConnectivityServiceImpl(
|
||||
fun updateConnectivity() {
|
||||
val currentKey = key
|
||||
val previous = currentConnectivity
|
||||
|
||||
val capabilities = resolveNetworkCapabilities()
|
||||
|
||||
val newConnectivity = if (capabilities == null) {
|
||||
Log_OC.w(TAG, "no network capabilities found, connectivity is disconnected")
|
||||
Connectivity.DISCONNECTED
|
||||
} else {
|
||||
val hasTransport = isSupportedTransport(capabilities)
|
||||
val hasTransport = SupportedNetworkTransports.isSupportedTransport(capabilities)
|
||||
val hasInternetCapability = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
|
||||
Connectivity(
|
||||
@@ -169,6 +175,7 @@ class ConnectivityServiceImpl(
|
||||
}
|
||||
|
||||
if (previous != newConnectivity) {
|
||||
Log_OC.d(TAG, "network capability changed - notifying listeners")
|
||||
currentConnectivity = newConnectivity
|
||||
walledCheckCache.putConnectivityValue(currentKey, newConnectivity)
|
||||
|
||||
@@ -178,6 +185,7 @@ class ConnectivityServiceImpl(
|
||||
)
|
||||
|
||||
if (isStructural) {
|
||||
Log_OC.d(TAG, "network structurally capability changed - clearing walled cache as well")
|
||||
walledCheckCache.clear(currentKey)
|
||||
}
|
||||
notifyListeners()
|
||||
@@ -195,6 +203,17 @@ class ConnectivityServiceImpl(
|
||||
// endregion
|
||||
|
||||
// region private methods
|
||||
private fun shouldHandleCapabilityChange(): Boolean {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val last = lastCapabilityCheckMs
|
||||
if (last != null && now - last < CAPABILITY_CHANGE_DEBOUNCE.inWholeMilliseconds) {
|
||||
return false
|
||||
}
|
||||
|
||||
lastCapabilityCheckMs = now
|
||||
return true
|
||||
}
|
||||
|
||||
private fun notifyListeners() {
|
||||
if (listeners.isEmpty()) {
|
||||
return
|
||||
@@ -219,21 +238,9 @@ class ConnectivityServiceImpl(
|
||||
|
||||
return connectivityManager.allNetworks
|
||||
.mapNotNull { connectivityManager.getNetworkCapabilities(it) }
|
||||
.firstOrNull { isSupportedTransport(it) }
|
||||
.firstOrNull { SupportedNetworkTransports.isSupportedTransport(it) }
|
||||
}
|
||||
|
||||
private fun isSupportedTransport(capabilities: NetworkCapabilities) =
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) ||
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) ||
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) ||
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI_AWARE) ||
|
||||
(
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_USB)
|
||||
)
|
||||
|
||||
private fun getWalledValueFromException(e: Exception): Boolean = when (e) {
|
||||
is UnknownHostException,
|
||||
is ConnectException -> {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2026 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
package com.nextcloud.client.network
|
||||
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.NetworkRequest
|
||||
import android.os.Build
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.NetworkType
|
||||
|
||||
object SupportedNetworkTransports {
|
||||
private val values: List<Int>
|
||||
get() = buildList {
|
||||
add(NetworkCapabilities.TRANSPORT_WIFI)
|
||||
add(NetworkCapabilities.TRANSPORT_CELLULAR)
|
||||
add(NetworkCapabilities.TRANSPORT_ETHERNET)
|
||||
add(NetworkCapabilities.TRANSPORT_VPN)
|
||||
add(NetworkCapabilities.TRANSPORT_BLUETOOTH)
|
||||
add(NetworkCapabilities.TRANSPORT_WIFI_AWARE)
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
add(NetworkCapabilities.TRANSPORT_USB)
|
||||
}
|
||||
}
|
||||
|
||||
fun getConstraints(requiresCharging: Boolean = false): Constraints {
|
||||
val networkRequest = NetworkRequest.Builder()
|
||||
.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
|
||||
.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
|
||||
.apply {
|
||||
values.forEach { addTransportType(it) }
|
||||
}
|
||||
.build()
|
||||
|
||||
return Constraints.Builder()
|
||||
.setRequiredNetworkRequest(networkRequest, NetworkType.CONNECTED)
|
||||
.setRequiresCharging(requiresCharging)
|
||||
.build()
|
||||
}
|
||||
|
||||
fun isSupportedTransport(capabilities: NetworkCapabilities) = values.any { capabilities.hasTransport(it) }
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 STRATO GmbH.
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.client.player
|
||||
|
||||
import android.content.Context
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.datasource.cache.Cache
|
||||
import androidx.media3.datasource.cache.LeastRecentlyUsedCacheEvictor
|
||||
import androidx.media3.datasource.cache.SimpleCache
|
||||
import com.nextcloud.client.player.media3.PlaybackService
|
||||
import com.nextcloud.client.player.ui.PlayerActivity
|
||||
import com.nextcloud.client.player.ui.PlayerProgressIndicator
|
||||
import com.nextcloud.client.player.ui.audio.AudioFileFragment
|
||||
import com.nextcloud.client.player.ui.audio.AudioPlayerView
|
||||
import com.nextcloud.client.player.ui.control.PlayerControlView
|
||||
import com.nextcloud.client.player.ui.video.VideoFileFragment
|
||||
import com.nextcloud.client.player.ui.video.VideoPlayerView
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.android.ContributesAndroidInjector
|
||||
import java.io.File
|
||||
import javax.inject.Singleton
|
||||
|
||||
private const val PLAYER_CACHE_DIR_NAME = "player"
|
||||
private const val PLAYER_CACHE_SIZE = 300 * 1024 * 1024L
|
||||
|
||||
@Module(includes = [PlayerModule.AndroidInjector::class])
|
||||
class PlayerModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
@UnstableApi
|
||||
fun provideCache(context: Context): Cache = SimpleCache(
|
||||
File(context.cacheDir, PLAYER_CACHE_DIR_NAME),
|
||||
LeastRecentlyUsedCacheEvictor(PLAYER_CACHE_SIZE)
|
||||
)
|
||||
|
||||
@Module
|
||||
abstract class AndroidInjector {
|
||||
|
||||
@UnstableApi
|
||||
@ContributesAndroidInjector
|
||||
abstract fun playbackService(): PlaybackService
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract fun playerActivity(): PlayerActivity
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract fun audioPlayerView(): AudioPlayerView
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract fun videoPlayerView(): VideoPlayerView
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract fun playerControlView(): PlayerControlView
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract fun playerProgressIndicator(): PlayerProgressIndicator
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract fun audioFileFragment(): AudioFileFragment
|
||||
|
||||
@ContributesAndroidInjector
|
||||
abstract fun videoFileFragment(): VideoFileFragment
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 STRATO GmbH.
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.client.player.media3
|
||||
|
||||
import android.content.Context
|
||||
import androidx.media3.common.MediaMetadata
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.session.DefaultMediaNotificationProvider
|
||||
import com.nextcloud.client.player.util.PlayerUtil.playbackFile
|
||||
|
||||
@UnstableApi
|
||||
class MediaNotificationProvider(context: Context) : DefaultMediaNotificationProvider(context) {
|
||||
|
||||
override fun getNotificationContentTitle(metadata: MediaMetadata): CharSequence =
|
||||
metadata.title ?: metadata.playbackFile?.getNameWithoutExtension() ?: ""
|
||||
|
||||
override fun getNotificationContentText(metadata: MediaMetadata): CharSequence =
|
||||
metadata.artist ?: metadata.albumTitle ?: ""
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 STRATO GmbH.
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.client.player.media3
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.view.SurfaceView
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.session.MediaController
|
||||
import androidx.media3.session.MediaSession
|
||||
import androidx.media3.session.SessionToken
|
||||
import com.google.common.util.concurrent.ListenableFuture
|
||||
import com.nextcloud.client.player.media3.session.MediaSessionFactory
|
||||
import com.nextcloud.client.player.model.PlaybackSettings
|
||||
import com.nextcloud.client.player.model.file.PlaybackFile
|
||||
import com.nextcloud.client.player.model.file.PlaybackFiles
|
||||
import com.nextcloud.client.player.model.state.PlaybackState
|
||||
import com.nextcloud.client.player.model.state.RepeatMode
|
||||
import com.nextcloud.client.player.util.PeriodicAction
|
||||
import com.nextcloud.client.player.util.PlayerUtil.indexOfFirst
|
||||
import com.nextcloud.client.player.util.PlayerUtil.playbackFile
|
||||
import com.nextcloud.client.player.util.PlayerUtil.readCurrentFiles
|
||||
import com.nextcloud.client.player.util.PlayerUtil.readMediaIds
|
||||
import com.nextcloud.client.player.util.PlayerUtil.setRepeatMode
|
||||
import com.nextcloud.client.player.util.PlayerUtil.toMediaItem
|
||||
import com.nextcloud.client.player.util.PlayerUtil.toPlaybackState
|
||||
import com.nextcloud.client.player.util.PlayerUtil.updateMediaItems
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import java.util.concurrent.ExecutionException
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
@Singleton
|
||||
@OptIn(markerClass = [UnstableApi::class])
|
||||
@Suppress("TooManyFunctions")
|
||||
class PlaybackModel @Inject constructor(
|
||||
private val context: Context,
|
||||
private val mediaSessionFactory: MediaSessionFactory,
|
||||
private val playbackSettings: PlaybackSettings
|
||||
) {
|
||||
|
||||
companion object {
|
||||
private const val CHECK_PROGRESS_INTERVAL = 1000L
|
||||
}
|
||||
|
||||
interface Listener {
|
||||
fun onPlaybackUpdate(state: PlaybackState)
|
||||
fun onPlaybackError(error: Throwable) = Unit
|
||||
}
|
||||
|
||||
private val listeners = mutableListOf<Listener>()
|
||||
|
||||
private val checkProgressPeriodicAction = PeriodicAction(CHECK_PROGRESS_INTERVAL) {
|
||||
notifyPlaybackUpdate()
|
||||
}
|
||||
|
||||
private val playerListener = PlaybackModelPlayerListener(
|
||||
checkProgressPeriodicAction,
|
||||
this::notifyPlaybackUpdate,
|
||||
this::onPlaybackError,
|
||||
this::onPlaylistChanged
|
||||
)
|
||||
|
||||
private val controllerListener = object : MediaController.Listener {
|
||||
override fun onDisconnected(controller: MediaController) {
|
||||
controller.removeListener(playerListener)
|
||||
if (this@PlaybackModel.controller === controller) {
|
||||
this@PlaybackModel.controller = null
|
||||
}
|
||||
videoSurfaceView = null
|
||||
invalidateCurrentFiles()
|
||||
stopFilesFlow()
|
||||
checkProgressPeriodicAction.stop()
|
||||
notifyPlaybackUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
private var controllerScope: CoroutineScope? = null
|
||||
private var controller: MediaController? = null
|
||||
private var filesFlowJob: Job? = null
|
||||
|
||||
private var mediaSession: MediaSession? = null
|
||||
|
||||
var onPictureInPictureClose: (() -> Unit)? = null
|
||||
|
||||
private var videoSurfaceView: SurfaceView? = null
|
||||
|
||||
private var cachedCurrentFiles: List<PlaybackFile>? = null
|
||||
private var cachedMediaIds: List<String>? = null
|
||||
|
||||
val state: PlaybackState?
|
||||
get() = controller?.toPlaybackState(currentFiles())
|
||||
|
||||
private fun currentFiles(): List<PlaybackFile> = cachedCurrentFiles
|
||||
?: (controller?.readCurrentFiles() ?: emptyList()).also { cachedCurrentFiles = it }
|
||||
|
||||
private fun onPlaylistChanged() {
|
||||
val mediaIds = controller?.readMediaIds() ?: emptyList()
|
||||
if (mediaIds == cachedMediaIds) return
|
||||
|
||||
cachedMediaIds = mediaIds
|
||||
cachedCurrentFiles = null
|
||||
}
|
||||
|
||||
private fun invalidateCurrentFiles() {
|
||||
cachedMediaIds = null
|
||||
cachedCurrentFiles = null
|
||||
}
|
||||
|
||||
fun getMediaSession(): MediaSession = mediaSession ?: mediaSessionFactory.create().also {
|
||||
mediaSession = it
|
||||
}
|
||||
|
||||
suspend fun start() {
|
||||
if (controller?.isConnected == true) {
|
||||
return
|
||||
}
|
||||
|
||||
releaseController()
|
||||
|
||||
videoSurfaceView = null
|
||||
val sessionToken = SessionToken(context, ComponentName(context, PlaybackService::class.java))
|
||||
controller = MediaController.Builder(context, sessionToken)
|
||||
.setListener(controllerListener)
|
||||
.buildAsync()
|
||||
.await()
|
||||
.apply {
|
||||
addListener(playerListener)
|
||||
setRepeatMode(playbackSettings.repeatMode)
|
||||
shuffleModeEnabled = playbackSettings.isShuffle
|
||||
}
|
||||
controllerScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
}
|
||||
|
||||
private fun releaseController() {
|
||||
stopFilesFlow()
|
||||
checkProgressPeriodicAction.stop()
|
||||
invalidateCurrentFiles()
|
||||
|
||||
val current = controller ?: return
|
||||
controller = null
|
||||
current.removeListener(playerListener)
|
||||
current.release()
|
||||
}
|
||||
|
||||
private fun stopFilesFlow() {
|
||||
filesFlowJob?.cancel()
|
||||
filesFlowJob = null
|
||||
controllerScope?.cancel()
|
||||
controllerScope = null
|
||||
}
|
||||
|
||||
@Suppress("TooGenericExceptionCaught")
|
||||
private suspend fun <T> ListenableFuture<T>.await(): T = suspendCancellableCoroutine { cont ->
|
||||
addListener(
|
||||
{
|
||||
try {
|
||||
cont.resume(get())
|
||||
} catch (e: ExecutionException) {
|
||||
cont.resumeWithException(e.cause ?: e)
|
||||
} catch (e: Exception) {
|
||||
cont.resumeWithException(e)
|
||||
}
|
||||
},
|
||||
Runnable::run
|
||||
)
|
||||
|
||||
cont.invokeOnCancellation {
|
||||
cancel(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun setFilesFlow(filesFlow: Flow<PlaybackFiles>) {
|
||||
filesFlowJob?.cancel()
|
||||
filesFlowJob = controllerScope?.launch {
|
||||
filesFlow
|
||||
.catch {
|
||||
notifyPlaybackError(it)
|
||||
release()
|
||||
}
|
||||
.collectLatest { setFiles(it) }
|
||||
}
|
||||
}
|
||||
|
||||
fun setFiles(files: PlaybackFiles) {
|
||||
if (files.list.isEmpty()) {
|
||||
release()
|
||||
return
|
||||
}
|
||||
|
||||
controller?.let { applyFiles(it, files) }
|
||||
}
|
||||
|
||||
private fun applyFiles(controller: MediaController, files: PlaybackFiles) {
|
||||
val mediaItems = files.list.map { it.toMediaItem() }
|
||||
|
||||
if (controller.readMediaIds() == mediaItems.map { it.mediaId }) {
|
||||
return
|
||||
}
|
||||
|
||||
val currentFile = controller.currentMediaItem?.mediaMetadata?.playbackFile
|
||||
|
||||
when {
|
||||
currentFile == null -> controller.setMediaItems(mediaItems)
|
||||
files.list.any { it.id == currentFile.id } -> controller.updateMediaItems(mediaItems)
|
||||
else -> controller.setMediaItems(mediaItems, getNextFileIndex(files, currentFile), 0)
|
||||
}
|
||||
|
||||
controller.prepare()
|
||||
}
|
||||
|
||||
private fun getNextFileIndex(files: PlaybackFiles, currentFile: PlaybackFile): Int = (files.list + currentFile)
|
||||
.sortedWith(files.comparator)
|
||||
.indexOfFirst { it.id == currentFile.id }
|
||||
.let { if (it in files.list.indices) it else 0 }
|
||||
|
||||
fun release() {
|
||||
videoSurfaceView = null
|
||||
releaseController()
|
||||
mediaSession?.player?.release()
|
||||
mediaSession?.release()
|
||||
mediaSession = null
|
||||
notifyPlaybackUpdate()
|
||||
}
|
||||
|
||||
fun clearVideoSurfaceView(surfaceView: SurfaceView) {
|
||||
if (videoSurfaceView === surfaceView) {
|
||||
setVideoSurfaceView(null)
|
||||
}
|
||||
}
|
||||
|
||||
fun setVideoSurfaceView(surfaceView: SurfaceView?) {
|
||||
if (videoSurfaceView === surfaceView) {
|
||||
return
|
||||
}
|
||||
|
||||
videoSurfaceView = surfaceView
|
||||
controller?.setVideoSurfaceView(surfaceView)
|
||||
}
|
||||
|
||||
fun addListener(listener: Listener) {
|
||||
if (!listeners.contains(listener)) {
|
||||
listeners.add(listener)
|
||||
}
|
||||
}
|
||||
|
||||
fun removeListener(listener: Listener) {
|
||||
listeners.remove(listener)
|
||||
}
|
||||
|
||||
fun play() {
|
||||
controller?.run {
|
||||
prepare()
|
||||
play()
|
||||
}
|
||||
}
|
||||
|
||||
fun pause() {
|
||||
controller?.pause()
|
||||
}
|
||||
|
||||
fun playNext() {
|
||||
controller?.run {
|
||||
seekToNextMediaItem()
|
||||
prepare()
|
||||
}
|
||||
}
|
||||
|
||||
fun seekToPosition(positionInMilliseconds: Long) {
|
||||
controller?.seekTo(positionInMilliseconds)
|
||||
}
|
||||
|
||||
fun setRepeatMode(repeatMode: RepeatMode) {
|
||||
playbackSettings.setRepeatMode(repeatMode)
|
||||
controller?.setRepeatMode(repeatMode)
|
||||
}
|
||||
|
||||
fun setShuffle(shuffle: Boolean) {
|
||||
playbackSettings.setShuffle(shuffle)
|
||||
controller?.shuffleModeEnabled = shuffle
|
||||
}
|
||||
|
||||
fun switchToFile(file: PlaybackFile) {
|
||||
controller?.run {
|
||||
val mediaItemIndex = indexOfFirst { it.mediaId == file.id }
|
||||
if (mediaItemIndex >= 0 && mediaItemIndex != currentMediaItemIndex) {
|
||||
seekToDefaultPosition(mediaItemIndex)
|
||||
prepare()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun stopPlaying(file: OCFile) {
|
||||
controller?.run {
|
||||
val mediaItemIndex = indexOfFirst { it.mediaId == file.localId.toString() }
|
||||
if (mediaItemIndex >= 0) {
|
||||
release()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun notifyPlaybackUpdate() {
|
||||
val currentState = state ?: releasedState()
|
||||
for (i in listeners.indices) {
|
||||
listeners.getOrNull(i)?.onPlaybackUpdate(currentState)
|
||||
}
|
||||
}
|
||||
|
||||
private fun releasedState(): PlaybackState = PlaybackState(
|
||||
currentFiles = emptyList(),
|
||||
currentItemState = null,
|
||||
repeatMode = playbackSettings.repeatMode,
|
||||
shuffle = playbackSettings.isShuffle
|
||||
)
|
||||
|
||||
private fun notifyPlaybackError(error: Throwable) {
|
||||
for (i in listeners.indices) {
|
||||
listeners.getOrNull(i)?.onPlaybackError(error)
|
||||
}
|
||||
}
|
||||
|
||||
private fun onPlaybackError(error: Throwable) {
|
||||
notifyPlaybackError(error)
|
||||
state?.let {
|
||||
if (shouldSwitchToNextSource(it)) {
|
||||
playNext()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun shouldSwitchToNextSource(state: PlaybackState): Boolean {
|
||||
val currentFile = state.currentItemState?.file
|
||||
val currentFiles = state.currentFiles
|
||||
val oneFileInQueue = currentFiles.size == 1
|
||||
val endOfQueue = currentFiles.indexOf(currentFile) == currentFiles.lastIndex
|
||||
return !oneFileInQueue && !endOfQueue
|
||||
}
|
||||
}
|
||||
Loaded 100 of 388 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user