Skip to content

Commit

Permalink
now you can load even videos out of a burrito
Browse files Browse the repository at this point in the history
  • Loading branch information
danielc-n committed Oct 16, 2024
1 parent 8264292 commit b30a9bb
Show file tree
Hide file tree
Showing 9 changed files with 178 additions and 107 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,16 @@ const TranslationHelps = ({
const userProfile = await localforage.getItem('userProfile');
const resourceDirPath = path.join(newpath, packageInfo.name, 'users', userProfile?.username, 'resources');
const pathToIngredients = path.resolve(resourceDirPath, offlineResource.data.projectDir, 'ingredients');
setImagesPath(pathToIngredients);
if (pathToIngredients) {
const pathRelationFile = path.resolve(pathToIngredients, 'relation.txt');
if (fs.existsSync(pathRelationFile)) {
setImagesPath(pathToIngredients);
const relationFileContent = fs.readFileSync(pathRelationFile, 'utf8');
const fileName = findFileByPartialName(fs, path.resolve(resourceDirPath), relationFileContent);
const fileName = findFileByPartialName(fs, path.resolve(resourceDirPath), relationFileContent.trim());
setResourceLinkPath(path.resolve(resourceDirPath, fileName, 'ingredients'));
} else {
setImagesPath('');
setResourceLinkPath(pathToIngredients);
debug('TranslationHelps.js', `pathRelationFile : ${pathRelationFile} - Not found!`);
}
}
Expand All @@ -63,7 +65,7 @@ const TranslationHelps = ({
}

getLinkedFolderPath();
}, [imagesPath]);
}, [selectedResource, offlineResource]);

return (
<>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
/* eslint-disable */
// import PropTypes from 'prop-types';
import React, { useEffect, useState } from 'react';
import i18n from '../../../translations/i18n';
const { net } = require('electron');
// import {
// useContent,
// } from 'translation-helps-rcl';
Expand All @@ -23,6 +25,57 @@ export default function TranslationHelpsImageCard({

const convertToFileUrl = (path) => `file://${path}`;

const CACHE_DIR = path.join(folderPath);

const isVideoCached = (videoUrl) => {
const videoFileName = path.basename(videoUrl);
const localVideoPath = path.join(CACHE_DIR, videoFileName);
return fs.existsSync(localVideoPath) ? localVideoPath : null;
};

const downloadAndCacheVideo = (videoUrl) => {
return new Promise((resolve, reject) => {
const videoFileName = path.basename(videoUrl);
const localVideoPath = path.join(CACHE_DIR, videoFileName);

const request = net.request(videoUrl);
const fileStream = fs.createWriteStream(localVideoPath);

request.on('response', (response) => {
response.pipe(fileStream);
fileStream.on('finish', () => {
resolve(localVideoPath);
});
});

request.on('error', (err) => {
reject(err);
});

request.end();
});
};

const loadVideo = async (videoUrl) => {
// Check if video is already cached
let localVideoPath = isVideoCached(videoUrl);

if (!localVideoPath) {
// If not cached, download and cache the video
console.log(`Downloading and caching video: ${videoUrl}`);
localVideoPath = await downloadAndCacheVideo(videoUrl);
}

return localVideoPath;
};




if (!fs.existsSync(CACHE_DIR)) {
fs.mkdirSync(CACHE_DIR);
}

/**
* Function to get image paths from a TSV file based on book code, chapter, and verse.
*
Expand All @@ -32,55 +85,67 @@ export default function TranslationHelpsImageCard({
const fs = window.require('fs');
const path = require('path');
const filePath = path.join(folderPath, `${projectId}.tsv`);
const metadataJson = JSON.parse(fs.readFileSync(path.join(linkedFolderPath, '..', 'metadata.json')));
let metadataJson = JSON.parse(fs.readFileSync(path.join(linkedFolderPath, '..', 'metadata.json')));
const reference = `${chapter}:${verse}`;
const finalImagePaths = [];

// Check if the file exists
if (!fs.existsSync(filePath)) {
return [];
}

const reference = `${chapter}:${verse}`;
const finalImagePaths = [];



// Read the TSV file
const fileContent = fs.readFileSync(filePath, 'utf-8');

// Split the content into lines
const lines = fileContent.trim().split('\n');

// Loop through each line, starting from 1 to skip the header

let columns;
let realPath;
let dashedName;
let dashedNameSplited;
let localizedNameTmp;
for (let i = 1; i < lines.length; i++) {
columns = lines[i].split('\t');

// Check if the reference matches
if (columns[0] === reference) {
// Add the last column (image path) to the list
dashedName = columns[columns.length - 1].split('images/')[1];
dashedNameSplited = dashedName.split('/')[1];
localizedNameTmp = metadataJson.localizedNames[dashedNameSplited];
realPath = convertToFileUrl(path.join(linkedFolderPath, `${dashedName }.jpg`));
if (localizedNameTmp) {
localizedNameTmp = localizedNameTmp.short.en;
finalImagePaths.push([localizedNameTmp, realPath]);
} else {
finalImagePaths.push([dashedNameSplited, realPath]);
if (linkedFolderPath === '') {
metadataJson = JSON.parse(fs.readFileSync(path.join(folderPath, '..', 'metadata.json')));
// Loop through each line, starting from 1 to skip the header
for (let i = 1; i < lines.length; i++) {
columns = lines[i].split('\t');
// Check if the reference matches
if (columns[0] === reference) {
// Add the last column (image path) to the list
dashedName = columns[columns.length - 1].split('/').at(-1).split('.')[0];
localizedNameTmp = metadataJson.localizedNames[dashedName]?.short[i18n.language] ?? '';
finalImagePaths.push([localizedNameTmp, columns[columns.length - 1]]);
}
}
} else {
// Loop through each line, starting from 1 to skip the header
for (let i = 1; i < lines.length; i++) {
columns = lines[i].split('\t');

// Check if the reference matches
if (columns[0] === reference) {
// Add the last column (image path) to the list
dashedName = columns[columns.length - 1].split('images/')[1];
dashedNameSplited = dashedName.split('/')[1];
localizedNameTmp = metadataJson.localizedNames[dashedNameSplited];
realPath = convertToFileUrl(path.join(linkedFolderPath, `${dashedName }.jpg`));
if (localizedNameTmp) {
localizedNameTmp = localizedNameTmp.short[i18n.language] ?? localizedNameTmp.short.en ?? '';
finalImagePaths.push([localizedNameTmp, realPath]);
} else {
finalImagePaths.push([dashedNameSplited, realPath]);
}
}
}
}

return finalImagePaths;
};

useEffect(() => {
if (linkedFolderPath && linkedFolderPath !== '') {
setImagePaths(getImagePathsFromTSV());
}
}, [chapter, verse, projectId]);
setImagePaths(getImagePathsFromTSV());
}, [chapter, verse, projectId, linkedFolderPath]);

const [zoomedImage, setZoomedImage] = useState(null);

Expand All @@ -96,24 +161,33 @@ export default function TranslationHelpsImageCard({
<div className="image-gallery">
<div className="image-scroll">
{imagePaths.length > 0 && imagePaths
.sort((a, b) => a[0].localeCompare(b[0]))
.sort((a, b) => a[0].localeCompare(b[0])) // Sort by name
.map((imagePath, index) => (
<div key={index} className="image-wrapper">
<div className="image-name">{imagePath[0]}</div>
<img
key={index}
src={imagePath[1]}
alt={`Image ${index + 1}`}
className="gallery-image"
onClick={() => handleImageClick(imagePath[1], imagePath[0])}
/>
{/* Check if the path is a video (e.g., ends with .mp4) */}
{imagePath[1].match(/\.(mp4|webm|ogg)$/i) ? (
<video
key={index}
src={imagePath[1]}
controls
className="gallery-video"
/>
) : (
<img
key={index}
src={imagePath[1]}
alt={`Image ${index + 1}`}
className="gallery-image"
onClick={() => handleImageClick(imagePath[1], imagePath[0])}
/>
)}
</div>
))}
{imagePaths.length === 0
&& 'No resources image for this Chapter/Verse'}
{imagePaths.length === 0 && "No resources image/video for this Chapter/Verse"}
</div>

{zoomedImage && (
{zoomedImage && !zoomedImage.src.match(/\.(mp4|webm|ogg)$/i) && (
<div className="zoomed-image-container" onClick={closeZoom}>
<div className="zoomed-content">
<span className="close-zoom" onClick={closeZoom}>X</span>
Expand All @@ -122,6 +196,16 @@ export default function TranslationHelpsImageCard({
</div>
</div>
)}

{zoomedImage && zoomedImage.src.match(/\.(mp4|webm|ogg)$/i) && (
<div className="zoomed-image-container" onClick={closeZoom}>
<div className="zoomed-content">
<span className="close-zoom" onClick={closeZoom}>X</span>
<div className="zoomed-image-name">{zoomedImage.title}</div>
<video src={zoomedImage.src} controls className="zoomed-video" />
</div>
</div>
)}
</div>
);
}
4 changes: 3 additions & 1 deletion renderer/src/components/EditorPage/TextEditor/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ export default function TextEditor() {
const {
state: {
bookId: defaultBookId, selectedFont, editorFontSize, projectScriptureDir,
chapter,
verse,
},
actions: {
handleSelectedFont, onChangeChapter, onChangeVerse, handleEditorFontSize,
Expand Down Expand Up @@ -71,7 +73,7 @@ export default function TextEditor() {
const handleUsjChange = useMemo(
() => debounce(async (updatedUsj) => {
updateCacheNSaveFile(updatedUsj, book);
console.log('usj updated', updatedUsj);
// console.log('usj updated', updatedUsj);
}, 1000),
[book],
);
Expand Down
2 changes: 1 addition & 1 deletion renderer/src/components/Resources/ListResources.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ export const ListResources = ({
const reference = resources.find((r) => r.id === selectResource);
// filter for a resource OR an x-bcvnotes burrito
// const offlineResource = subMenuItems ? subMenuItems.filter((item) => (item?.value?.type?.flavorType?.flavor?.name === 'x-bcvnotes' || item?.value?.type?.flavorType?.flavor?.name === 'x-resourcelinks') || (item?.value?.agOffline && item?.value?.dublin_core?.identifier === selectResource)) : [];
const offlineResource = subMenuItems ? subMenuItems.filter((item) => (item?.value?.agOffline && item?.value?.dublin_core?.identifier === selectResource) || (item?.value?.type?.flavorType?.flavor?.name === 'x-bcvnotes' && selectResource === 'tn') || (item?.value?.type?.flavorType?.flavor?.name === 'x-imagedict' && selectResource === 'tir')) : [];
const offlineResource = subMenuItems ? subMenuItems.filter((item) => (item?.value?.agOffline && item?.value?.dublin_core?.identifier === selectResource) || (item?.value?.type?.flavorType?.flavor?.name === 'x-bcvnotes' && selectResource === 'tn') || ((item?.value?.type?.flavorType?.flavor?.name === 'x-imagedict' || item?.value?.type?.flavorType?.flavor?.name === 'x-videolinks') && selectResource === 'tir')) : [];

return { reference, offlineResource };
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export const fetchTranslationResource = async (urlpath, setResource, selectResou
if (selectResource === 'tn') {
filteredRepos = fetchedJson.filter((repo) => repo.topics.includes('burrito' && 'bcvnotes'));
} else if (selectResource === 'tir') {
filteredRepos = fetchedJson.filter((repo) => repo.topics.includes('burrito' && 'imagedict'));
filteredRepos = fetchedJson.filter((repo) => repo.topics.includes('burrito' && 'imagedict') || repo.topics.includes('burrito' && 'videolinks') );
filteredReposResourcelinks = fetchedJson.filter((repo) => repo.topics.includes('burrito' && 'resourcelinks'));
}

Expand Down
14 changes: 7 additions & 7 deletions renderer/src/components/context/ProjectContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { isElectron } from '../../core/handleElectron';
import * as logger from '../../logger';
import { saveProjectsMeta, saveSupabaseProjectsMeta } from '../../core/projects/saveProjetcsMeta';
import { environment } from '../../../environment';
import staicLangJson from '../../lib/lang/langNames.json';
import staticLangJson from '../../lib/lang/langNames.json';
import packageInfo from '../../../../package.json';

import {
Expand All @@ -28,7 +28,7 @@ const ProjectContextProvider = ({ children }) => {
const [drawer, setDrawer] = useState(false);
const [scrollLock, setScrollLock] = useState(false);
const [sideTabTitle, setSideTabTitle] = useState('New');
const [languages, setLanguages] = useState(staicLangJson);
const [languages, setLanguages] = useState(staticLangJson);
const [language, setLanguage] = useState({});
const [customLanguages, setCustomLanguages] = useState([]);

Expand Down Expand Up @@ -150,7 +150,7 @@ const ProjectContextProvider = ({ children }) => {
});
}
};
const concatLanguages = async (json, staicLangJson) => {
const concatLanguages = async (json, staticLangJson) => {
logger.debug('ProjectContext.js', 'In concat languages');
const userlanguages = [];
json.history?.languages?.forEach((userLang) => {
Expand All @@ -163,9 +163,9 @@ const ProjectContextProvider = ({ children }) => {
userlanguages.push(obj);
});
const concatedLang = userlanguages.length > 0
? (staicLangJson)
? (staticLangJson)
.concat(userlanguages)
: staicLangJson;
: staticLangJson;
return { concatedLang, userlanguages };
};

Expand Down Expand Up @@ -211,7 +211,7 @@ const ProjectContextProvider = ({ children }) => {
.concat(json.history?.textTranslation.canonSpecification)
: advanceSettings.canonSpecification);
// concat static and custom languages
const langFilter = await concatLanguages(json, staicLangJson);
const langFilter = await concatLanguages(json, staticLangJson);
const filteredLang = langFilter.concatedLang.filter((lang) => lang?.ang.trim() !== '');
setLanguages([...filteredLang]);
setCustomLanguages(langFilter.userlanguages);
Expand Down Expand Up @@ -262,7 +262,7 @@ const ProjectContextProvider = ({ children }) => {
.concat(json.history?.textTranslation.canonSpecification)
: advanceSettings.canonSpecification);
// concat static and custom languages
const langFilter = await concatLanguages(json, staicLangJson);
const langFilter = await concatLanguages(json, staticLangJson);
const filteredLang = langFilter.concatedLang.filter((lang) => lang?.ang.trim() !== '');
setLanguages([...filteredLang]);
setCustomLanguages(langFilter.userlanguages);
Expand Down
2 changes: 1 addition & 1 deletion renderer/src/translations/en.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export const En = {
'label-resource-obs-tq': 'OBS Translation Questions',
'label-resource-obs': 'Open Bible Stories',
'label-resource-tn': 'Translation Notes',
'label-resource-tir': 'Translation Image Resources',
'label-resource-tir': 'Translation Multimedia Resources',
'label-resource-twlm': 'Translation Words',
'label-resource-twl': 'Translation Word Links',
'label-resource-tq': 'Translation Questions',
Expand Down
2 changes: 1 addition & 1 deletion renderer/src/translations/id.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export const Id = {
'label-resource-obs-tq': 'OBS Translation Questions',
'label-resource-obs': 'Open Bible Stories',
'label-resource-tn': 'Translation Notes',
'label-resource-tir': 'Translation Image Resources',
'label-resource-tir': 'Translation Multimedia Resources',
'label-resource-twlm': 'Translation Words',
'label-resource-twl': 'Translation Word Links',
'label-resource-tq': 'Translation Questions',
Expand Down
Loading

0 comments on commit b30a9bb

Please sign in to comment.