这是indexloc提供的服务,不要输入任何密码
Skip to content

Milestone 3: Publishing #393

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

Merged
merged 28 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
c7d6025
feat : add butoon to add document
WidaSuryani Jun 19, 2024
e8eee02
fix : add icon for loading
WidaSuryani Jun 21, 2024
20d14ba
fix : update function to create document
WidaSuryani Jun 21, 2024
b334809
fix : update error createdAt
WidaSuryani Jun 29, 2024
85e2b81
Updating config utility
DennisAlund Jun 30, 2024
7403166
Adding cloud function for publishing and unpublishing
DennisAlund Jul 1, 2024
ce43061
Updating `publishedAt` type
DennisAlund Jul 1, 2024
e4be536
Implementing support for scheduling
DennisAlund Jul 1, 2024
6a58de2
Fixing lint issues
DennisAlund Jul 1, 2024
3059076
Merge pull request #387 from oddbit/issue/382-cloud-function-for-publ…
DennisAlund Jul 7, 2024
2bbfd0f
Merge pull request #388 from oddbit/issue/383-implement-scheduling-of…
DennisAlund Jul 7, 2024
9273a56
Merge branch 'milestone/3-publishing' into issue/366-create-a-new-doc…
WidaSuryani Jul 16, 2024
6c8527b
fix : update model
WidaSuryani Jul 16, 2024
06343b9
fix : use button component
WidaSuryani Jul 16, 2024
2eaf964
fix : delete unuse code
WidaSuryani Jul 16, 2024
20fbf73
fix : refactor
WidaSuryani Jul 16, 2024
5fe9fa4
fix : refactoring create article
WidaSuryani Jul 17, 2024
544a13a
Merge pull request #386 from oddbit/issue/366-create-a-new-document-type
DennisAlund Jul 17, 2024
c281fff
Merge branch 'main' into milestone/3-publishing
muzanella11 Jul 30, 2024
d6e317a
add publish button
muzanella11 Jul 30, 2024
c292dd4
refactor crud tanam document
muzanella11 Jul 31, 2024
3fb39a7
remove unused
muzanella11 Jul 31, 2024
c9a2c85
add toggle publish document
muzanella11 Jul 31, 2024
d5d4305
Updating model's status implementation
DennisAlund Aug 2, 2024
443045e
Updating document hook and toggle component
DennisAlund Aug 2, 2024
0424873
Removing unused import
DennisAlund Aug 2, 2024
1d1d934
Merge pull request #421 from oddbit/issue/380-toggle-publish-unpublis…
DennisAlund Aug 2, 2024
52aeb06
Merge branch 'main' into milestone/3-publishing
DennisAlund Aug 2, 2024
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
23 changes: 23 additions & 0 deletions functions/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,27 @@
export class TanamConfig {
static get projectId(): string {
const projectId = process.env.GOOGLE_CLOUD_PROJECT || process.env.GCLOUD_PROJECT || process.env.GCP_PROJECT;

if (!projectId) {
throw new Error("Could not find project ID in any variable");
}

return projectId;
}

static get cloudFunctionRegion(): string {
return "us-central1";
}

/**
* Get flag for whether the functions are running in emulator or not.
* This can be derived by checking the existence of any emulator provided
* variables.
*/
static get isEmulated(): boolean {
return !!process.env.FIREBASE_EMULATOR_HUB;
}

static get databaseName(): string {
return process.env.database || "(default)";
}
Expand Down
173 changes: 173 additions & 0 deletions functions/src/document-publish.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import * as admin from "firebase-admin";
import {Timestamp} from "firebase-admin/firestore";
import {getFunctions} from "firebase-admin/functions";
import {getStorage} from "firebase-admin/storage";
import {logger} from "firebase-functions/v2";
import {onDocumentWritten} from "firebase-functions/v2/firestore";
import {onTaskDispatched} from "firebase-functions/v2/tasks";
import {ITanamDocument} from "./models/TanamDocument";
import {TanamDocumentAdmin} from "./models/TanamDocumentAdmin";

const db = admin.firestore();
const storage = getStorage().bucket();

// Document publish change handler
// This function is handling updates when a document is published or unpublished.
// It will ignore updates that does not change the publish status of the document.
export const onPublishChange = onDocumentWritten("tanam-documents/{documentId}", async (event) => {
const documentId = event.params.documentId;
const unpublishQueue = getFunctions().taskQueue("taskUnpublishDocument");
const publishQueue = getFunctions().taskQueue("taskPublishDocument");
if (!event.data || !event.data.after.exists) {
logger.info("Document was deleted. Unpublishing document.");
return unpublishQueue.enqueue({documentId});
}

const documentBeforeData = (event.data.before.data() || {}) as ITanamDocument<Timestamp>;
const documentBefore = new TanamDocumentAdmin(documentId, documentBeforeData);

const documentAfterData = (event.data.after.data() || {}) as ITanamDocument<Timestamp>;
const documentAfter = new TanamDocumentAdmin(documentId, documentAfterData);

if (documentBefore.status === documentAfter.status) {
logger.info("Document status did not change. Skipping.");
return;
}

if (documentAfter.status === "published") {
logger.info("Document was published.");
return publishQueue.enqueue({documentId});
}

if (documentBefore.status === "published") {
logger.info("Document was unpublished", documentAfter.toJson());
await unpublishQueue.enqueue({documentId});
}

const publishedAt = documentAfter.publishedAt?.toDate();
if (documentAfter.status === "scheduled" && !!publishedAt) {
logger.info("Document has been scheduled", documentAfter.toJson());
if (publishedAt !== normalizeDateToMaxOffset(publishedAt)) {
logger.error("Scheduled date is too far in the future", documentAfter.toJson());
throw new Error("Scheduled date is too far in the future");
}

logger.info(`Enqueueing document for publishing at ${publishedAt}`, documentAfter.toJson());
await publishQueue.enqueue(
{documentId},
{
scheduleTime: publishedAt,
},
);
}
});

// Task to publish a document
// This task is responsible for copying the document data to the public collection
// and copying associated files to the cloud storage public directory.
export const taskPublishDocument = onTaskDispatched(
{
retryConfig: {
maxAttempts: 3,
minBackoffSeconds: 60,
},
rateLimits: {
// Try to give room for concurrency of documents in firestore
maxDispatchesPerSecond: 1,
},
},
async (req) => {
const documentId = req.data.documentId;
const documentRef = db.collection("tanam-documents").doc(documentId);
const publicDocumentRef = db.collection("tanam-public").doc(documentId);
const snap = await documentRef.get();

if (!snap.exists) {
logger.error(`Document does not exist anymore: ${documentId}`);
return;
}

const documentData = snap.data();
if (!documentData) {
logger.error(`Document data is empty: ${documentId}`);
return;
}
const document = new TanamDocumentAdmin(documentId, documentData as ITanamDocument<Timestamp>);

if (document.status !== "published") {
// This could happen if the document changed status while the task was in the queue
logger.info("Document is no longer published. Stop here.");
return;
}

const promises = [];

// Copy document data to public collection
promises.push(publicDocumentRef.set(documentData));

// Copy associated files to public directory
const [files] = await storage.getFiles({prefix: `tanam-documents/${documentId}/`});
for (const file of files) {
const publishedFileName = file.name.replace("tanam-documents/", "tanam-public/");
promises.push(storage.file(file.name).copy(storage.file(publishedFileName)));
}

await Promise.all(promises);
},
);

// Task to unpublish a document
// This task is responsible for removing the document from the public collection
// and deleting associated files from the cloud storage public directory.
export const taskUnpublishDocument = onTaskDispatched(
{
retryConfig: {
maxAttempts: 3,
minBackoffSeconds: 60,
},
rateLimits: {
// Adjust for concurrency of documents in firestore
maxDispatchesPerSecond: 1,
},
},
async (req) => {
const documentId = req.data.documentId;
const publicDocumentRef = db.collection("tanam-public").doc(documentId);
const documentRef = db.collection("tanam-documents").doc(documentId);
const snap = await documentRef.get();

const documentData = snap.data();
const document = new TanamDocumentAdmin(documentId, documentData as ITanamDocument<Timestamp>);

if (document.status === "published") {
// This could happen if the document changed status while the task was in the queue
logger.info("Document is in status published. Stop here.");
return;
}

// Remove document from public collection
const promises = [publicDocumentRef.delete()];

// Delete associated files from public directory
const [files] = await storage.getFiles({prefix: `tanam-public/${documentId}/`});
for (const file of files) {
promises.push(storage.file(file.name).delete().then());
}

await Promise.all(promises);
},
);

/**
* Normalize a date to a maximum offset from now
*
* @param {Date} date A date to normalize
* @param {number} hours Optional. Default is 720 hours (30 days)
* @return {Date} The normalized date
*/
function normalizeDateToMaxOffset(date: Date, hours = 720): Date {
const now = new Date();
const maxDate = new Date(now.getTime() + hours * 60 * 60 * 1000);

return date > maxDate ? maxDate : date;
}
1 change: 1 addition & 0 deletions functions/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ import admin from "firebase-admin";
const app = admin.initializeApp();
app.firestore().settings({ignoreUndefinedProperties: true});

export * from "./document-publish";
export * from "./triggers/users";
14 changes: 6 additions & 8 deletions functions/src/models/TanamDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ export interface ITanamDocument<TimestampType> {
data: DocumentData;
documentType: string;
revision?: number;
publishedAt?: Date;
createdAt: TimestampType;
updatedAt: TimestampType;
publishedAt?: TimestampType;
createdAt?: TimestampType;
updatedAt?: TimestampType;
}

export abstract class TanamDocument<TimestampType, FieldValueType> {
Expand All @@ -27,16 +27,14 @@ export abstract class TanamDocument<TimestampType, FieldValueType> {
public readonly id: string;
public data: DocumentData;
public documentType: string;
public publishedAt?: Date;
public publishedAt?: TimestampType;
public revision: number;
public readonly createdAt: TimestampType;
public readonly updatedAt: TimestampType;
public readonly createdAt?: TimestampType;
public readonly updatedAt?: TimestampType;

get status(): TanamPublishStatus {
if (!this.publishedAt) {
return "unpublished";
} else if (this.publishedAt > new Date()) {
return "scheduled";
} else {
return "published";
}
Expand Down
2 changes: 1 addition & 1 deletion functions/src/models/TanamDocumentAdmin.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {FieldValue, Timestamp} from "firebase-admin/firestore";
import {ITanamDocument, TanamDocument} from "./TanamDocument";
import {DocumentSnapshot} from "firebase-functions/v2/firestore";
import {ITanamDocument, TanamDocument} from "./TanamDocument";

export class TanamDocumentAdmin extends TanamDocument<Timestamp, FieldValue> {
constructor(id: string, json: ITanamDocument<Timestamp>) {
Expand Down
12 changes: 10 additions & 2 deletions hosting/package-lock.json

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

1 change: 1 addition & 0 deletions hosting/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"codecheck": "npm run prettier:fix && npm run lint:fix"
},
"dependencies": {
"@iconify-json/line-md": "^1.1.37",
"@tiptap/extension-code-block-lowlight": "^2.4.0",
"@tiptap/extension-floating-menu": "^2.5.5",
"@tiptap/extension-underline": "^2.4.0",
Expand Down
18 changes: 17 additions & 1 deletion hosting/src/app/(protected)/content/[documentTypeId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {useTanamDocuments} from "@/hooks/useTanamDocuments";
import {Suspense, useEffect, useState} from "react";
import {useParams} from "next/navigation";
import {UserNotification} from "@/models/UserNotification";
import {Button} from "@/components/Button";

export default function DocumentTypeDocumentsPage() {
const {documentTypeId} = useParams<{documentTypeId: string}>() ?? {};
Expand All @@ -19,10 +20,25 @@ export default function DocumentTypeDocumentsPage() {
setNotification(docsError);
}, [docsError]);

const addNewDocument = async () => {};

return (
<>
<Suspense fallback={<Loader />}>
{documentType ? <PageHeader pageName={documentType.titlePlural.translated} /> : <Loader />}
{documentType ? (
<div className="flex items-center gap-4">
<PageHeader pageName={documentType.titlePlural.translated} />{" "}
<div className="mb-6">
<Button
onClick={addNewDocument}
title={`Add New ${documentType.titleSingular.translated}`}
style="rounded"
/>
</div>
</div>
) : (
<Loader />
)}
</Suspense>
{notification && (
<Notification type={notification.type} title={notification.title} message={notification.message} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default function DocumentDetailsPage() {
const router = useRouter();
const {documentId} = useParams<{documentId: string}>() ?? {};
const {data: document, error: documentError} = useTanamDocument(documentId);
const {update, error: writeError} = useCrudTanamDocument(documentId);
const {update, error: writeError} = useCrudTanamDocument();
const [readonlyMode] = useState<boolean>(false);
const [notification, setNotification] = useState<UserNotification | null>(null);
if (!!document?.documentType && document?.documentType !== "article") {
Expand All @@ -26,7 +26,12 @@ export default function DocumentDetailsPage() {

async function onDocumentContentChange(content: string) {
console.log("[onDocumentContentChange]", content);
await update({data: {...document?.data, content}});
if (!document) {
return;
}

document.data.content = content;
await update(document);
}

return (
Expand Down
Loading