aio-capacitor 2.1.0 → 2.2.2

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 (3) hide show
  1. package/index.d.ts +123 -58
  2. package/index.js +360 -362
  3. package/package.json +15 -13
package/index.d.ts CHANGED
@@ -1,20 +1,3 @@
1
- import { Directory } from '@capacitor/filesystem';
2
-
3
- type I_logItem = {
4
- tags?: string[];
5
- id?: string;
6
- message: string;
7
- status?: 'error' | 'success' | 'warning' | 'info';
8
- data?: any;
9
- date?: number;
10
- };
11
- export type NotificationItem = {
12
- id: number;
13
- title: string;
14
- body: string;
15
- fireAt: number;
16
- status: 'pending' | 'scheduled' | 'done';
17
- };
18
1
  export type I_speak = {
19
2
  text: string;
20
3
  lang?: 'fa-IR' | 'en-US';
@@ -23,17 +6,35 @@ export type I_speak = {
23
6
  };
24
7
  type PermissionName = "CAMERA" | "ACCESS_FINE_LOCATION" | "ACCESS_COARSE_LOCATION" | "POST_NOTIFICATIONS";
25
8
  export declare class AIOCapacitor {
26
- onLog: ((log: I_logItem) => void) | undefined;
9
+ logs: Logs;
10
+ notif: NotificationService;
27
11
  constructor(p?: {
28
- onLog?: (log: I_logItem) => void;
12
+ notificationActionCallBack?: (actionId: string) => void;
29
13
  });
30
14
  getPlatform: () => 'web' | 'android' | 'ios';
31
15
  isNative: () => boolean;
32
- addLog: (log: I_logItem) => void;
16
+ addNotif: (_item: I_notifItem) => Promise<number>;
17
+ cancelNotif: (p: {
18
+ tags?: string[];
19
+ ids?: number[];
20
+ }) => Promise<void>;
21
+ getNotifs: (filter?: {
22
+ fired?: boolean;
23
+ tags?: string[];
24
+ }) => Promise<I_notifItem[]>;
33
25
  vibrate: (p: {
34
26
  pattern?: number[];
35
27
  density?: 'light' | 'medium' | 'heavy';
36
28
  }) => Promise<void>;
29
+ addLog: (log: Omit<I_logItem, "date">) => I_logItem[];
30
+ removeLog: (p: {
31
+ id?: number;
32
+ tags?: string[];
33
+ }) => I_logItem[];
34
+ getLogs: (filter?: {
35
+ tags?: string[];
36
+ status?: "error" | "success" | "warning" | "info";
37
+ }) => I_logItem[];
37
38
  vibratePattern: (pattern: number[]) => Promise<void>;
38
39
  vibrateImpact: (style?: 'light' | 'medium' | 'heavy') => Promise<void>;
39
40
  getPermissions: (permissionNames: PermissionName[]) => Promise<void>;
@@ -48,12 +49,34 @@ export declare class AIOCapacitor {
48
49
  storageLoad: (name: string, def: any) => Promise<any>;
49
50
  copy: (text: string) => Promise<void>;
50
51
  paste: () => Promise<string>;
51
- readFile: (path: string, directory: Directory) => Promise<any>;
52
+ getDirectory: (location?: 'Data' | 'Documents' | 'Cache') => any;
52
53
  uriToSrc: (uri: string) => Promise<any>;
53
54
  pathToUri: (path: string, directory: Directory) => Promise<any>;
54
55
  pathToSrc: (path: string, directory: Directory) => Promise<any>;
55
- writeFile: (data: string, path: string, encoding?: boolean) => Promise<any>;
56
- save: (data: string | File | Blob, path: string) => Promise<{
56
+ pickFolder: (extensions?: string[]) => Promise<{
57
+ files: {
58
+ filePath: string;
59
+ fileName: string;
60
+ }[];
61
+ folderPath: string;
62
+ }>;
63
+ getFolderFiles: (folderPath: string, extensions: string[]) => Promise<false | ({
64
+ filePath: string;
65
+ fileName: string;
66
+ }[])>;
67
+ openFile: (filePath: string) => Promise<void>;
68
+ readFile: (path: string, options?: {
69
+ location?: 'Data' | 'Documents' | 'Cache';
70
+ utf8?: boolean;
71
+ }) => Promise<any>;
72
+ writeFile: (data: string, path: string, options?: {
73
+ location?: 'Data' | 'Documents' | 'Cache';
74
+ utf8?: boolean;
75
+ }) => Promise<any>;
76
+ save: (data: string | File | Blob, path: string, options?: {
77
+ location?: 'Data' | 'Documents' | 'Cache';
78
+ utf8?: boolean;
79
+ }) => Promise<{
57
80
  success: boolean;
58
81
  message: any;
59
82
  }>;
@@ -64,13 +87,8 @@ export declare class AIOCapacitor {
64
87
  success: boolean;
65
88
  error: any;
66
89
  }>;
67
- shareFile: (file: Blob | File, fileName?: string) => Promise<FileResult<string> | {
68
- success: boolean;
69
- error?: undefined;
70
- } | {
71
- success: boolean;
72
- error: any;
73
- }>;
90
+ getExtensions: (type: 'image' | 'audio' | 'video') => string[];
91
+ shareFile: (file: Blob | File, fileName?: string) => Promise<any>;
74
92
  getLocation: () => Promise<{
75
93
  success: boolean;
76
94
  latitude?: number;
@@ -80,23 +98,38 @@ export declare class AIOCapacitor {
80
98
  error?: string;
81
99
  }>;
82
100
  awake: (state?: boolean) => Promise<any>;
83
- isAwake: () => Promise<any>;
101
+ isAwake: () => Promise<boolean>;
84
102
  }
85
- type DB = {
86
- save: (item: NotificationItem) => Promise<void>;
87
- getAll: () => Promise<NotificationItem[]>;
88
- update: (id: number, patch: Partial<NotificationItem>) => Promise<void>;
103
+ type I_logItem = {
104
+ tags: string[];
105
+ id?: number;
106
+ repeat?: number;
107
+ message: string;
108
+ status: 'error' | 'success' | 'warning' | 'info';
109
+ data?: any;
110
+ expiredByHours?: number;
111
+ date: number;
89
112
  };
90
- export declare class NotificationService {
91
- private db;
92
- constructor(db: DB);
93
- init(): Promise<void>;
94
- notifyAt(date: number, title: string, body: string): Promise<number>;
95
- private schedule;
96
- private fireNow;
97
- resync(): Promise<void>;
98
- cancel(id: number): Promise<void>;
99
- list(): Promise<any>;
113
+ declare class Logs {
114
+ logs: I_logItem[];
115
+ load: () => Promise<I_logItem[]>;
116
+ save: (logs: I_logItem[]) => Promise<void>;
117
+ constructor(p: {
118
+ load: () => Promise<I_logItem[]>;
119
+ save: (logs: I_logItem[]) => Promise<void>;
120
+ });
121
+ private removeExpiredLogs;
122
+ addLog: (log: Omit<I_logItem, 'date'>) => I_logItem[];
123
+ remove: (p: {
124
+ id?: number;
125
+ tags?: string[];
126
+ }) => I_logItem[];
127
+ private getTagsDic;
128
+ private isTagsMatch;
129
+ getLogs: (filter?: {
130
+ tags?: string[];
131
+ status?: 'error' | 'success' | 'warning' | 'info';
132
+ }) => I_logItem[];
100
133
  }
101
134
  export declare class Tracker {
102
135
  private watchId;
@@ -118,18 +151,50 @@ export declare class Tracker {
118
151
  stop(): Promise<void>;
119
152
  isTracking(): boolean;
120
153
  }
121
- export type I_FileRecordType = 'image' | 'file' | 'json' | 'text';
122
- export type I_FileRecord = {
123
- id: string;
124
- name: string;
125
- path: string;
126
- type: I_FileRecordType;
127
- createdAt: number;
128
- meta?: any;
129
- };
130
- type FileResult<T> = {
131
- success: boolean;
132
- result: T;
133
- message?: string;
154
+ export type I_notifItem = {
155
+ id: number;
156
+ title: string;
157
+ body: string;
158
+ fireAt: number;
159
+ showInExpired?: boolean;
160
+ keepUntil?: number;
161
+ actions?: string[];
162
+ tags?: string[];
163
+ importance?: 'low' | 'default' | 'high';
164
+ sound?: string;
165
+ vibration?: boolean;
134
166
  };
167
+ export declare class NotificationService {
168
+ private notificationFile;
169
+ constructor(actionCallBack?: (actionId: string) => void);
170
+ init: (actionCallBack?: (actionId: string) => void) => Promise<void>;
171
+ private handleReceived;
172
+ private getChannelId;
173
+ private registerChannel;
174
+ register: (_item: I_notifItem) => Promise<number>;
175
+ cancel: (p: {
176
+ tags?: string[];
177
+ ids?: number[];
178
+ }) => Promise<void>;
179
+ private cancelByIds;
180
+ private cancelById;
181
+ private cancelByTag;
182
+ private cancelByTags;
183
+ private resync;
184
+ private schedule;
185
+ private registerActionType;
186
+ private getActionTypeId;
187
+ private getImportance;
188
+ tagsMatch: (tagsDic: {
189
+ [tag: string]: boolean;
190
+ }, itemTags?: string[]) => boolean | string[];
191
+ getTagsDic: (tags?: string[]) => {
192
+ [tag: string]: boolean;
193
+ };
194
+ getList: (filter?: {
195
+ fired?: boolean;
196
+ tags?: string[];
197
+ }) => Promise<I_notifItem[]>;
198
+ private save;
199
+ }
135
200
  export {};
package/index.js CHANGED
@@ -19,16 +19,36 @@ import { Haptics, ImpactStyle } from '@capacitor/haptics';
19
19
  import { Share } from '@capacitor/share';
20
20
  import { LocalNotifications } from '@capacitor/local-notifications';
21
21
  import { KeepAwake } from '@capacitor-community/keep-awake';
22
+ import { FolderPicker } from 'aio-capacitor-folder-picker';
23
+ import { FileClass, GenerateId } from 'aio-class';
22
24
  export class AIOCapacitor {
23
25
  constructor(p) {
26
+ this.logs = new Logs({
27
+ load: () => __awaiter(this, void 0, void 0, function* () {
28
+ try {
29
+ const storageRes = yield this.readFile('logs.json', { location: "Data", utf8: true });
30
+ const res = JSON.parse(storageRes);
31
+ return res;
32
+ }
33
+ catch (err) {
34
+ return [];
35
+ }
36
+ }),
37
+ save: (logs) => __awaiter(this, void 0, void 0, function* () {
38
+ try {
39
+ yield this.writeFile(JSON.stringify(logs), 'logs.json', { location: "Data", utf8: true });
40
+ }
41
+ catch (err) {
42
+ alert(err.message);
43
+ }
44
+ })
45
+ });
46
+ this.notif = new NotificationService();
24
47
  this.getPlatform = () => Capacitor.getPlatform();
25
48
  this.isNative = () => ['android', 'ios'].indexOf(Capacitor.getPlatform()) !== -1;
26
- this.addLog = (log) => {
27
- if (!this.onLog) {
28
- return;
29
- }
30
- this.onLog(log);
31
- };
49
+ this.addNotif = this.notif.register;
50
+ this.cancelNotif = this.notif.cancel;
51
+ this.getNotifs = this.notif.getList;
32
52
  this.vibrate = (p) => __awaiter(this, void 0, void 0, function* () {
33
53
  if (p.pattern) {
34
54
  yield this.vibratePattern(p.pattern);
@@ -37,6 +57,9 @@ export class AIOCapacitor {
37
57
  this.vibrateImpact(p.density);
38
58
  }
39
59
  });
60
+ this.addLog = this.logs.addLog;
61
+ this.removeLog = this.logs.remove;
62
+ this.getLogs = this.logs.getLogs;
40
63
  this.vibratePattern = (pattern) => __awaiter(this, void 0, void 0, function* () {
41
64
  try {
42
65
  for (const duration of pattern) {
@@ -48,7 +71,7 @@ export class AIOCapacitor {
48
71
  console.error('Haptics pattern error:', err);
49
72
  }
50
73
  });
51
- this.vibrateImpact = (style = 'medium') => __awaiter(this, void 0, void 0, function* () {
74
+ this.vibrateImpact = (...args_1) => __awaiter(this, [...args_1], void 0, function* (style = 'medium') {
52
75
  try {
53
76
  const map = {
54
77
  light: ImpactStyle.Light,
@@ -62,34 +85,34 @@ export class AIOCapacitor {
62
85
  }
63
86
  });
64
87
  this.getPermissions = (permissionNames) => __awaiter(this, void 0, void 0, function* () {
65
- var _a, _b, _c, _d, _e;
66
88
  for (const permission of permissionNames) {
67
89
  try {
68
90
  switch (permission) {
69
91
  case "CAMERA": {
70
92
  yield Camera.requestPermissions();
71
- (_a = this.addLog) === null || _a === void 0 ? void 0 : _a.call(this, { message: "CAMERA permission requested", status: "success" });
93
+ this.addLog({ message: "CAMERA permission requested", status: "success", tags: ['permission'] });
72
94
  break;
73
95
  }
74
96
  case "ACCESS_FINE_LOCATION":
75
97
  case "ACCESS_COARSE_LOCATION": {
76
98
  yield Geolocation.requestPermissions();
77
- (_b = this.addLog) === null || _b === void 0 ? void 0 : _b.call(this, { message: "LOCATION permission requested", status: "success" });
99
+ this.addLog({ message: "LOCATION permission requested", status: "success", tags: ['permission'] });
78
100
  break;
79
101
  }
80
102
  case "POST_NOTIFICATIONS": {
81
103
  yield PushNotifications.requestPermissions();
82
- (_c = this.addLog) === null || _c === void 0 ? void 0 : _c.call(this, { message: "NOTIFICATION permission requested", status: "success" });
104
+ this.addLog({ message: "NOTIFICATION permission requested", status: "success", tags: ['permission'] });
83
105
  break;
84
106
  }
85
107
  default:
86
- (_d = this.addLog) === null || _d === void 0 ? void 0 : _d.call(this, { message: `Permission not supported: ${permission}`, status: "error" });
108
+ this.addLog({ message: `Permission not supported: ${permission}`, status: "error", tags: ['permission'] });
87
109
  }
88
110
  }
89
111
  catch (err) {
90
- (_e = this.addLog) === null || _e === void 0 ? void 0 : _e.call(this, {
112
+ this.addLog({
91
113
  message: `Permission error for ${permission}: ${err === null || err === void 0 ? void 0 : err.message}`,
92
- status: "error"
114
+ status: "error",
115
+ tags: ['permission']
93
116
  });
94
117
  }
95
118
  }
@@ -147,17 +170,47 @@ export class AIOCapacitor {
147
170
  return '';
148
171
  }
149
172
  });
150
- this.readFile = (path, directory) => __awaiter(this, void 0, void 0, function* () { return yield Filesystem.readFile({ path, directory }); });
173
+ this.getDirectory = (location) => {
174
+ return { Data: Directory.Data, Documents: Directory.Documents, Cache: Directory.Cache }[location || 'Data'];
175
+ };
151
176
  this.uriToSrc = (uri) => __awaiter(this, void 0, void 0, function* () { return Capacitor.convertFileSrc(uri); });
152
177
  this.pathToUri = (path, directory) => __awaiter(this, void 0, void 0, function* () { return (yield Filesystem.getUri({ path, directory })).uri; });
153
178
  this.pathToSrc = (path, directory) => __awaiter(this, void 0, void 0, function* () { return yield this.uriToSrc(yield this.pathToUri(path, directory)); });
154
- this.writeFile = (data, path, encoding) => __awaiter(this, void 0, void 0, function* () { return yield Filesystem.writeFile({ path, data, directory: Directory.Documents, encoding: encoding ? Encoding.UTF8 : undefined }); });
155
- this.save = (data, path) => __awaiter(this, void 0, void 0, function* () {
179
+ this.pickFolder = (extensions) => __awaiter(this, void 0, void 0, function* () {
180
+ const { folderPath, files } = yield FolderPicker.pickFolder(extensions ? { extensions } : undefined);
181
+ return { folderPath, files };
182
+ });
183
+ this.getFolderFiles = (folderPath, extensions) => __awaiter(this, void 0, void 0, function* () {
184
+ try {
185
+ const res = yield FolderPicker.getFolderFiles({ folderPath, extensions });
186
+ return res.files;
187
+ }
188
+ catch (error) {
189
+ alert("updateFolder error:" + String(error));
190
+ return false;
191
+ }
192
+ });
193
+ this.openFile = (filePath) => __awaiter(this, void 0, void 0, function* () {
194
+ try {
195
+ yield FolderPicker.openFile({ filePath });
196
+ }
197
+ catch (error) {
198
+ alert(`Open file error:\n${String(error)}`);
199
+ }
200
+ });
201
+ this.readFile = (path, options) => __awaiter(this, void 0, void 0, function* () {
202
+ const res = yield Filesystem.readFile({ path, directory: this.getDirectory(options === null || options === void 0 ? void 0 : options.location), encoding: (options === null || options === void 0 ? void 0 : options.utf8) ? Encoding.UTF8 : undefined });
203
+ return res.data;
204
+ });
205
+ this.writeFile = (data, path, options) => __awaiter(this, void 0, void 0, function* () {
206
+ return Filesystem.writeFile({ path, data, directory: this.getDirectory(options === null || options === void 0 ? void 0 : options.location), encoding: (options === null || options === void 0 ? void 0 : options.utf8) ? Encoding.UTF8 : undefined });
207
+ });
208
+ this.save = (data, path, options) => __awaiter(this, void 0, void 0, function* () {
156
209
  try {
157
210
  const fs = new FileClass();
158
211
  if (typeof data === 'string' && !fs.isUrl(data)) {
159
212
  try {
160
- yield this.writeFile(data, path, true);
213
+ yield this.writeFile(data, path, options);
161
214
  return { success: true, message: '' };
162
215
  }
163
216
  catch (err) {
@@ -173,7 +226,8 @@ export class AIOCapacitor {
173
226
  if (!res2.success) {
174
227
  return { success: false, message: res2.message };
175
228
  }
176
- yield this.writeFile(res2.result, path);
229
+ alert(res2.result.slice(0, 50));
230
+ yield this.writeFile(res2.result, path, options);
177
231
  return { success: true, message: '' };
178
232
  }
179
233
  }
@@ -190,7 +244,27 @@ export class AIOCapacitor {
190
244
  return { success: false, error: (err === null || err === void 0 ? void 0 : err.message) || err };
191
245
  }
192
246
  });
193
- this.shareFile = (file, fileName = `file_${Date.now()}`) => __awaiter(this, void 0, void 0, function* () {
247
+ this.getExtensions = (type) => {
248
+ const extensions = {
249
+ image: [
250
+ 'jpg', 'jpeg', 'png', 'gif', 'webp',
251
+ 'bmp', 'svg', 'ico', 'tiff', 'tif', 'avif'
252
+ ],
253
+ audio: [
254
+ 'mp3', 'wav', 'flac', 'aac', 'm4a',
255
+ 'ogg', 'oga', 'opus', 'wma', 'aiff', 'aif',
256
+ 'alac', 'amr', 'mid', 'midi'
257
+ ],
258
+ video: [
259
+ 'mp4', 'webm', 'mkv', 'avi', 'mov',
260
+ 'wmv', 'flv', 'm4v', '3gp', '3g2',
261
+ 'mpeg', 'mpg', 'mts', 'm2ts', 'ts',
262
+ 'ogv', 'vob'
263
+ ]
264
+ };
265
+ return extensions[type];
266
+ };
267
+ this.shareFile = (file_1, ...args_2) => __awaiter(this, [file_1, ...args_2], void 0, function* (file, fileName = `file_${Date.now()}`) {
194
268
  try {
195
269
  const res = yield new FileClass().toDataUrl(file);
196
270
  if (!res.success) {
@@ -259,7 +333,7 @@ export class AIOCapacitor {
259
333
  const _isAwake = yield this.isAwake();
260
334
  _awake = !_isAwake;
261
335
  }
262
- if (_awake) {
336
+ if (!_awake) {
263
337
  yield KeepAwake.allowSleep();
264
338
  }
265
339
  else {
@@ -267,126 +341,98 @@ export class AIOCapacitor {
267
341
  }
268
342
  return _awake;
269
343
  });
270
- this.isAwake = () => __awaiter(this, void 0, void 0, function* () { return yield KeepAwake.isKeptAwake(); });
271
- this.onLog = p === null || p === void 0 ? void 0 : p.onLog;
272
- }
273
- }
274
- export class NotificationService {
275
- constructor(db) { this.db = db; }
276
- // -------------------------
277
- // INIT (CRITICAL)
278
- // -------------------------
279
- init() {
280
- return __awaiter(this, void 0, void 0, function* () {
281
- yield LocalNotifications.requestPermissions();
282
- yield this.resync();
283
- });
284
- }
285
- // -------------------------
286
- // CREATE NOTIFICATION
287
- // -------------------------
288
- notifyAt(date, title, body) {
289
- return __awaiter(this, void 0, void 0, function* () {
290
- const id = Date.now();
291
- const item = {
292
- id,
293
- title,
294
- body,
295
- fireAt: date,
296
- status: 'pending'
297
- };
298
- yield this.db.save(item);
299
- yield this.schedule(item);
300
- return id;
344
+ this.isAwake = () => __awaiter(this, void 0, void 0, function* () {
345
+ const res = yield KeepAwake.isKeptAwake();
346
+ return !!res.isKeptAwake;
301
347
  });
348
+ this.notif = new NotificationService(p === null || p === void 0 ? void 0 : p.notificationActionCallBack);
302
349
  }
303
- // -------------------------
304
- // SCHEDULE TO OS
305
- // -------------------------
306
- schedule(item) {
307
- return __awaiter(this, void 0, void 0, function* () {
308
- if (item.fireAt <= Date.now()) {
309
- yield this.fireNow(item);
310
- return;
311
- }
312
- yield LocalNotifications.schedule({
313
- notifications: [
314
- {
315
- id: item.id,
316
- title: item.title,
317
- body: item.body,
318
- schedule: {
319
- at: new Date(item.fireAt)
320
- }
321
- }
322
- ]
323
- });
324
- yield this.db.update(item.id, {
325
- status: 'scheduled'
350
+ }
351
+ class Logs {
352
+ constructor(p) {
353
+ this.logs = [];
354
+ this.removeExpiredLogs = (logs) => {
355
+ return logs.filter((o) => {
356
+ if (!o.expiredByHours) {
357
+ return true;
358
+ }
359
+ const currentTime = Date.now();
360
+ const delta = currentTime - o.date;
361
+ return delta < o.expiredByHours * 60 * 60 * 1000;
326
362
  });
327
- });
328
- }
329
- // -------------------------
330
- // IMMEDIATE NOTIFICATION
331
- // -------------------------
332
- fireNow(item) {
333
- return __awaiter(this, void 0, void 0, function* () {
334
- yield LocalNotifications.schedule({
335
- notifications: [
336
- {
337
- id: item.id,
338
- title: item.title,
339
- body: item.body,
340
- schedule: { at: new Date() }
363
+ };
364
+ this.addLog = (log) => {
365
+ let newLogs = [...this.logs, Object.assign(Object.assign({}, log), { date: Date.now(), id: log.id === undefined ? GenerateId('number') : log.id })];
366
+ if (log.repeat) {
367
+ const newReverseLogs = [];
368
+ let count = 0;
369
+ for (let i = newLogs.length - 1; i >= 0; i--) {
370
+ if (newLogs[i].id === log.id && count < log.repeat) {
371
+ newReverseLogs.push(newLogs[i]);
372
+ count++;
341
373
  }
342
- ]
343
- });
344
- yield this.db.update(item.id, {
345
- status: 'done'
346
- });
347
- });
348
- }
349
- // -------------------------
350
- // RESYNC AFTER RESTART
351
- // -------------------------
352
- resync() {
353
- return __awaiter(this, void 0, void 0, function* () {
354
- const all = yield this.db.getAll();
355
- const pending = all.filter(i => i.status !== 'done');
356
- for (const item of pending) {
357
- yield this.schedule(item);
374
+ else {
375
+ newReverseLogs.push(this.logs[i]);
376
+ }
377
+ }
378
+ newLogs = newReverseLogs.reverse();
358
379
  }
359
- });
360
- }
361
- // -------------------------
362
- // CANCEL
363
- // -------------------------
364
- cancel(id) {
365
- return __awaiter(this, void 0, void 0, function* () {
366
- yield LocalNotifications.cancel({
367
- notifications: [{ id }]
368
- });
369
- yield this.db.update(id, {
370
- status: 'done'
380
+ newLogs = this.removeExpiredLogs(newLogs);
381
+ this.logs = newLogs;
382
+ return newLogs;
383
+ };
384
+ this.remove = (p) => {
385
+ let newLogs = this.logs;
386
+ newLogs = newLogs.filter((o) => {
387
+ if (p.id !== undefined && o.id !== p.id) {
388
+ return false;
389
+ }
390
+ if (p.tags && p.tags.length) {
391
+ const dic = this.getTagsDic(p.tags);
392
+ return this.isTagsMatch(dic, o);
393
+ }
394
+ return true;
371
395
  });
372
- });
373
- }
374
- // -------------------------
375
- // LIST (DEBUG)
376
- // -------------------------
377
- list() {
378
- return __awaiter(this, void 0, void 0, function* () {
379
- return yield LocalNotifications.getPending();
380
- });
396
+ newLogs = this.removeExpiredLogs(newLogs);
397
+ this.logs = newLogs;
398
+ return newLogs;
399
+ };
400
+ this.getTagsDic = (tags) => {
401
+ const dic = {};
402
+ for (let i = 0; i < tags.length; i++) {
403
+ dic[tags[i]] = true;
404
+ }
405
+ return dic;
406
+ };
407
+ this.isTagsMatch = (tagsDic, log) => {
408
+ if (!log.tags || !log.tags.length) {
409
+ return false;
410
+ }
411
+ for (let i = 0; i < log.tags.length; i++) {
412
+ if (!tagsDic[log.tags[i]]) {
413
+ return false;
414
+ }
415
+ }
416
+ return true;
417
+ };
418
+ this.getLogs = (filter) => {
419
+ if (!filter) {
420
+ return this.logs;
421
+ }
422
+ let res = this.logs;
423
+ if (filter.tags) {
424
+ const dic = this.getTagsDic(filter.tags);
425
+ res = res.filter((o) => this.isTagsMatch(dic, o));
426
+ }
427
+ if (filter.status) {
428
+ res = res.filter((o) => o.status === filter.status);
429
+ }
430
+ return res;
431
+ };
432
+ this.load = p.load;
433
+ this.save = p.save;
381
434
  }
382
435
  }
383
- // const notifications = new NotificationService(db);
384
- // await notifications.init();
385
- // await notifications.notifyAt(
386
- // Date.now() + 10000,
387
- // "Hello",
388
- // "This is persistent notification"
389
- // );
390
436
  export class Tracker {
391
437
  constructor(p) {
392
438
  this.watchId = null;
@@ -433,265 +479,217 @@ export class Tracker {
433
479
  return !!this.watchId;
434
480
  }
435
481
  }
436
- class FileClass {
437
- constructor() {
438
- this.isNative = false;
439
- this.isUrl = (input) => input.startsWith("http://") || input.startsWith("https://") || input.startsWith("blob:");
440
- this.isDataUrl = (input) => input.startsWith("data:");
441
- this.toDataUrl = (input) => __awaiter(this, void 0, void 0, function* () {
442
- const blobRes = yield this.toBlob(input);
443
- if (!blobRes.success) {
444
- return { success: false, result: "", message: blobRes.message };
445
- }
446
- const fr = new FileReader();
447
- return new Promise((resolve) => {
448
- fr.onload = () => resolve({ success: true, result: fr.result, message: "" });
449
- fr.onerror = () => resolve({ success: false, result: "", message: "FileReader error" });
450
- fr.readAsDataURL(blobRes.result);
451
- });
482
+ export class NotificationService {
483
+ constructor(actionCallBack) {
484
+ this.notificationFile = 'notifications.json';
485
+ this.init = (actionCallBack) => __awaiter(this, void 0, void 0, function* () {
486
+ yield LocalNotifications.requestPermissions();
487
+ yield LocalNotifications.addListener('localNotificationReceived', (notification) => __awaiter(this, void 0, void 0, function* () { yield this.handleReceived(notification.id); }));
488
+ yield LocalNotifications.addListener('localNotificationActionPerformed', (event) => __awaiter(this, void 0, void 0, function* () {
489
+ var _a;
490
+ const actions = (_a = event.notification.extra) === null || _a === void 0 ? void 0 : _a.actions;
491
+ const action = actions === null || actions === void 0 ? void 0 : actions.find((action) => action === event.actionId);
492
+ if (!action || !actionCallBack)
493
+ return;
494
+ actionCallBack(action);
495
+ }));
496
+ yield this.resync();
452
497
  });
453
- this.fileToText = (file) => __awaiter(this, void 0, void 0, function* () {
454
- return new Promise((resolve, reject) => {
455
- const fr = new FileReader();
456
- fr.onload = () => {
457
- try {
458
- const result = fr.result;
459
- resolve(result);
460
- }
461
- catch (error) {
462
- reject(new Error('Error parsing JSON: ' + error.message));
463
- }
464
- };
465
- fr.onerror = () => reject(new Error('Error reading file.'));
466
- fr.readAsText(file);
498
+ this.handleReceived = (id) => __awaiter(this, void 0, void 0, function* () {
499
+ const items = yield this.getList();
500
+ const item = items.find(item => item.id === id);
501
+ if (!item)
502
+ return;
503
+ item.showInExpired = false;
504
+ if (item.keepUntil === undefined) {
505
+ yield this.save(items.filter(item => item.id !== id));
506
+ return;
507
+ }
508
+ yield this.save(items);
509
+ });
510
+ this.getChannelId = (item) => {
511
+ var _a, _b;
512
+ return [
513
+ (_a = item.importance) !== null && _a !== void 0 ? _a : 'default',
514
+ (_b = item.sound) !== null && _b !== void 0 ? _b : 'none',
515
+ item.vibration ? 'vibration' : 'no-vibration'
516
+ ].join('-');
517
+ };
518
+ this.registerChannel = (channel) => __awaiter(this, void 0, void 0, function* () {
519
+ yield LocalNotifications.createChannel({
520
+ id: channel.id,
521
+ name: channel.name,
522
+ description: channel.description,
523
+ importance: this.getImportance(channel.importance),
524
+ sound: channel.sound,
525
+ vibration: channel.vibration
467
526
  });
468
527
  });
469
- this.readText = (input) => __awaiter(this, void 0, void 0, function* () {
470
- if (typeof input === 'object' && 'path' in input && 'directory' in input) {
471
- return yield this.readCapacitorText(input.path, input.directory);
472
- }
473
- else {
474
- try {
475
- const blobRes = yield this.toBlob(input);
476
- if (!blobRes.success)
477
- return blobRes;
478
- let result = yield blobRes.result.text();
479
- return { success: true, result, message: "" };
480
- }
481
- catch (e) {
482
- return { success: false, result: "", message: (e === null || e === void 0 ? void 0 : e.message) || `read text failed` };
528
+ this.register = (_item) => __awaiter(this, void 0, void 0, function* () {
529
+ const items = yield this.getList();
530
+ const id = items.length ? Math.max(...items.map(item => item.id)) + 1 : 1;
531
+ const item = Object.assign(Object.assign({}, _item), { id });
532
+ items.push(item);
533
+ yield this.save(items);
534
+ if (item.fireAt <= Date.now()) {
535
+ if (item.showInExpired) {
536
+ yield this.schedule(item, true);
537
+ item.showInExpired = false;
538
+ yield this.save(items);
483
539
  }
540
+ return id;
484
541
  }
542
+ yield this.schedule(item);
543
+ return id;
485
544
  });
486
- this.readCapacitorText = (path, directory) => __awaiter(this, void 0, void 0, function* () {
487
- try {
488
- const res = yield this.pathToBase64(path, directory);
489
- if (!res.success) {
490
- return { success: false, result: null, message: 'Empty file' };
491
- }
492
- const blobRes = this.base64ToBlob(res.result);
493
- if (!blobRes.success) {
494
- return blobRes;
495
- }
496
- return this.readText(blobRes.result);
545
+ this.cancel = (p) => __awaiter(this, void 0, void 0, function* () {
546
+ if (p.ids !== undefined) {
547
+ yield this.cancelByIds(p.ids);
497
548
  }
498
- catch (e) {
499
- return { success: false, result: null, message: (e === null || e === void 0 ? void 0 : e.message) || 'Storage read failed' };
549
+ if (p.tags !== undefined) {
550
+ yield this.cancelByTags(p.tags);
500
551
  }
501
552
  });
502
- this.pathToBase64 = (path, directory) => __awaiter(this, void 0, void 0, function* () {
503
- const a = new AIOCapacitor();
504
- const res = yield a.readFile(path, directory);
505
- if (!(res === null || res === void 0 ? void 0 : res.data)) {
506
- return { success: false, result: null, message: 'Empty file' };
553
+ this.cancelByIds = (ids) => __awaiter(this, void 0, void 0, function* () {
554
+ for (const id of ids) {
555
+ yield this.cancelById(id);
507
556
  }
508
- return { success: true, result: res.data, message: '' };
509
557
  });
510
- this.pathToSrc = (path, directory) => __awaiter(this, void 0, void 0, function* () { return yield new AIOCapacitor().pathToSrc(path, directory); });
511
- this.toSrc = (file) => typeof file === 'string' ? file : window.URL.createObjectURL(file);
512
- this.toBase64 = (input) => __awaiter(this, void 0, void 0, function* () {
513
- const dataUrl = yield this.toDataUrl(input);
514
- if (!dataUrl.success) {
515
- return { success: false, result: "", message: dataUrl.message };
558
+ this.cancelById = (id) => __awaiter(this, void 0, void 0, function* () {
559
+ yield LocalNotifications.cancel({ notifications: [{ id }] });
560
+ const items = yield this.getList();
561
+ const newItems = items.filter(item => item.id !== id);
562
+ if (newItems.length !== items.length) {
563
+ yield this.save(newItems);
516
564
  }
517
- return this.dataUrlToBase64(dataUrl.result);
518
565
  });
519
- this.GetDurationByUrl = (url) => __awaiter(this, void 0, void 0, function* () {
520
- return new Promise((resolve) => {
521
- const video = document.createElement("video");
522
- video.preload = "metadata";
523
- video.src = url;
524
- video.onloadedmetadata = () => { resolve(isNaN(video.duration) ? null : video.duration); video.remove(); };
525
- video.onerror = () => { resolve(null); video.remove(); };
526
- });
527
- });
528
- this.GetSizeByUrl = (url) => __awaiter(this, void 0, void 0, function* () {
529
- let size = null;
530
- try {
531
- const res = yield fetch(url, { method: "HEAD" });
532
- const contentLength = res.headers.get("content-length");
533
- if (contentLength)
534
- size = parseInt(contentLength, 10);
535
- }
536
- catch (err) { }
537
- return size;
538
- });
539
- this.GetNameByUrl = (url) => { var _a; return decodeURIComponent(((_a = url.split("/").pop()) === null || _a === void 0 ? void 0 : _a.split("?")[0]) || "unknown"); };
540
- this.GetFileDetailsByUrl = (url) => __awaiter(this, void 0, void 0, function* () {
541
- const name = this.GetNameByUrl(url);
542
- const size = yield this.GetSizeByUrl(url);
543
- const duration = yield this.GetDurationByUrl(url);
544
- return { name, size, duration };
545
- });
546
- this.fetchBlob = (url) => __awaiter(this, void 0, void 0, function* () {
547
- try {
548
- const res = yield fetch(url);
549
- if (!res.ok) {
550
- return { success: false, result: null, message: `HTTP Error: ${res.status}` };
551
- }
552
- const blob = yield res.blob();
553
- return { success: true, result: blob, message: "" };
554
- }
555
- catch (e) {
556
- return { success: false, result: null, message: (e === null || e === void 0 ? void 0 : e.message) || "Fetch failed" };
566
+ this.cancelByTag = (tag) => __awaiter(this, void 0, void 0, function* () {
567
+ const items = yield this.getList();
568
+ const tagItems = items.filter(item => { var _a; return (_a = item.tags) === null || _a === void 0 ? void 0 : _a.includes(tag); });
569
+ for (const item of tagItems) {
570
+ yield this.cancelById(item.id);
557
571
  }
558
572
  });
559
- this.fetchBlob2 = () => __awaiter(this, void 0, void 0, function* () {
573
+ this.cancelByTags = (tags) => __awaiter(this, void 0, void 0, function* () {
574
+ for (const tag of tags) {
575
+ yield this.cancelByTag(tag);
576
+ }
560
577
  });
561
- this.base64ToBlob = (base64) => {
562
- try {
563
- const byteCharacters = atob(base64);
564
- const byteNumbers = new Array(byteCharacters.length);
565
- for (let i = 0; i < byteCharacters.length; i++) {
566
- byteNumbers[i] = byteCharacters.charCodeAt(i);
578
+ this.resync = () => __awaiter(this, void 0, void 0, function* () {
579
+ const items = yield this.getList();
580
+ const now = Date.now();
581
+ const pending = yield LocalNotifications.getPending();
582
+ const pendingIds = new Set(pending.notifications.map(notification => notification.id));
583
+ const validItems = [];
584
+ for (const item of items) {
585
+ if (item.keepUntil !== undefined && item.keepUntil <= now) {
586
+ yield LocalNotifications.cancel({ notifications: [{ id: item.id }] });
587
+ continue;
588
+ }
589
+ if (item.fireAt <= now) {
590
+ if (pendingIds.has(item.id)) {
591
+ validItems.push(item);
592
+ continue;
593
+ }
594
+ if (item.showInExpired) {
595
+ yield this.schedule(item, true);
596
+ item.showInExpired = false;
597
+ }
598
+ if (item.keepUntil !== undefined) {
599
+ validItems.push(item);
600
+ }
601
+ continue;
602
+ }
603
+ validItems.push(item);
604
+ if (!pendingIds.has(item.id)) {
605
+ yield this.schedule(item);
567
606
  }
568
- const byteArray = new Uint8Array(byteNumbers);
569
- return { success: true, result: new Blob([byteArray]), message: "" };
570
607
  }
571
- catch (e) {
572
- return { success: false, result: null, message: (e === null || e === void 0 ? void 0 : e.message) || "Invalid base64" };
608
+ yield this.save(validItems);
609
+ });
610
+ this.schedule = (item, atNow) => __awaiter(this, void 0, void 0, function* () {
611
+ yield this.registerActionType(item);
612
+ const channelId = this.getChannelId(item);
613
+ yield this.registerChannel({ id: channelId, name: channelId, importance: item.importance, sound: item.sound, vibration: item.vibration });
614
+ yield LocalNotifications.schedule({
615
+ notifications: [{
616
+ id: item.id, title: item.title, body: item.body, channelId,
617
+ actionTypeId: this.getActionTypeId(item),
618
+ extra: { actions: item.actions },
619
+ schedule: !atNow ? { at: new Date(item.fireAt) } : undefined
620
+ }]
621
+ });
622
+ });
623
+ this.registerActionType = (item) => __awaiter(this, void 0, void 0, function* () {
624
+ var _b;
625
+ if (!((_b = item.actions) === null || _b === void 0 ? void 0 : _b.length))
626
+ return;
627
+ yield LocalNotifications.registerActionTypes({
628
+ types: [{ id: this.getActionTypeId(item), actions: item.actions.map(action => ({ id: action, title: action })) }]
629
+ });
630
+ });
631
+ this.getActionTypeId = (item) => `notification-${item.id}`;
632
+ this.getImportance = (importance) => {
633
+ switch (importance) {
634
+ case 'low': return 2;
635
+ case 'high': return 4;
636
+ default: return 3;
573
637
  }
574
638
  };
575
- this.handleFileName = (selectedName) => selectedName || window.prompt('Please Enter File Name') || `file-${Date.now()}.json`;
576
- this.generateFileName = (mimeType) => {
577
- const map = {
578
- 'application/json': 'file.json',
579
- 'text/plain': 'file.txt',
580
- 'text/html': 'file.html',
581
- 'text/csv': 'file.csv',
582
- 'application/pdf': 'file.pdf',
583
- 'image/png': 'image.png',
584
- 'image/jpeg': 'image.jpg',
585
- 'image/webp': 'image.webp',
586
- 'application/zip': 'archive.zip',
587
- 'application/octet-stream': 'file.bin'
588
- };
589
- const base = map[mimeType || ''] || 'file.bin';
590
- const timestamp = Date.now();
591
- const [name, ext] = base.split('.');
592
- return `${name}-${timestamp}.${ext}`;
593
- };
594
- this.saveWeb = (url, fileName) => __awaiter(this, void 0, void 0, function* () {
595
- const a = document.createElement('a');
596
- a.href = url;
597
- a.download = fileName;
598
- document.body.appendChild(a);
599
- a.click();
600
- document.body.removeChild(a);
601
- URL.revokeObjectURL(url);
602
- return { success: true, message: '' };
603
- });
604
- this.dataUrlToBase64 = (dataUrl) => {
605
- try {
606
- const base64 = dataUrl.split(",")[1];
607
- return { success: true, result: base64, message: "" };
639
+ this.tagsMatch = (tagsDic, itemTags) => {
640
+ if (!itemTags || !itemTags.length) {
641
+ return false;
608
642
  }
609
- catch (_a) {
610
- return { success: false, result: "", message: "Invalid data url" };
611
- }
612
- };
613
- this.toBlob = (input) => __awaiter(this, void 0, void 0, function* () {
614
- try {
615
- if (input instanceof Blob) {
616
- return { success: true, result: input, message: "" };
617
- }
618
- if (input instanceof ArrayBuffer) {
619
- const result = new Blob([input], { type: 'application/octet-stream' });
620
- return { success: true, result };
621
- }
622
- if (input instanceof Uint8Array) {
623
- const buffer = input.buffer instanceof ArrayBuffer ? input.buffer : new ArrayBuffer(input.byteLength);
624
- const result = new Blob([new Uint8Array(buffer)], { type: 'application/octet-stream' });
625
- return { success: true, result };
643
+ return itemTags.filter((itemTag) => {
644
+ if (!tagsDic[itemTag]) {
645
+ return false;
626
646
  }
627
- if (typeof input !== "string") {
628
- const result = new Blob([JSON.stringify(input)], { type: 'application/json' });
629
- return { success: true, result, message: "" };
630
- }
631
- if (this.isDataUrl(input)) {
632
- const base64 = this.dataUrlToBase64(input);
633
- if (!base64.success) {
634
- return { success: false, result: null, message: base64.message };
635
- }
636
- return this.base64ToBlob(base64.result);
637
- }
638
- if (this.isUrl(input)) {
639
- return yield this.fetchBlob(input);
640
- }
641
- return { success: false, result: null, message: "Unsupported input" };
647
+ });
648
+ return true;
649
+ };
650
+ this.getTagsDic = (tags) => {
651
+ if (!tags) {
652
+ return {};
642
653
  }
643
- catch (e) {
644
- return { success: false, result: null, message: e === null || e === void 0 ? void 0 : e.message };
654
+ const res = {};
655
+ for (let i = 0; i < tags.length; i++) {
656
+ res[tags[i]] = true;
645
657
  }
646
- });
647
- this.saveText = (text, path) => __awaiter(this, void 0, void 0, function* () {
658
+ return res;
659
+ };
660
+ this.getList = (filter) => __awaiter(this, void 0, void 0, function* () {
648
661
  try {
649
- if (this.isNative) {
650
- return yield new AIOCapacitor().save(text, path);
662
+ const result = yield Filesystem.readFile({ path: this.notificationFile, directory: Directory.Data, encoding: Encoding.UTF8 });
663
+ const res = JSON.parse(result.data);
664
+ if (!filter) {
665
+ return res;
651
666
  }
652
667
  else {
653
- const blob = new Blob([text], { type: "text/plain" });
654
- const url = URL.createObjectURL(blob);
655
- try {
656
- return yield this.saveWeb(url, path);
657
- }
658
- finally {
659
- URL.revokeObjectURL(url);
660
- }
668
+ const tagsDic = this.getTagsDic(filter.tags);
669
+ const now = Date.now();
670
+ return res.filter((o) => {
671
+ if (filter.fired !== undefined) {
672
+ const fired = o.fireAt < now;
673
+ if (filter.fired && !fired) {
674
+ return false;
675
+ }
676
+ if (!filter.fired && fired) {
677
+ return false;
678
+ }
679
+ }
680
+ if (filter.tags && filter.tags.length) {
681
+ return this.tagsMatch(tagsDic, filter.tags);
682
+ }
683
+ });
661
684
  }
662
685
  }
663
- catch (e) {
664
- return { success: false, message: (e === null || e === void 0 ? void 0 : e.message) || "Text download failed" };
686
+ catch (_c) {
687
+ return [];
665
688
  }
666
689
  });
667
- this.saveFile = (input, path) => __awaiter(this, void 0, void 0, function* () {
668
- const blobRes = yield new FileClass().toBlob(input);
669
- if (!blobRes.success) {
670
- return { success: false, message: blobRes.message };
671
- }
672
- if (this.isNative) {
673
- return yield new AIOCapacitor().save(blobRes.result, path);
674
- }
675
- else {
676
- const url = URL.createObjectURL(blobRes.result);
677
- yield this.saveWeb(url, path);
678
- return { success: true, message: '' };
679
- }
680
- });
681
- this.sizeToString = (size) => {
682
- if (typeof size !== "number")
683
- size = 0;
684
- const gb = size / (Math.pow(1024, 3));
685
- const mb = size / (Math.pow(1024, 2));
686
- const kb = size / 1024;
687
- if (gb >= 1)
688
- return gb.toFixed(2) + " GB";
689
- if (mb >= 1)
690
- return mb.toFixed(2) + " MB";
691
- if (kb >= 1)
692
- return kb.toFixed(2) + " KB";
693
- return size + " byte";
694
- };
695
- this.isNative = new AIOCapacitor().isNative();
690
+ this.save = (items) => __awaiter(this, void 0, void 0, function* () {
691
+ yield Filesystem.writeFile({ path: this.notificationFile, directory: Directory.Data, data: JSON.stringify(items), encoding: Encoding.UTF8 });
692
+ });
693
+ this.init(actionCallBack);
696
694
  }
697
695
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aio-capacitor",
3
- "version": "2.1.0",
3
+ "version": "2.2.2",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -8,18 +8,20 @@
8
8
  "test": "echo \"Error: no test specified\" && exit 1"
9
9
  },
10
10
  "dependencies": {
11
- "@capacitor/core": "^8.4.0",
12
- "@capacitor/preferences": "^8.0.1",
13
- "@capacitor/clipboard": "^8.0.1",
14
- "@capacitor/camera": "^8.2.0",
15
- "@capacitor/geolocation": "^8.2.0",
16
- "@capacitor/push-notifications": "^8.1.1",
17
- "@capacitor-community/text-to-speech": "^8.0.0",
18
- "@capacitor/filesystem": "^8.1.2",
19
- "@capacitor/haptics": "^8.0.2",
20
- "@capacitor/share": "^8.0.1",
21
- "@capacitor/local-notifications": "^8.2.0",
22
- "@capacitor-community/keep-awake": "^8.0.1"
11
+ "@capacitor-community/keep-awake": "latest",
12
+ "@capacitor-community/text-to-speech": "latest",
13
+ "@capacitor/camera": "latest",
14
+ "@capacitor/clipboard": "latest",
15
+ "@capacitor/core": "latest",
16
+ "@capacitor/filesystem": "latest",
17
+ "@capacitor/geolocation": "latest",
18
+ "@capacitor/haptics": "latest",
19
+ "@capacitor/local-notifications": "latest",
20
+ "@capacitor/preferences": "latest",
21
+ "@capacitor/push-notifications": "latest",
22
+ "@capacitor/share": "latest",
23
+ "aio-capacitor-folder-picker":"latest",
24
+ "aio-class":"latest"
23
25
  },
24
26
  "repository": {
25
27
  "type": "git",