Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(teaching): cache course files with readable names #443

Merged
merged 7 commits into from
Feb 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1047,4 +1047,4 @@ SPEC CHECKSUMS:

PODFILE CHECKSUM: 61a76b69206754db38d48117525d4ed24975f765

COCOAPODS: 1.12.1
COCOAPODS: 1.14.3
2 changes: 1 addition & 1 deletion package-lock.json

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

4 changes: 4 additions & 0 deletions src/core/constants.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { Platform } from 'react-native';
import { DocumentDirectoryPath, ExternalDirectoryPath } from 'react-native-fs';

export const IS_ANDROID = Platform.OS === 'android';
export const IS_IOS = Platform.OS === 'ios';
export const MAX_RECENT_SEARCHES = 10;
export const PUBLIC_APP_DIRECTORY_PATH = IS_IOS
? DocumentDirectoryPath
: ExternalDirectoryPath;
export const courseColors = [
{ name: 'colors.red', color: '#DC2626' },
{ name: 'colors.orange', color: '#EA580C' },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,40 @@ import {
downloadFile,
stopDownload as fsStopDownload,
mkdir,
moveFile,
unlink,
} from 'react-native-fs';
import { dirname } from 'react-native-path';

import { FilesCacheContext } from '../../features/courses/contexts/FilesCacheContext';
import { CourseFilesCacheContext } from '../../features/courses/contexts/CourseFilesCacheContext';
import { UnsupportedFileTypeError } from '../../features/courses/errors/UnsupportedFileTypeError';
import { useCoursesFilesCachePath } from '../../features/courses/hooks/useCourseFilesCachePath';
import { cleanupEmptyFolders } from '../../utils/files';
import { useApiContext } from '../contexts/ApiContext';
import { Download, useDownloadsContext } from '../contexts/DownloadsContext';

export const useDownload = (fromUrl: string, toFile: string) => {
export const useDownloadCourseFile = (
fromUrl: string,
toFile: string,
fileId: string,
) => {
const { token } = useApiContext();
const { t } = useTranslation();
const coursesFilesCachePath = useCoursesFilesCachePath();
const { downloadsRef, setDownloads } = useDownloadsContext();
const { cache, isRefreshing: isCacheRefreshing } =
useContext(FilesCacheContext);
const {
cache,
isRefreshing: isCacheRefreshing,
refresh,
} = useContext(CourseFilesCacheContext);
const key = `${fromUrl}:${toFile}`;
const download = useMemo(
() =>
downloadsRef.current?.[key] ?? {
isDownloaded: false,
downloadProgress: undefined,
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[downloadsRef.current?.[key], key],
);

Expand All @@ -46,19 +58,41 @@ export const useDownload = (fromUrl: string, toFile: string) => {
[key, setDownloads],
);

const cachedFilePath = cache[fileId];

useEffect(() => {
if (toFile && !isCacheRefreshing) {
updateDownload({ isDownloaded: Boolean(cache[toFile]) });
}
}, [cache, isCacheRefreshing, toFile, updateDownload]);
(async () => {
if (toFile && !isCacheRefreshing) {
if (cachedFilePath) {
if (cachedFilePath === toFile) {
updateDownload({ isDownloaded: true });
} else {
// Update the name when changed
await mkdir(dirname(toFile));
await moveFile(cachedFilePath, toFile);
await cleanupEmptyFolders(coursesFilesCachePath);
refresh();
}
} else {
updateDownload({ isDownloaded: false });
}
}
})();
}, [
cachedFilePath,
coursesFilesCachePath,
fileId,
isCacheRefreshing,
refresh,
toFile,
updateDownload,
]);

const startDownload = useCallback(async () => {
if (!download.isDownloaded && download.downloadProgress == null) {
updateDownload({ downloadProgress: 0 });
try {
await mkdir(dirname(toFile), {
NSURLIsExcludedFromBackupKey: true,
});
await mkdir(dirname(toFile));
const { jobId, promise } = downloadFile({
fromUrl,
toFile,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import {
CachesDirectoryPath,
mkdir,
moveFile,
readDir,
unlink,
} from 'react-native-fs';

import { splitNameAndExtension } from '../../../utils/files';
import { PUBLIC_APP_DIRECTORY_PATH } from '../../constants';
import { PreferencesContextProps } from '../../contexts/PreferencesContext';

export const migrateCourseFilesCacheToDocumentsDirectory = async (
preferences: PreferencesContextProps,
) => {
const { username } = preferences;
if (!username) {
return;
}

try {
const courseCachesPath = [CachesDirectoryPath, username, 'Courses'].join(
'/',
);
const courseCaches = await readDir(courseCachesPath);
for (const courseCache of courseCaches) {
if (courseCache.isDirectory()) {
const newCourseCachePath = [
PUBLIC_APP_DIRECTORY_PATH,
username,
'Courses',
courseCache.name,
].join('/');
await mkdir(newCourseCachePath);
const files = await readDir(courseCache.path);
for (const courseFile of files) {
if (courseFile.isFile()) {
const [name, extension] = splitNameAndExtension(courseFile.name);
const newPath = [newCourseCachePath, `(${name}).${extension}`].join(
'/',
);
await moveFile(courseFile.path, newPath);
}
}
await unlink(courseCache.path);
}
}
await unlink(courseCachesPath);
} catch (_) {
// Empty cache, don't transfer
}
};
5 changes: 5 additions & 0 deletions src/core/migrations/MigrationService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { version as currentVersion } from '../../../package.json';
import { PreferencesContextProps } from '../contexts/PreferencesContext';
import { Migration } from '../types/migrations';
import { storeCoursePreferencesByShortcode } from './1.5.0/storeCoursePreferencesByShortcode';
import { migrateCourseFilesCacheToDocumentsDirectory } from './1.6.2/migrateCourseFilesCacheToDocumentsDirectory';
import { invalidateCache } from './common';

export class MigrationService {
Expand All @@ -14,6 +15,10 @@ export class MigrationService {
runBeforeVersion: '1.5.0',
run: [storeCoursePreferencesByShortcode, invalidateCache],
},
{
runBeforeVersion: '1.6.2',
run: [migrateCourseFilesCacheToDocumentsDirectory],
},
];

static needsMigration(preferences: PreferencesContextProps) {
Expand Down
63 changes: 50 additions & 13 deletions src/core/queries/courseHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import {
useQueryClient,
} from '@tanstack/react-query';

import { CourseRecentFile } from '../../features/courses/components/CourseRecentFileListItem';
import { CourseLectureSection } from '../../features/courses/types/CourseLectureSections';
import { notNullish } from '../../utils/predicates';
import { pluckData } from '../../utils/queries';
Expand All @@ -30,6 +29,10 @@ import {
usePreferencesContext,
} from '../contexts/PreferencesContext';
import { CourseOverview } from '../types/api';
import {
CourseDirectoryContentWithLocations,
CourseFileOverviewWithLocation,
} from '../types/files';
import { useGetExams } from './examHooks';

export const COURSES_QUERY_KEY = ['courses'];
Expand Down Expand Up @@ -193,7 +196,8 @@ export const useGetCourseFiles = (courseId: number) => {
() => {
return coursesClient
.getCourseFiles({ courseId: courseId })
.then(pluckData);
.then(pluckData)
.then(computeFileLocations);
},
{
staleTime: courseFilesStaleTime,
Expand Down Expand Up @@ -233,25 +237,58 @@ export const useGetCourseFilesRecent = (courseId: number) => {
};
};

const isFile = (
item: CourseDirectoryContentInner,
): item is { type: 'file' } & CourseFileOverview => item.type === 'file';

/**
* Extract a flat array of files contained into the given directory tree
* Assigns a location to each file
*/
const flattenFiles = (
directoryContent: CourseDirectoryContentInner[] | CourseFileOverview[],
const computeFileLocations = (
directoryContent: CourseDirectoryContentInner[],
location: string = '/',
): CourseRecentFile[] => {
const result: CourseRecentFile[] = [];
): CourseDirectoryContentWithLocations[] => {
const result: CourseDirectoryContentWithLocations[] = [];
directoryContent?.forEach(item => {
if (item.type === 'file') {
if (isFile(item)) {
result.push({ ...item, location });
} else {
result.push(
...flattenFiles(
(item as CourseDirectory).files,
result.push({
...item,
files: computeFileLocations(
item.files,
location.length === 1
? location + item.name
: location + '/' + item.name,
),
});
}
});
return result;
};

/**
* Extract a flat array of files contained into the given directory tree
*/
const flattenFiles = (
directoryContent:
| CourseDirectoryContentWithLocations[]
| CourseFileOverviewWithLocation[],
): CourseFileOverviewWithLocation[] => {
const result: CourseFileOverviewWithLocation[] = [];
directoryContent?.forEach(item => {
if (item.type === 'file') {
result.push(item);
} else {
result.push(
...flattenFiles(
(
item as Extract<
CourseDirectoryContentWithLocations,
{ type: 'directory' }
>
).files,
),
);
}
});
Expand All @@ -262,8 +299,8 @@ const flattenFiles = (
* Extract files from folders and sort them by decreasing createdAt
*/
const sortRecentFiles = (
directoryContent: CourseDirectoryContentInner[],
): CourseRecentFile[] => {
directoryContent: CourseDirectoryContentWithLocations[],
): CourseFileOverviewWithLocation[] => {
const flatFiles = flattenFiles(directoryContent);
return flatFiles.sort(
(a, b) => b.createdAt.getTime() - a.createdAt.getTime(),
Expand Down
12 changes: 12 additions & 0 deletions src/core/types/files.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { CourseFileOverview } from '@polito/api-client';
import type { CourseDirectory } from '@polito/api-client/models/CourseDirectory';

export type CourseFileOverviewWithLocation = CourseFileOverview & {
location: string;
};

export type CourseDirectoryContentWithLocations =
| ({ type: 'directory' } & CourseDirectory & {
files: CourseDirectoryContentWithLocations[];
})
| ({ type: 'file' } & CourseFileOverviewWithLocation);
Loading
Loading