@openpeepshq/core 0.1.35 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/analytics/report.d.ts +1 -1
  2. package/dist/config/defaults/logs.d.ts +4 -0
  3. package/dist/config/defaults/logs.js +5 -0
  4. package/dist/config/index.d.ts +8 -0
  5. package/dist/db/pg/filters/posts.js +1 -1
  6. package/dist/groups/finders.d.ts +2 -2
  7. package/dist/groups/helpers.d.ts +6 -6
  8. package/dist/groups/mapping.d.ts +4 -4
  9. package/dist/jams/helpers.d.ts +2 -2
  10. package/dist/jams/livekit.d.ts +2 -2
  11. package/dist/jams/mapping.d.ts +10 -10
  12. package/dist/jams/mutations.d.ts +2 -2
  13. package/dist/log/index.d.ts +1 -0
  14. package/dist/log/index.js +1 -0
  15. package/dist/log/retention.d.ts +9 -0
  16. package/dist/log/retention.js +83 -0
  17. package/dist/log/retentionJobs.d.ts +17 -0
  18. package/dist/log/retentionJobs.js +50 -0
  19. package/dist/media/index.js +87 -10
  20. package/dist/mediaAttachments/mapping.d.ts +1 -1
  21. package/dist/notifications/defaultNotifications/jamModerator/index.js +25 -16
  22. package/dist/notifications/defaultNotifications/jamModerator/recipients.d.ts +2 -0
  23. package/dist/notifications/defaultNotifications/jamModerator/recipients.js +5 -0
  24. package/dist/notifications/defaultNotifications/newGroupPost/index.js +3 -3
  25. package/dist/notifications/defaultNotifications/newGroupPost/recipients.d.ts +5 -0
  26. package/dist/notifications/defaultNotifications/newGroupPost/recipients.js +23 -0
  27. package/dist/notifications/eventIcsAttachment.d.ts +6 -0
  28. package/dist/notifications/eventIcsAttachment.js +32 -0
  29. package/dist/notifications/helpers.d.ts +11 -1
  30. package/dist/notifications/helpers.js +26 -0
  31. package/dist/notifications/jobs.js +6 -0
  32. package/dist/notifications/mutations.js +9 -1
  33. package/dist/posts/activity.d.ts +1 -1
  34. package/dist/posts/activity.js +1 -1
  35. package/dist/posts/eventAgenda.js +4 -2
  36. package/dist/posts/finders.d.ts +6 -6
  37. package/dist/posts/helpers/index.d.ts +26 -26
  38. package/dist/posts/mapping.d.ts +98 -98
  39. package/dist/posts/mutations.d.ts +13 -13
  40. package/dist/posts/mutations.js +2 -4
  41. package/dist/profileSettings/mapping.d.ts +1 -0
  42. package/dist/profiles/mapping.d.ts +10 -10
  43. package/dist/reports/mapping.d.ts +1 -1
  44. package/dist/stats/mapping.d.ts +6 -6
  45. package/package.json +3 -3
  46. package/LICENSE +0 -674
@@ -95,7 +95,7 @@ export declare const buildAnalyticsBoardReport: (query?: AnalyticsDateQuery) =>
95
95
  resource: number;
96
96
  }[];
97
97
  postTypes: {
98
- type: "resource" | "poll" | "note" | "event" | "article" | "jam";
98
+ type: "resource" | "note" | "event" | "article" | "poll" | "jam";
99
99
  count: number;
100
100
  }[];
101
101
  activeUsersSeries: {
@@ -2,5 +2,9 @@ declare const _default: {
2
2
  local: {
3
3
  path: string;
4
4
  };
5
+ retention: {
6
+ zipAfterDays: number;
7
+ deleteAfterDays: number;
8
+ };
5
9
  };
6
10
  export default _default;
@@ -1,7 +1,12 @@
1
1
  import dotenv from 'dotenv';
2
+ import { readEnvInteger } from '../helpers.js';
2
3
  dotenv.config();
3
4
  export default {
4
5
  local: {
5
6
  path: process.env.LOGS_LOCAL_PATH || './.logs',
6
7
  },
8
+ retention: {
9
+ zipAfterDays: readEnvInteger('LOGS_RETENTION_ZIP_AFTER_DAYS', 7),
10
+ deleteAfterDays: readEnvInteger('LOGS_RETENTION_DELETE_AFTER_DAYS', 30),
11
+ },
7
12
  };
@@ -49,6 +49,10 @@ export declare const config: <T = {
49
49
  local: {
50
50
  path: string;
51
51
  };
52
+ retention: {
53
+ zipAfterDays: number;
54
+ deleteAfterDays: number;
55
+ };
52
56
  };
53
57
  media: {
54
58
  maxUploadMb: number;
@@ -291,6 +295,10 @@ export declare const sanitizedConfigWithDefaults: <T = {
291
295
  local: {
292
296
  path: string;
293
297
  };
298
+ retention: {
299
+ zipAfterDays: number;
300
+ deleteAfterDays: number;
301
+ };
294
302
  };
295
303
  media: {
296
304
  maxUploadMb: number;
@@ -55,7 +55,7 @@ export const postFilters = {
55
55
  : undefined,
56
56
  };
57
57
  export const eventTimeFilters = {
58
- upcoming: (now = new Date().toISOString()) => pgSql(or(sql `${eventStart} > ${now}`, and(sql `${posts.body}->'end' IS NOT NULL`, sql `${eventEnd} > ${now}`))),
58
+ upcoming: (now = new Date().toISOString()) => pgSql(sql `${eventEffectiveEnd} >= ${now}::timestamptz`),
59
59
  current: (now = new Date().toISOString()) => pgSql(and(sql `${eventStart}::timestamptz <= ${now}::timestamptz`, sql `${eventEffectiveEnd} >= ${now}::timestamptz`)),
60
60
  past: (now = new Date().toISOString()) => pgSql(sql `${eventEffectiveEnd} < ${now}::timestamptz`),
61
61
  };
@@ -74,7 +74,7 @@ export declare const listAdminGroups: () => Promise<{
74
74
  postsCount: number;
75
75
  owners: {
76
76
  handle: string;
77
- type: "guest" | "local" | "federated";
77
+ type: "local" | "guest" | "federated";
78
78
  id: string;
79
79
  createdAt: string;
80
80
  updatedAt: string;
@@ -107,7 +107,7 @@ export declare const listAdminGroups: () => Promise<{
107
107
  guestData?: {
108
108
  email?: string | undefined;
109
109
  resource?: {
110
- type: "profiles" | "groups" | "posts" | "notifications" | "reports" | "db" | "self" | "*" | "jams" | "webhooks" | "analytics" | "render";
110
+ type: "db" | "jams" | "profiles" | "self" | "*" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
111
111
  id?: string | undefined;
112
112
  } | undefined;
113
113
  } | undefined;
@@ -2,7 +2,7 @@ import type { GroupWithMeta, ProfileWithMeta } from '@openpeepshq/common/types';
2
2
  import type { PgFilter } from '../db/pg/map/queryTypes';
3
3
  export declare const addMember: (db: import("../db").PgDb, from: {
4
4
  id: string;
5
- type: "guest" | "local" | "federated";
5
+ type: "local" | "guest" | "federated";
6
6
  createdAt: string;
7
7
  updatedAt: string;
8
8
  handle: string;
@@ -77,18 +77,18 @@ export declare const addMember: (db: import("../db").PgDb, from: {
77
77
  lastPostAt?: string | null | undefined;
78
78
  deletedAt?: string | null | undefined;
79
79
  }, data?: {
80
- roles?: ("local" | "none" | "member" | "moderator" | "admin" | "owner" | "invited")[] | null | undefined;
80
+ roles?: ("local" | "member" | "none" | "owner" | "moderator" | "admin" | "invited")[] | null | undefined;
81
81
  } & {
82
82
  id?: string;
83
83
  }) => Promise<import("../db/pg/map").WithId<{
84
- roles?: ("local" | "none" | "member" | "moderator" | "admin" | "owner" | "invited")[] | null | undefined;
84
+ roles?: ("local" | "member" | "none" | "owner" | "moderator" | "admin" | "invited")[] | null | undefined;
85
85
  } & {
86
86
  _from: string;
87
87
  _to: string;
88
88
  }>>;
89
89
  export declare const removeMember: (db: import("../db").PgDb, from: {
90
90
  id: string;
91
- type: "guest" | "local" | "federated";
91
+ type: "local" | "guest" | "federated";
92
92
  createdAt: string;
93
93
  updatedAt: string;
94
94
  handle: string;
@@ -165,7 +165,7 @@ export declare const removeMember: (db: import("../db").PgDb, from: {
165
165
  }) => Promise<void>;
166
166
  export declare const updateMember: (db: import("../db").PgDb, from: {
167
167
  id: string;
168
- type: "guest" | "local" | "federated";
168
+ type: "local" | "guest" | "federated";
169
169
  createdAt: string;
170
170
  updatedAt: string;
171
171
  handle: string;
@@ -240,6 +240,6 @@ export declare const updateMember: (db: import("../db").PgDb, from: {
240
240
  lastPostAt?: string | null | undefined;
241
241
  deletedAt?: string | null | undefined;
242
242
  }, data?: {
243
- roles?: ("local" | "none" | "member" | "moderator" | "admin" | "owner" | "invited")[] | null | undefined;
243
+ roles?: ("local" | "member" | "none" | "owner" | "moderator" | "admin" | "invited")[] | null | undefined;
244
244
  } | undefined) => Promise<void>;
245
245
  export declare const canSeeGroupFilter: (profile?: ProfileWithMeta) => PgFilter<GroupWithMeta> | undefined;
@@ -76,7 +76,7 @@ export declare const adminGroupsMapping: import("../db/pg/map").Mapping<{
76
76
  postsCount: number;
77
77
  owners: {
78
78
  handle: string;
79
- type: "guest" | "local" | "federated";
79
+ type: "local" | "guest" | "federated";
80
80
  id: string;
81
81
  createdAt: string;
82
82
  updatedAt: string;
@@ -109,7 +109,7 @@ export declare const adminGroupsMapping: import("../db/pg/map").Mapping<{
109
109
  guestData?: {
110
110
  email?: string | undefined;
111
111
  resource?: {
112
- type: "profiles" | "groups" | "posts" | "notifications" | "reports" | "db" | "self" | "*" | "jams" | "webhooks" | "analytics" | "render";
112
+ type: "db" | "jams" | "profiles" | "self" | "*" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
113
113
  id?: string | undefined;
114
114
  } | undefined;
115
115
  } | undefined;
@@ -138,7 +138,7 @@ export declare const adminGroupsMapping: import("../db/pg/map").Mapping<{
138
138
  postsCount: number;
139
139
  owners: {
140
140
  handle: string;
141
- type: "guest" | "local" | "federated";
141
+ type: "local" | "guest" | "federated";
142
142
  id: string;
143
143
  createdAt: string;
144
144
  updatedAt: string;
@@ -171,7 +171,7 @@ export declare const adminGroupsMapping: import("../db/pg/map").Mapping<{
171
171
  guestData?: {
172
172
  email?: string | undefined;
173
173
  resource?: {
174
- type: "profiles" | "groups" | "posts" | "notifications" | "reports" | "db" | "self" | "*" | "jams" | "webhooks" | "analytics" | "render";
174
+ type: "db" | "jams" | "profiles" | "self" | "*" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
175
175
  id?: string | undefined;
176
176
  } | undefined;
177
177
  } | undefined;
@@ -24,7 +24,7 @@ export declare const connectRecording: (db: import("../db").PgDb, from: ProfileW
24
24
  updatedAt: string;
25
25
  description?: string | undefined;
26
26
  blurhash?: string | undefined;
27
- status?: "failed" | "processing" | "ready" | undefined;
27
+ status?: "failed" | "ready" | "processing" | undefined;
28
28
  error?: string | undefined;
29
29
  deletedAt?: string | null | undefined;
30
30
  } | undefined;
@@ -56,7 +56,7 @@ export declare const connectRecording: (db: import("../db").PgDb, from: ProfileW
56
56
  updatedAt: string;
57
57
  description?: string | undefined;
58
58
  blurhash?: string | undefined;
59
- status?: "failed" | "processing" | "ready" | undefined;
59
+ status?: "failed" | "ready" | "processing" | undefined;
60
60
  error?: string | undefined;
61
61
  deletedAt?: string | null | undefined;
62
62
  } | undefined;
@@ -51,7 +51,7 @@ export declare const stopRtmpStream: (jamPost: PostWithMeta) => Promise<{
51
51
  updatedAt: string;
52
52
  description?: string | undefined;
53
53
  blurhash?: string | undefined;
54
- status?: "failed" | "processing" | "ready" | undefined;
54
+ status?: "failed" | "ready" | "processing" | undefined;
55
55
  error?: string | undefined;
56
56
  deletedAt?: string | null | undefined;
57
57
  } | undefined;
@@ -88,7 +88,7 @@ export declare const stopRecording: (jamPost: PostWithMeta, recurrenceId?: strin
88
88
  updatedAt: string;
89
89
  description?: string | undefined;
90
90
  blurhash?: string | undefined;
91
- status?: "failed" | "processing" | "ready" | undefined;
91
+ status?: "failed" | "ready" | "processing" | undefined;
92
92
  error?: string | undefined;
93
93
  deletedAt?: string | null | undefined;
94
94
  } | undefined;
@@ -7,7 +7,7 @@ type EdgeMetadata = {
7
7
  export declare const jamEventsMapping: import("../db/pg/map").Mapping<{
8
8
  id: string;
9
9
  jamId: string;
10
- type: "close" | "join" | "message" | "start" | "reaction" | "leave" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
10
+ type: "message" | "join" | "close" | "reaction" | "start" | "leave" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
11
11
  profileId: string;
12
12
  content?: string | undefined;
13
13
  reaction?: "👍" | undefined;
@@ -16,7 +16,7 @@ export declare const jamEventsMapping: import("../db/pg/map").Mapping<{
16
16
  export declare const jamSessionStartsMapping: import("../db/pg/map").Mapping<{
17
17
  id: string;
18
18
  jamId: string;
19
- type: "close" | "join" | "message" | "start" | "reaction" | "leave" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
19
+ type: "message" | "join" | "close" | "reaction" | "start" | "leave" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
20
20
  profileId: string;
21
21
  content?: string | undefined;
22
22
  reaction?: "👍" | undefined;
@@ -25,7 +25,7 @@ export declare const jamSessionStartsMapping: import("../db/pg/map").Mapping<{
25
25
  export declare const jamSessionClosesMapping: import("../db/pg/map").Mapping<{
26
26
  id: string;
27
27
  jamId: string;
28
- type: "close" | "join" | "message" | "start" | "reaction" | "leave" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
28
+ type: "message" | "join" | "close" | "reaction" | "start" | "leave" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
29
29
  profileId: string;
30
30
  content?: string | undefined;
31
31
  reaction?: "👍" | undefined;
@@ -34,7 +34,7 @@ export declare const jamSessionClosesMapping: import("../db/pg/map").Mapping<{
34
34
  export declare const jamParticipantsMapping: import("../db/pg/map").Mapping<{
35
35
  id: string;
36
36
  jamId: string;
37
- type: "close" | "join" | "message" | "start" | "reaction" | "leave" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
37
+ type: "message" | "join" | "close" | "reaction" | "start" | "leave" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
38
38
  profileId: string;
39
39
  content?: string | undefined;
40
40
  reaction?: "👍" | undefined;
@@ -42,7 +42,7 @@ export declare const jamParticipantsMapping: import("../db/pg/map").Mapping<{
42
42
  }, JamEvent, JamEvent>;
43
43
  export declare const jamRecordingRelation: RelationWithMapping<PostWithMeta, JamRecording>;
44
44
  export declare const jamRecordingsMapping: import("../db/pg/map").Mapping<{
45
- status: "active" | "completed" | "failed" | "requested" | "finalizing";
45
+ status: "completed" | "failed" | "active" | "requested" | "finalizing";
46
46
  kind?: "file" | "rtmp" | undefined;
47
47
  destinationHost?: string | undefined;
48
48
  egressId?: string | undefined;
@@ -66,7 +66,7 @@ export declare const jamRecordingsMapping: import("../db/pg/map").Mapping<{
66
66
  updatedAt: string;
67
67
  description?: string | undefined;
68
68
  blurhash?: string | undefined;
69
- status?: "ready" | "failed" | "processing" | undefined;
69
+ status?: "failed" | "ready" | "processing" | undefined;
70
70
  error?: string | undefined;
71
71
  deletedAt?: string | null | undefined;
72
72
  } | undefined;
@@ -76,7 +76,7 @@ export declare const jamRecordingsMapping: import("../db/pg/map").Mapping<{
76
76
  updatedAt: string;
77
77
  deletedAt?: string | null | undefined;
78
78
  } & {
79
- status: "active" | "completed" | "failed" | "requested" | "finalizing";
79
+ status: "completed" | "failed" | "active" | "requested" | "finalizing";
80
80
  kind?: "file" | "rtmp" | undefined;
81
81
  destinationHost?: string | undefined;
82
82
  egressId?: string | undefined;
@@ -100,7 +100,7 @@ export declare const jamRecordingsMapping: import("../db/pg/map").Mapping<{
100
100
  updatedAt: string;
101
101
  description?: string | undefined;
102
102
  blurhash?: string | undefined;
103
- status?: "ready" | "failed" | "processing" | undefined;
103
+ status?: "failed" | "ready" | "processing" | undefined;
104
104
  error?: string | undefined;
105
105
  deletedAt?: string | null | undefined;
106
106
  } | undefined;
@@ -112,7 +112,7 @@ export declare const jamRecordingsMapping: import("../db/pg/map").Mapping<{
112
112
  updatedAt: string;
113
113
  deletedAt?: string | null | undefined;
114
114
  } & {
115
- status: "active" | "completed" | "failed" | "requested" | "finalizing";
115
+ status: "completed" | "failed" | "active" | "requested" | "finalizing";
116
116
  kind?: "file" | "rtmp" | undefined;
117
117
  destinationHost?: string | undefined;
118
118
  egressId?: string | undefined;
@@ -136,7 +136,7 @@ export declare const jamRecordingsMapping: import("../db/pg/map").Mapping<{
136
136
  updatedAt: string;
137
137
  description?: string | undefined;
138
138
  blurhash?: string | undefined;
139
- status?: "ready" | "failed" | "processing" | undefined;
139
+ status?: "failed" | "ready" | "processing" | undefined;
140
140
  error?: string | undefined;
141
141
  deletedAt?: string | null | undefined;
142
142
  } | undefined;
@@ -5,7 +5,7 @@ export declare const updateJamRecording: (recordingId: string, recording: Partia
5
5
  updatedAt: string;
6
6
  deletedAt?: string | null | undefined;
7
7
  } & {
8
- status: "active" | "completed" | "failed" | "requested" | "finalizing";
8
+ status: "completed" | "failed" | "active" | "requested" | "finalizing";
9
9
  kind?: "file" | "rtmp" | undefined;
10
10
  destinationHost?: string | undefined;
11
11
  egressId?: string | undefined;
@@ -29,7 +29,7 @@ export declare const updateJamRecording: (recordingId: string, recording: Partia
29
29
  updatedAt: string;
30
30
  description?: string | undefined;
31
31
  blurhash?: string | undefined;
32
- status?: "ready" | "failed" | "processing" | undefined;
32
+ status?: "failed" | "ready" | "processing" | undefined;
33
33
  error?: string | undefined;
34
34
  deletedAt?: string | null | undefined;
35
35
  } | undefined;
@@ -1,3 +1,4 @@
1
1
  import type { LoggerFactory } from '@openpeepshq/common/types';
2
+ export { logRetentionQueue, logRetentionWorker, ensureLogRetentionSchedule, LOG_RETENTION_CRON, type LogRetentionJobData, } from './retentionJobs';
2
3
  export declare const listLogs: (date?: Date) => Promise<any[]>;
3
4
  export declare const logger: LoggerFactory;
package/dist/log/index.js CHANGED
@@ -5,6 +5,7 @@ import * as readline from 'node:readline';
5
5
  import { formatDate } from 'date-fns/format';
6
6
  import safeJsonStringify from 'safe-json-stringify';
7
7
  import { default as logsConfig } from '../config/defaults/logs.js';
8
+ export { logRetentionQueue, logRetentionWorker, ensureLogRetentionSchedule, LOG_RETENTION_CRON, } from './retentionJobs.js';
8
9
  const createLogDirectory = () => mkdirSync(logsConfig.local.path, { recursive: true });
9
10
  const currentFile = (date) => join(logsConfig.local.path, formatDate(date, 'yyyyMMdd') + '.log');
10
11
  export const listLogs = async (date = new Date()) => {
@@ -0,0 +1,9 @@
1
+ export interface LogRetentionResult {
2
+ /** Log files archived to a .zip during this run. */
3
+ zipped: string[];
4
+ /** Files (log and .zip) removed during this run. */
5
+ deleted: string[];
6
+ /** Log files under the zip threshold, or already zipped. */
7
+ untouched: number;
8
+ }
9
+ export declare const cleanOldLogs: (dir: string, zipAfterDays: number, deleteAfterDays: number) => Promise<LogRetentionResult>;
@@ -0,0 +1,83 @@
1
+ import { createReadStream, createWriteStream } from 'node:fs';
2
+ import { readdir, rm, stat } from 'node:fs/promises';
3
+ import { basename, join } from 'node:path';
4
+ import archiver from 'archiver';
5
+ const DAY_MS = 24 * 60 * 60 * 1000;
6
+ /** Daily log file as written by the logger, e.g. `20261001.log`. */
7
+ const RAW_LOG_FILE = /^\d{8}\.log$/;
8
+ /** Archive produced by `cleanOldLogs`, e.g. `20261001.log.zip`. */
9
+ const LOG_ZIP_FILE = /^\d{8}\.log\.zip$/;
10
+ const fileExists = async (path) => {
11
+ try {
12
+ await stat(path);
13
+ return true;
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ };
19
+ const zipLogFile = (file, zipPath) => new Promise((resolve, reject) => {
20
+ const output = createWriteStream(zipPath);
21
+ const archive = archiver('zip', { zlib: { level: 9 } });
22
+ output.on('close', () => resolve());
23
+ output.on('error', reject);
24
+ archive.on('error', reject);
25
+ archive.on('warning', (err) => {
26
+ if (err.code === 'ENOENT')
27
+ return;
28
+ reject(err);
29
+ });
30
+ archive.pipe(output);
31
+ archive.append(createReadStream(file), { name: basename(file) });
32
+ void archive.finalize();
33
+ });
34
+ export const cleanOldLogs = async (dir, zipAfterDays, deleteAfterDays) => {
35
+ const result = { zipped: [], deleted: [], untouched: 0 };
36
+ const now = Date.now();
37
+ let entries;
38
+ try {
39
+ entries = await readdir(dir);
40
+ }
41
+ catch (err) {
42
+ // The log directory is created lazily by the logger; nothing to clean.
43
+ if (err.code === 'ENOENT')
44
+ return result;
45
+ throw err;
46
+ }
47
+ for (const entry of entries) {
48
+ const isRawLog = RAW_LOG_FILE.test(entry);
49
+ if (!isRawLog && !LOG_ZIP_FILE.test(entry))
50
+ continue;
51
+ const filePath = join(dir, entry);
52
+ // May already be gone: deleting a raw log also removes its zip.
53
+ if (!(await fileExists(filePath)))
54
+ continue;
55
+ const st = await stat(filePath);
56
+ if (!st.isFile())
57
+ continue;
58
+ if (now - st.mtimeMs > deleteAfterDays * DAY_MS) {
59
+ // Zips share the raw log's lifetime so disk usage actually shrinks.
60
+ await rm(filePath, { force: true });
61
+ result.deleted.push(entry);
62
+ if (isRawLog) {
63
+ const zipPath = `${filePath}.zip`;
64
+ if (await fileExists(zipPath)) {
65
+ await rm(zipPath, { force: true });
66
+ result.deleted.push(`${entry}.zip`);
67
+ }
68
+ }
69
+ continue;
70
+ }
71
+ if (!isRawLog)
72
+ continue;
73
+ if (now - st.mtimeMs > zipAfterDays * DAY_MS &&
74
+ !(await fileExists(`${filePath}.zip`))) {
75
+ await zipLogFile(filePath, `${filePath}.zip`);
76
+ result.zipped.push(entry);
77
+ }
78
+ else {
79
+ result.untouched += 1;
80
+ }
81
+ }
82
+ return result;
83
+ };
@@ -0,0 +1,17 @@
1
+ export declare const LOG_RETENTION_CRON = "0 2 * * *";
2
+ export interface LogRetentionJobData {
3
+ /** Override the zip threshold; mostly for testing. */
4
+ zipAfterDays?: number;
5
+ /** Override the delete threshold; mostly for testing. */
6
+ deleteAfterDays?: number;
7
+ /** Override the log directory; mostly for testing. */
8
+ dir?: string;
9
+ }
10
+ declare const logRetentionQueue: () => import("bullmq").Queue, logRetentionWorker: () => import("bullmq").Worker;
11
+ /**
12
+ * Registers (or refreshes) the daily schedule with BullMQ. Safe to call
13
+ * repeatedly — `upsertJobScheduler` is idempotent and overwrites the existing
14
+ * schedule entry under the same id.
15
+ */
16
+ export declare const ensureLogRetentionSchedule: () => Promise<void>;
17
+ export { logRetentionQueue, logRetentionWorker };
@@ -0,0 +1,50 @@
1
+ import { queueAndWorker } from '../jobs/index.js';
2
+ import { cleanOldLogs } from './retention.js';
3
+ // Cron pattern (UTC): every day at 02:00. Off-peak for most regions and
4
+ // staggered away from the other daily housekeeping (streaming cleanup 03:00,
5
+ // analytics retention 03:30, event occurrences 04:00).
6
+ export const LOG_RETENTION_CRON = '0 2 * * *';
7
+ const SCHEDULER_ID = 'log-retention-daily';
8
+ const JOB_NAME = 'clean';
9
+ const [logRetentionQueue, logRetentionWorker] = queueAndWorker('log-retention', async (job) => {
10
+ // Dynamic imports: the log barrel is among the first modules loaded,
11
+ // and ../config -> ../events -> this barrel, so a static edge would
12
+ // create a load-time import cycle.
13
+ const { logger } = await import('./index.js');
14
+ const { config } = await import('../config/index.js');
15
+ const log = logger('app:log:retention');
16
+ const coreConfig = await config();
17
+ const zipAfterDays = job.data.zipAfterDays ?? coreConfig.logs.retention.zipAfterDays;
18
+ const deleteAfterDays = job.data.deleteAfterDays ?? coreConfig.logs.retention.deleteAfterDays;
19
+ const dir = job.data.dir ?? coreConfig.logs.local.path;
20
+ log.info(`Running log retention (zipAfterDays=${zipAfterDays}, ` +
21
+ `deleteAfterDays=${deleteAfterDays})`);
22
+ const result = await cleanOldLogs(dir, zipAfterDays, deleteAfterDays);
23
+ log.info(`Log retention done: zipped=${result.zipped.length}, ` +
24
+ `deleted=${result.deleted.length}, untouched=${result.untouched}`);
25
+ if (result.zipped.length > 0) {
26
+ log.info(`Zipped logs: ${result.zipped.join(', ')}`);
27
+ }
28
+ if (result.deleted.length > 0) {
29
+ log.info(`Deleted logs: ${result.deleted.join(', ')}`);
30
+ }
31
+ }, {
32
+ defaultJobOptions: {
33
+ // We never need more than the most recent runs; keep a small history
34
+ // for debugging and let BullMQ trim the rest.
35
+ removeOnComplete: { count: 10 },
36
+ removeOnFail: { age: 86400 * 14, count: 50 },
37
+ },
38
+ });
39
+ /**
40
+ * Registers (or refreshes) the daily schedule with BullMQ. Safe to call
41
+ * repeatedly — `upsertJobScheduler` is idempotent and overwrites the existing
42
+ * schedule entry under the same id.
43
+ */
44
+ export const ensureLogRetentionSchedule = async () => {
45
+ const queue = logRetentionQueue();
46
+ await queue.upsertJobScheduler(SCHEDULER_ID, { pattern: LOG_RETENTION_CRON }, { name: JOB_NAME });
47
+ const { logger } = await import('./index.js');
48
+ logger('app:log:retention').info(`Log retention schedule registered: cron="${LOG_RETENTION_CRON}"`);
49
+ };
50
+ export { logRetentionQueue, logRetentionWorker };
@@ -8,6 +8,7 @@ import fs from 'node:fs/promises';
8
8
  import { createReadStream, createWriteStream } from 'node:fs';
9
9
  import { Readable } from 'node:stream';
10
10
  import { pipeline } from 'node:stream/promises';
11
+ import { spawn } from 'node:child_process';
11
12
  import { getTheme, randomString } from '@openpeepshq/common/lib';
12
13
  import { logger } from '../log/index.js';
13
14
  import { hub } from '../events/index.js';
@@ -130,17 +131,75 @@ const escapeXml = (value) => value
130
131
  .replace(/</g, '&lt;')
131
132
  .replace(/>/g, '&gt;')
132
133
  .replace(/"/g, '&quot;');
133
- const createPdfPreview = (inputPath) => {
134
+ /**
135
+ * Render the first page of a PDF to a WebP thumbnail via sharp. The prebuilt
136
+ * sharp binary bundles poppler, so PDF decoding is available without any extra
137
+ * system packages on Linux/musl (Alpine) and glibc.
138
+ */
139
+ const createPdfPreview = async (inputPath) => {
134
140
  const outputPath = join(tmpdir(), `preview-${randomString(16)}.webp`);
135
- return new Promise((resolve, reject) => {
136
- ffmpeg(inputPath)
137
- .frames(1)
138
- .outputOptions(['-c:v libwebp', '-lossless 0', '-q:v 80'])
139
- .output(outputPath)
140
- .on('end', () => resolve({ path: outputPath, mimetype: 'image/webp' }))
141
- .on('error', reject)
142
- .run();
141
+ await sharp(inputPath, { density: 150, pages: 1 })
142
+ .resize(previewMaxWidth)
143
+ .webp({ quality: 80 })
144
+ .toFile(outputPath);
145
+ return { path: outputPath, mimetype: 'image/webp' };
146
+ };
147
+ const OFFICE_DOC_EXTENSIONS = new Set([
148
+ '.docx',
149
+ '.doc',
150
+ '.xlsx',
151
+ '.xls',
152
+ '.pptx',
153
+ '.ppt',
154
+ '.odt',
155
+ '.ods',
156
+ '.odp',
157
+ ]);
158
+ const isOfficeDocument = (originalName) => OFFICE_DOC_EXTENSIONS.has(path.extname(originalName).toLowerCase());
159
+ /**
160
+ * Convert an office document (docx/xlsx/pptx/etc.) to PDF using LibreOffice in
161
+ * headless mode. Returns the path to the generated PDF inside a temp directory
162
+ * the caller is responsible for cleaning up.
163
+ */
164
+ const convertOfficeToPdf = async (inputPath, originalName) => {
165
+ const outputDir = join(tmpdir(), `office-${randomString(16)}`);
166
+ await fs.mkdir(outputDir, { recursive: true });
167
+ await new Promise((resolve, reject) => {
168
+ const proc = spawn('libreoffice', [
169
+ '--headless',
170
+ '--no-first-run',
171
+ '--nofirstwizard',
172
+ '--norestore',
173
+ '--nologging',
174
+ '--convert-to',
175
+ 'pdf',
176
+ '--outdir',
177
+ outputDir,
178
+ inputPath,
179
+ ], { stdio: ['ignore', 'ignore', 'pipe'] });
180
+ let stderr = '';
181
+ proc.stderr?.setEncoding('utf8');
182
+ proc.stderr?.on('data', (chunk) => {
183
+ stderr += chunk;
184
+ });
185
+ proc.on('error', (err) => {
186
+ reject(err.code === 'ENOENT' ? new Error('libreoffice binary not found') : err);
187
+ });
188
+ proc.on('close', (code) => {
189
+ if (code === 0) {
190
+ resolve();
191
+ }
192
+ else {
193
+ reject(new Error(`libreoffice conversion failed (exit ${code}): ${stderr}`));
194
+ }
195
+ });
143
196
  });
197
+ const files = await fs.readdir(outputDir);
198
+ const pdfFile = files.find((f) => f.endsWith('.pdf'));
199
+ if (!pdfFile) {
200
+ throw new Error(`libreoffice did not produce a PDF for ${originalName}`);
201
+ }
202
+ return join(outputDir, pdfFile);
144
203
  };
145
204
  const createDocumentCardPreview = async (originalName) => {
146
205
  const ext = (path.extname(originalName).replace('.', '') || 'FILE')
@@ -166,7 +225,25 @@ const createFilePreview = async (inputPath, mimetype, originalName) => {
166
225
  return await createPdfPreview(inputPath);
167
226
  }
168
227
  catch {
169
- // Some ffmpeg builds cannot rasterize PDFs.
228
+ // sharp PDF support may be missing; fall back to card preview below.
229
+ }
230
+ }
231
+ if (isOfficeDocument(originalName)) {
232
+ let pdfPath;
233
+ try {
234
+ pdfPath = await convertOfficeToPdf(inputPath, originalName);
235
+ return await createPdfPreview(pdfPath);
236
+ }
237
+ catch (error) {
238
+ const message = error instanceof Error ? error.message : String(error);
239
+ log.warn(`Office document preview failed for ${originalName}: ${message}`);
240
+ }
241
+ finally {
242
+ if (pdfPath) {
243
+ await fs
244
+ .rm(path.dirname(pdfPath), { recursive: true, force: true })
245
+ .catch(() => undefined);
246
+ }
170
247
  }
171
248
  }
172
249
  return createDocumentCardPreview(originalName);
@@ -16,6 +16,6 @@ export declare const mediaAttachmentsMapping: import("../db/pg/map").Mapping<{
16
16
  };
17
17
  description?: string | undefined;
18
18
  blurhash?: string | undefined;
19
- status?: "ready" | "failed" | "processing" | undefined;
19
+ status?: "failed" | "ready" | "processing" | undefined;
20
20
  error?: string | undefined;
21
21
  }, MediaAttachment, MediaAttachment>;