Skip to content

Commit

Permalink
Archive export running ok
Browse files Browse the repository at this point in the history
  • Loading branch information
belinde committed Apr 23, 2024
1 parent 1bee0a1 commit e837e5b
Show file tree
Hide file tree
Showing 9 changed files with 72 additions and 35 deletions.
11 changes: 10 additions & 1 deletion src/components/InitialNotesList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ const style = StyleSheet.create({
alignItems: "center",
justifyContent: "space-between",
},
penta: {
display: "flex",
flexDirection: "column",
},
initialNotes: {
flexGrow: 1,
},
Expand All @@ -31,13 +35,18 @@ const style = StyleSheet.create({

export const InitialNotesList: FC<{
initialNotes: InitialNoteMap;
transpose?: number;
renderAction: (note: InitialNote, key: Part) => ReactNode;
trasposeElement: ReactNode;
children?: ReactNode;
}> = (props) => {
return (
<View style={style.card}>
<View style={style.display}>
<Pentagram notes={props.initialNotes} />
<View style={style.penta}>
<Pentagram notes={props.initialNotes} />
{props.trasposeElement}
</View>
<View style={style.initialNotes}>
{Object.entries(props.initialNotes)
.sort(([_k1, a], [_k2, b]) => {
Expand Down
6 changes: 3 additions & 3 deletions src/components/ScorePhoto.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { documentDirectory } from "expo-file-system";
import { FC } from "react";
import { Image, useWindowDimensions } from "react-native";
import { DOCUMENT_DIRECTORY, SCORE_PHOTO_RATIO } from "../constants";

export const ScorePhoto: FC<{ source: string; noCache?: number }> = (props) => {
const { width } = useWindowDimensions();

return (
<Image
height={width / 5}
height={width / SCORE_PHOTO_RATIO}
width={width}
resizeMode="contain"
source={{
uri: `${documentDirectory}${props.source}?no-cache=${props.noCache || Date.now()}`,
uri: `${DOCUMENT_DIRECTORY}${props.source}?no-cache=${props.noCache || Date.now()}`,
}}
/>
);
Expand Down
4 changes: 4 additions & 0 deletions src/components/SongDisplay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,12 @@ export const SongDisplay: FC<{ song: Song }> = ({ song }) => {
</View>
{song.image && <ScorePhoto source={song.image} />}
<InitialNotesList
transpose={song.transpose}
initialNotes={song.initialNotes}
renderAction={(initial) => <PlayNote note={initial.note} />}
trasposeElement={
<Text>Trasposto di {JSON.stringify(song.transpose)}</Text>
}
/>
<Text>{song.annotations}</Text>
</ScrollView>
Expand Down
26 changes: 17 additions & 9 deletions src/components/SongForm/SongPhotoManagement.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import { CameraView, useCameraPermissions } from "expo-camera/next";
import { deleteAsync, documentDirectory, moveAsync } from "expo-file-system";
import { deleteAsync, moveAsync } from "expo-file-system";
import { SaveFormat, manipulateAsync } from "expo-image-manipulator";
import { FC, MutableRefObject, useCallback, useRef, useState } from "react";
import { useWindowDimensions } from "react-native";
import { Button } from "react-native-paper";
import { DOCUMENT_DIRECTORY, SCORE_PHOTO_RATIO } from "../../constants";
import { Song } from "../../types";
import { ScorePhoto } from "../ScorePhoto";

export const SongPhotoManagement: FC<{
song: MutableRefObject<Song>;
}> = (props) => {
const { width } = useWindowDimensions();
const height = Math.round(width / 5);
const height = Math.round(width / SCORE_PHOTO_RATIO);
const [image, setImage] = useState(() => props.song.current.image);
const [noCache, setNoCache] = useState(Date.now());
const [status, requestPermissions] = useCameraPermissions();
Expand All @@ -34,7 +35,12 @@ export const SongPhotoManagement: FC<{
if (!camera.current) return;
setElaborating(true);
camera.current
.takePictureAsync({ exif: false, imageType: "jpg", quality: 1 })
.takePictureAsync({
exif: false,
imageType: "jpg",
quality: 1,
skipProcessing: true,
})
.then(async (picture) => {
if (picture) {
const cropped = await manipulateAsync(
Expand All @@ -43,15 +49,17 @@ export const SongPhotoManagement: FC<{
{
crop: {
originX: 0,
originY: picture.height / 2 - picture.width / 10,
originY:
picture.height / 2 -
picture.width / (SCORE_PHOTO_RATIO * 2),
width: picture.width,
height: picture.width / 5,
height: picture.width / SCORE_PHOTO_RATIO,
},
},
{
resize: {
width,
height,
width: width * 2,
height: height * 2,
},
},
],
Expand All @@ -60,7 +68,7 @@ export const SongPhotoManagement: FC<{
const filename = `score_${props.song.current.id}.jpeg`;
await moveAsync({
from: cropped.uri,
to: documentDirectory + filename,
to: DOCUMENT_DIRECTORY + filename,
});

props.song.current.image = filename;
Expand Down Expand Up @@ -91,7 +99,7 @@ export const SongPhotoManagement: FC<{
onPress={pickImage}
disabled={elaborating}
>
{capturing ? "Scatta foto" : "Modifica"}
{capturing || !image ? "Scatta foto" : "Modifica"}
</Button>
</>
);
Expand Down
4 changes: 4 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { documentDirectory } from "expo-file-system";
import { PentagramPreference, Section } from "./types";

export const DOCUMENT_DIRECTORY = `${documentDirectory}storage/`;
export const SCORE_PHOTO_RATIO = 5;

export const SECTIONS = [
"tenori",
"baritoni",
Expand Down
23 changes: 14 additions & 9 deletions src/functions.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import {
deleteAsync,
documentDirectory,
getInfoAsync,
makeDirectoryAsync,
readAsStringAsync,
writeAsStringAsync,
} from "expo-file-system";
import { SECTIONS } from "./constants";
import { DOCUMENT_DIRECTORY, SECTIONS } from "./constants";
import { InitialNote, Note, Section } from "./types";

export const createIdentifier = () =>
Expand All @@ -23,7 +23,7 @@ export const noteSorter = (a: InitialNote, b: InitialNote) => {
};

export const deleteFile = async (fileName: string) => {
await deleteAsync(documentDirectory + fileName).catch((e) => {
await deleteAsync(DOCUMENT_DIRECTORY + fileName).catch((e) => {
console.warn("Cannot delete file", fileName, e);
});
};
Expand All @@ -32,11 +32,13 @@ export const readJsonFile = async <T>(
fileName: string,
defaultValue: T
): Promise<T> => {
const info = await getInfoAsync(documentDirectory + fileName);
const file = DOCUMENT_DIRECTORY + fileName;
console.log("Reading file", file);
const info = await getInfoAsync(file);
if (!info.exists) {
return defaultValue;
}
const content = await readAsStringAsync(documentDirectory + fileName, {
const content = await readAsStringAsync(file, {
encoding: "utf8",
}).catch((e) => {
console.warn("Cannot open file", fileName, e);
Expand All @@ -46,11 +48,14 @@ export const readJsonFile = async <T>(
};

export const writeJsonFile = async <T>(fileName: string, data: T) => {
await writeAsStringAsync(documentDirectory + fileName, JSON.stringify(data), {
await makeDirectoryAsync(DOCUMENT_DIRECTORY, { intermediates: true }).catch(
(e) => console.warn("Cannot create directory", DOCUMENT_DIRECTORY, e)
);
const file = DOCUMENT_DIRECTORY + fileName;
console.log("Writing file", file);
await writeAsStringAsync(file, JSON.stringify(data), {
encoding: "utf8",
}).catch((e) => {
console.warn("Cannot write file", fileName, e);
});
}).catch((e) => console.warn("Cannot write file", fileName, e));
};

export const favoriteSectionNote = (section: Section): Note => {
Expand Down
26 changes: 14 additions & 12 deletions src/pages/Settings/SettingsSectionArchive.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { cacheDirectory, documentDirectory } from "expo-file-system";
import { cacheDirectory, deleteAsync } from "expo-file-system";
import { isAvailableAsync, shareAsync } from "expo-sharing";
import { FC, useCallback, useEffect, useState } from "react";
import { Button, ProgressBar, Text } from "react-native-paper";
import { zip } from "react-native-zip-archive";
import { subscribe, zip } from "react-native-zip-archive";
import { DOCUMENT_DIRECTORY } from "../../constants";
import { SettingsSection } from "./SettingsSection";

export const SettingsSectionArchive: FC = () => {
Expand All @@ -11,33 +12,34 @@ export const SettingsSectionArchive: FC = () => {
const [progress, setProgress] = useState(0);

const now = new Date();
const targetPath = `${cacheDirectory}/backup_${now.getFullYear()}-${now.getMonth()}-${now.getDate()}.meistru.zip`;
const targetPath = `${cacheDirectory}backup_${now.getFullYear()}-${now.getMonth()}-${now.getDate()}.meistru.zip`;

useEffect(() => {
isAvailableAsync().then(setCanShare);
}, []);

// useEffect(() => {
// const observer = subscribe(
// (evt) => evt.filePath === targetPath && setProgress(evt.progress)
// );
// return () => observer.remove();
// }, [targetPath]);
useEffect(() => {
const observer = subscribe(
(evt) => evt.filePath === targetPath && setProgress(evt.progress)
);
return () => observer.remove();
}, [targetPath]);

const doBackup = useCallback(async () => {
if (!canShare || !documentDirectory || !cacheDirectory) return;
if (!canShare || !cacheDirectory) return;
setElaboratingBackup(true);
setProgress(0);

try {
console.log("Zipping...", { documentDirectory, targetPath });
await zip(documentDirectory + "cacca", targetPath);
await zip(DOCUMENT_DIRECTORY, targetPath);
await shareAsync(targetPath, {
mimeType: "application/zip",
dialogTitle: "Esporta archivio",
});
} catch (err) {
console.error(err);
} finally {
await deleteAsync(targetPath);
setElaboratingBackup(false);
}
}, [canShare, targetPath]);
Expand Down
6 changes: 5 additions & 1 deletion src/serialization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type CompressedSong = [
string, // artist
string, // annotations
CompressedInitialNote[],
number | undefined, // transpose
];

export const isCompressedSong = (data: unknown): data is CompressedSong =>
Expand All @@ -43,7 +44,8 @@ export const isCompressedSong = (data: unknown): data is CompressedSong =>
note[2].length === 1 &&
(note[3] === "" || note[3] === "#" || note[3] === "b") &&
typeof note[4] === "number"
);
) &&
(typeof data[5] === "undefined" || typeof data[5] === "number");

export const serializeSong = (song: Song): string => {
const compressed: CompressedSong = [
Expand All @@ -58,6 +60,7 @@ export const serializeSong = (song: Song): string => {
note.note.alteration || "",
note.note.octave,
]),
song.transpose || 0,
];
return JSON.stringify(compressed);
};
Expand All @@ -79,6 +82,7 @@ export const unserializeSong = (data: string): Song | null => {
artist: compressed[2],
annotations: compressed[3],
initialNotes: {},
transpose: compressed[5] || undefined,
};

compressed[4].forEach((note) => {
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export type Song = {
artist: string;
annotations: string;
initialNotes: InitialNoteMap;
transpose?: number;
image?: string;
};

Expand Down

0 comments on commit e837e5b

Please sign in to comment.