Skip to content

Commit

Permalink
whattheduck: Load data from cache before downloading live data
Browse files Browse the repository at this point in the history
  • Loading branch information
bperel committed Sep 30, 2024
1 parent c001551 commit d127b1a
Show file tree
Hide file tree
Showing 12 changed files with 205 additions and 90 deletions.
18 changes: 9 additions & 9 deletions apps/dumili/src/components/Entry.vue
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
"{numberOfStories} histoires trouvées avec ces mots-clés",
{
numberOfStories: pages[0].aiOcrPossibleStories.length,
}
},
)
}}
<table-tooltip
Expand Down Expand Up @@ -164,10 +164,10 @@ const { indexation, acceptedStories, acceptedStoryKinds, entriesFirstPages } =
const pages = computed(() => {
const { startsAtPage, endsAtPage } = entriesFirstPages.value.find(
({ entryId }) => entry.value.id === entryId
({ entryId }) => entry.value.id === entryId,
)!;
return indexation.value!.pages.filter(
({ pageNumber }) => pageNumber >= startsAtPage && pageNumber <= endsAtPage
({ pageNumber }) => pageNumber >= startsAtPage && pageNumber <= endsAtPage,
);
});
Expand All @@ -177,16 +177,16 @@ const acceptedStory = computed(() => acceptedStories.value[props.entry.id]);
const storyKindAiSuggestion = computed(() =>
entry.value.storyKindSuggestions.find(
({ aiSourcePageId }) => aiSourcePageId !== null
)
({ aiSourcePageId }) => aiSourcePageId !== null,
),
);
const storyAiSuggestions = computed(() =>
entry.value.storySuggestions.filter(({ ocrDetailsId }) => ocrDetailsId)
entry.value.storySuggestions.filter(({ ocrDetailsId }) => ocrDetailsId),
);
const acceptedStoryKind = computed(
() => acceptedStoryKinds.value[props.entry.id]
() => acceptedStoryKinds.value[props.entry.id],
);
const storycode = computed(() => acceptedStory.value?.storyversion.storycode);
Expand All @@ -195,15 +195,15 @@ const title = computed(() => entry.value.title || $t("Sans titre"));
const comment = computed(() => entry.value.entrycomment);
const urlEncodedStorycode = computed(
() => storycode.value && encodeURIComponent(storycode.value)
() => storycode.value && encodeURIComponent(storycode.value),
);
const getStoryKind = (storyKind: storyKind) =>
storyKinds.find(({ code }) => code === storyKind)?.label;
const acceptStoryKindSuggestion = (kind: storyKind) => {
getIndexationSocket(
entry.value.indexationId
entry.value.indexationId,
).services.acceptStoryKindSuggestion({
entryId: entry.value.id,
kind,
Expand Down
4 changes: 1 addition & 3 deletions apps/edgecreator/api/services/text/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@ const generateImage = (parameters: {
);
}
})
.catch((response: Error) => {
return Promise.reject(response);
})
.catch((response: Error) => Promise.reject(response))
.then(() =>
cloudinary.uploader.upload(
`${process.env.FONT_IMAGE_GEN_URL!}?${new URLSearchParams({
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/components/InducksStory.vue
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const tagName = computed(() => (showLink.value === "outer" ? "a" : "span"));
const url = computed(
() =>
storycode.value &&
`https://inducks.org/story.php?c=${encodeURIComponent(storycode.value)}`
`https://inducks.org/story.php?c=${encodeURIComponent(storycode.value)}`,
);
const storyTypeText = computed(() => {
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/composables/useDmSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ const defaultExport = (
socket.onConnected = onConnected;
}
return {
socket,
options,
publicCollection: socket.addNamespace<PublicCollectionServices>(
PublicCollectionServices.namespaceEndpoint,
Expand Down
8 changes: 4 additions & 4 deletions apps/web/src/stores/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,13 @@ export const collection = defineStore("collection", () => {
await collectionServices.deletePurchase(id);
await loadPurchases(true);
},
fetchIssueCountsByCountrycode = async () => {
if (!coaIssueCountsByPublicationcode.value)
fetchIssueCountsByCountrycode = async (force = false) => {
if (!coaIssueCountsByPublicationcode.value || force)
coaIssueCountsPerCountrycode.value =
await collectionServices.getCoaCountByCountrycode();
},
fetchIssueCountsByPublicationcode = async () => {
if (!coaIssueCountsByPublicationcode.value)
fetchIssueCountsByPublicationcode = async (force = false) => {
if (!coaIssueCountsByPublicationcode.value || force)
coaIssueCountsByPublicationcode.value =
await collectionServices.getCoaCountByPublicationcode();
},
Expand Down
19 changes: 12 additions & 7 deletions apps/web/src/stores/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,18 @@ export const users = defineStore("users", () => {
count.value = await globalStatsServices.getUserCount();
}
},
fetchStats = async (userIds: number[] /*, clearCacheEntry = true*/) => {
const missingUserIds = [...new Set(userIds)].filter(
(userId) =>
!Object.keys(points.value)
.map((userIdHavingPoints) => parseInt(userIdHavingPoints))
.includes(userId),
);
fetchStats = async (userIds: number[], force = false) => {
let missingUserIds;
if (force) {
missingUserIds = userIds;
} else {
missingUserIds = [...new Set(userIds)].filter(
(userId) =>
!Object.keys(points.value)
.map((userIdHavingPoints) => parseInt(userIdHavingPoints))
.includes(userId),
);
}
if (!missingUserIds.length) return;

const data =
Expand Down
27 changes: 16 additions & 11 deletions apps/whattheduck/src/App.vue
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
<template>
<ion-app>
<ion-progress-bar v-if="bundleDownloadProgress" :value="bundleDownloadProgress"></ion-progress-bar>
<OfflineBanner :on-offline="routeMeta.onOffline" v-if="isOfflineMode" />

<ion-router-outlet
v-if="route.path === '/login' || route.path === '/test'"
:style="{ 'margin-top': `${offlineBannerHeight}px` }"
id="main-content"
:class="{ 'greyed-out': bundleDownloadProgress !== undefined }"
/>
<AppWithPersistedData v-else-if="socket" />
</ion-app>
Expand Down Expand Up @@ -33,6 +35,8 @@ const { isOfflineMode, token, socket, offlineBannerHeight } = storeToRefs(appSto
const route = useRoute();
const router = useRouter();
const bundleDownloadProgress = ref<number | undefined>(undefined);
interface RouteMeta {
onOffline?: 'readonly' | 'unavailable';
onNoToken?: 'logout';
Expand Down Expand Up @@ -65,15 +69,7 @@ const assignSocket = () => {
return undefined;
}
const { value, ttl, timestamp } = JSON.parse(item);
const now = Date.now();
if (now - timestamp > ttl) {
storage.remove(key);
return undefined;
}
return value;
return JSON.parse(item);
},
remove: (key) => storage.remove(key),
clear: () => storage.clear(),
Expand Down Expand Up @@ -114,11 +110,20 @@ watch(token, async () => {
assignSocket();
const currentBundleVersion = (await CapacitorUpdater.current())?.bundle.version;
const bundle = await socket.value!.app.services.getBundleUrl({ version: currentBundleVersion });
if ('url' in bundle && bundle.url) {
if (Capacitor.isNativePlatform() && 'url' in bundle && bundle.url) {
CapacitorUpdater.addListener('download', ({ percent }) => {
bundleDownloadProgress.value = percent / 100;
});
const bundleInfo = await CapacitorUpdater.download(bundle);
await CapacitorUpdater.set(bundleInfo);
} else {
console.warn(bundle.error);
switch (bundle.error) {
case 'Already up to date':
console.log('Bundle is already up to date');
break;
default:
console.warn(bundle.error);
}
}
}
});
Expand Down
1 change: 0 additions & 1 deletion apps/whattheduck/src/components/List.vue
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,6 @@ watch(isCameraPreviewShown, async () => {
}),
{},
) as DOMRect;
console.log(boundingClientRect);
if (boundingClientRect.height) {
clearInterval(interval);
Expand Down
76 changes: 45 additions & 31 deletions apps/whattheduck/src/stores/wtdcollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,13 @@ export type purchaseWithStringDate = Omit<purchase, 'date' | 'userId'> & {
export const wtdcollection = defineStore('wtdcollection', () => {
const coaStore = webStores.coa();
const webCollectionStore = webStores.collection();
const { issues, purchases, user } = storeToRefs(webCollectionStore);
const statsStore = webStores.stats();
const usersStore = webStores.users();
const { quotedIssues, quotationSum } = webComposables.useCollection(
issues as ShallowRef<(issue & { issuecode: string })[]>,
);

const {
createPurchase,
findInCollection,
fetchIssueCountsByCountrycode,
fetchIssueCountsByPublicationcode,
fetchPublicationNames,
isLoadingSuggestions,
loadCollection,
loadPurchases,
Expand All @@ -36,6 +31,27 @@ export const wtdcollection = defineStore('wtdcollection', () => {
updateCollectionMultipleIssues,
} = webCollectionStore;

const {
coaIssueCountsByPublicationcode,
coaIssueCountsPerCountrycode,
issues,
issuesByIssuecode,
numberPerCondition,
purchases,
purchasesById,
suggestions,
total,
totalPerCountry,
totalPerPublication,
totalUniqueIssues,
user,
} = storeToRefs(webCollectionStore);
const statsStore = webStores.stats();
const usersStore = webStores.users();
const { quotedIssues, quotationSum } = webComposables.useCollection(
issues as ShallowRef<(issue & { issuecode: string })[]>,
);

const ownedCountries = computed(() =>
ownedPublications.value
? [...new Set((ownedPublications.value || []).map((publicationcode) => publicationcode.split('/')[0]))].sort()
Expand All @@ -46,25 +62,23 @@ export const wtdcollection = defineStore('wtdcollection', () => {
? [...new Set((issues.value || []).map(({ publicationcode }) => publicationcode))].sort()
: issues.value,
),
fetchAndTrackCollection = async () => {
await loadCollection();
await loadPurchases();
await loadUser();
fetchCollection = async (force = false) => {
await loadCollection(force);
await loadPurchases(force);
await loadUser(force);
await coaStore.fetchCountryNames(true);
coaStore.addPublicationNames(await webCollectionStore.fetchPublicationNames());
await usersStore.fetchStats([webCollectionStore.user?.id || 0]);
coaStore.addPublicationNames(await fetchPublicationNames());
await usersStore.fetchStats([webCollectionStore.user?.id || 0], force);
// TODO retrieve user notification countries

await fetchIssueCountsByCountrycode();
await fetchIssueCountsByPublicationcode();
await fetchIssueCountsByCountrycode(force);
await fetchIssueCountsByPublicationcode(force);

// TODO get app version
(async () => {
await loadSuggestions({ countryCode: 'ALL', sinceLastVisit: false });
await statsStore.loadRatings();
// TODO register for notifications
})();

// TODO register for notifications
},
highestQuotedIssue = computedAsync(async () => {
const issue = quotedIssues.value?.sort((a, b) => b.estimationGivenCondition - a.estimationGivenCondition)[0];
Expand All @@ -78,36 +92,36 @@ export const wtdcollection = defineStore('wtdcollection', () => {
issues.value!.filter(({ issuecode: collectionIssuecode }) => collectionIssuecode === issuecode);

return {
issues,
coaIssueCountsByPublicationcode,
coaIssueCountsPerCountrycode,
createPurchase,
fetchAndTrackCollection,
fetchCollection,
fetchIssueCountsByPublicationcode,
findInCollection,
getCollectionIssues,
highestQuotedIssue,
coaIssueCountsByPublicationcode: computed(() => webCollectionStore.coaIssueCountsByPublicationcode),
coaIssueCountsPerCountrycode: computed(() => webCollectionStore.coaIssueCountsPerCountrycode),
isLoadingSuggestions,
issuesByIssuecode: computed(() => webCollectionStore.issuesByIssuecode),
issues,
issuesByIssuecode,
loadCollection,
loadPurchases,
loadSuggestions,
loadUserIssueQuotations,
loadPurchases,
login,
numberPerCondition: computed(() => webCollectionStore.numberPerCondition),
numberPerCondition,
ownedCountries,
ownedPublications,
purchases,
purchasesById: computed(() => webCollectionStore.purchasesById),
purchasesById,
quotationSum,
signup,
suggestions: computed(() => webCollectionStore.suggestions),
total: computed(() => webCollectionStore.total),
totalPerCountry: computed(() => webCollectionStore.totalPerCountry),
totalPerPublication: computed(() => webCollectionStore.totalPerPublication),
totalUniqueIssues: computed(() => webCollectionStore.totalUniqueIssues),
updateCollectionSingleIssue,
suggestions,
total,
totalPerCountry,
totalPerPublication,
totalUniqueIssues,
updateCollectionMultipleIssues,
updateCollectionSingleIssue,
user,
};
});
Expand Down
5 changes: 5 additions & 0 deletions apps/whattheduck/src/theme/global.scss
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,9 @@ ion-checkbox {

.fab-button-in-list {
color: white
}

.greyed-out {
pointer-events: none;
opacity: 0.5;
}
Loading

0 comments on commit d127b1a

Please sign in to comment.