aio-capacitor 2.2.0 → 2.2.3

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 +125 -36
  2. package/index.js +453 -133
  3. package/package.json +14 -2
package/index.d.ts CHANGED
@@ -1,18 +1,3 @@
1
- type I_logItem = {
2
- tags?: string[];
3
- id?: string;
4
- message: string;
5
- status?: 'error' | 'success' | 'warning' | 'info';
6
- data?: any;
7
- date?: number;
8
- };
9
- export type NotificationItem = {
10
- id: number;
11
- title: string;
12
- body: string;
13
- fireAt: number;
14
- status: 'pending' | 'scheduled' | 'done';
15
- };
16
1
  export type I_speak = {
17
2
  text: string;
18
3
  lang?: 'fa-IR' | 'en-US';
@@ -21,17 +6,35 @@ export type I_speak = {
21
6
  };
22
7
  type PermissionName = "CAMERA" | "ACCESS_FINE_LOCATION" | "ACCESS_COARSE_LOCATION" | "POST_NOTIFICATIONS";
23
8
  export declare class AIOCapacitor {
24
- onLog: ((log: I_logItem) => void) | undefined;
9
+ logs: Logs;
10
+ notif: NotificationService;
25
11
  constructor(p?: {
26
- onLog?: (log: I_logItem) => void;
12
+ notificationActionCallBack?: (actionId: string) => void;
27
13
  });
28
14
  getPlatform: () => 'web' | 'android' | 'ios';
29
15
  isNative: () => boolean;
30
- 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[]>;
31
25
  vibrate: (p: {
32
26
  pattern?: number[];
33
27
  density?: 'light' | 'medium' | 'heavy';
34
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[];
35
38
  vibratePattern: (pattern: number[]) => Promise<void>;
36
39
  vibrateImpact: (style?: 'light' | 'medium' | 'heavy') => Promise<void>;
37
40
  getPermissions: (permissionNames: PermissionName[]) => Promise<void>;
@@ -46,12 +49,36 @@ export declare class AIOCapacitor {
46
49
  storageLoad: (name: string, def: any) => Promise<any>;
47
50
  copy: (text: string) => Promise<void>;
48
51
  paste: () => Promise<string>;
49
- readFile: (path: string, directory: Directory) => Promise<any>;
52
+ getDirectory: (location?: 'Data' | 'Documents' | 'Cache') => any;
50
53
  uriToSrc: (uri: string) => Promise<any>;
51
54
  pathToUri: (path: string, directory: Directory) => Promise<any>;
52
55
  pathToSrc: (path: string, directory: Directory) => Promise<any>;
53
- writeFile: (data: string, path: string, encoding?: boolean) => Promise<any>;
54
- 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
+ isFileExist: (path: string, location?: 'Data' | 'Documents' | 'Cache') => Promise<boolean>;
69
+ readFile: (path: string, def: any, options?: {
70
+ location?: 'Data' | 'Documents' | 'Cache';
71
+ utf8?: boolean;
72
+ writeDef?: boolean;
73
+ }) => Promise<any>;
74
+ writeFile: (data: any, path: string, options?: {
75
+ location?: 'Data' | 'Documents' | 'Cache';
76
+ utf8?: boolean;
77
+ }) => Promise<string>;
78
+ save: (data: string | File | Blob, path: string, options?: {
79
+ location?: 'Data' | 'Documents' | 'Cache';
80
+ utf8?: boolean;
81
+ }) => Promise<{
55
82
  success: boolean;
56
83
  message: any;
57
84
  }>;
@@ -62,6 +89,7 @@ export declare class AIOCapacitor {
62
89
  success: boolean;
63
90
  error: any;
64
91
  }>;
92
+ getExtensions: (type: 'image' | 'audio' | 'video') => string[];
65
93
  shareFile: (file: Blob | File, fileName?: string) => Promise<any>;
66
94
  getLocation: () => Promise<{
67
95
  success: boolean;
@@ -72,23 +100,38 @@ export declare class AIOCapacitor {
72
100
  error?: string;
73
101
  }>;
74
102
  awake: (state?: boolean) => Promise<any>;
75
- isAwake: () => Promise<any>;
103
+ isAwake: () => Promise<boolean>;
76
104
  }
77
- type DB = {
78
- save: (item: NotificationItem) => Promise<void>;
79
- getAll: () => Promise<NotificationItem[]>;
80
- update: (id: number, patch: Partial<NotificationItem>) => Promise<void>;
105
+ type I_logItem = {
106
+ tags: string[];
107
+ id?: number;
108
+ repeat?: number;
109
+ message: string;
110
+ status: 'error' | 'success' | 'warning' | 'info';
111
+ data?: any;
112
+ expiredByHours?: number;
113
+ date: number;
81
114
  };
82
- export declare class NotificationService {
83
- private db;
84
- constructor(db: DB);
85
- init(): Promise<void>;
86
- notifyAt(date: number, title: string, body: string): Promise<number>;
87
- private schedule;
88
- private fireNow;
89
- resync(): Promise<void>;
90
- cancel(id: number): Promise<void>;
91
- list(): Promise<any>;
115
+ declare class Logs {
116
+ logs: I_logItem[];
117
+ load: () => Promise<I_logItem[]>;
118
+ save: (logs: I_logItem[]) => Promise<void>;
119
+ constructor(p: {
120
+ load: () => Promise<I_logItem[]>;
121
+ save: (logs: I_logItem[]) => Promise<void>;
122
+ });
123
+ private removeExpiredLogs;
124
+ addLog: (log: Omit<I_logItem, 'date'>) => I_logItem[];
125
+ remove: (p: {
126
+ id?: number;
127
+ tags?: string[];
128
+ }) => I_logItem[];
129
+ private getTagsDic;
130
+ private isTagsMatch;
131
+ getLogs: (filter?: {
132
+ tags?: string[];
133
+ status?: 'error' | 'success' | 'warning' | 'info';
134
+ }) => I_logItem[];
92
135
  }
93
136
  export declare class Tracker {
94
137
  private watchId;
@@ -110,4 +153,50 @@ export declare class Tracker {
110
153
  stop(): Promise<void>;
111
154
  isTracking(): boolean;
112
155
  }
156
+ export type I_notifItem = {
157
+ id: number;
158
+ title: string;
159
+ body: string;
160
+ fireAt: number;
161
+ showInExpired?: boolean;
162
+ keepUntil?: number;
163
+ actions?: string[];
164
+ tags?: string[];
165
+ importance?: 'low' | 'default' | 'high';
166
+ sound?: string;
167
+ vibration?: boolean;
168
+ };
169
+ export declare class NotificationService {
170
+ private notificationFile;
171
+ constructor(actionCallBack?: (actionId: string) => void);
172
+ init: (actionCallBack?: (actionId: string) => void) => Promise<void>;
173
+ private handleReceived;
174
+ private getChannelId;
175
+ private registerChannel;
176
+ register: (_item: I_notifItem) => Promise<number>;
177
+ cancel: (p: {
178
+ tags?: string[];
179
+ ids?: number[];
180
+ }) => Promise<void>;
181
+ private cancelByIds;
182
+ private cancelById;
183
+ private cancelByTag;
184
+ private cancelByTags;
185
+ private resync;
186
+ private schedule;
187
+ private registerActionType;
188
+ private getActionTypeId;
189
+ private getImportance;
190
+ tagsMatch: (tagsDic: {
191
+ [tag: string]: boolean;
192
+ }, itemTags?: string[]) => boolean | string[];
193
+ getTagsDic: (tags?: string[]) => {
194
+ [tag: string]: boolean;
195
+ };
196
+ getList: (filter?: {
197
+ fired?: boolean;
198
+ tags?: string[];
199
+ }) => Promise<I_notifItem[]>;
200
+ private save;
201
+ }
113
202
  export {};
package/index.js CHANGED
@@ -7,18 +7,48 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import { Capacitor, Preferences, Clipboard, Camera, Geolocation, PushNotifications, TextToSpeech, Filesystem, Directory, Encoding, Haptics, ImpactStyle, Share, LocalNotifications, KeepAwake } from 'aio-capacitor-deps';
11
- import { FileClass } from 'aio-class';
10
+ import { Capacitor } from '@capacitor/core';
11
+ import { Preferences } from '@capacitor/preferences';
12
+ import { Clipboard } from '@capacitor/clipboard';
13
+ import { Camera } from '@capacitor/camera';
14
+ import { Geolocation } from '@capacitor/geolocation';
15
+ import { PushNotifications } from '@capacitor/push-notifications';
16
+ import { TextToSpeech } from '@capacitor-community/text-to-speech';
17
+ import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
18
+ import { Haptics, ImpactStyle } from '@capacitor/haptics';
19
+ import { Share } from '@capacitor/share';
20
+ import { LocalNotifications } from '@capacitor/local-notifications';
21
+ import { KeepAwake } from '@capacitor-community/keep-awake';
22
+ import { FolderPicker } from 'aio-capacitor-folder-picker';
23
+ import { FileClass, GenerateId } from 'aio-class';
12
24
  export class AIOCapacitor {
13
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();
14
47
  this.getPlatform = () => Capacitor.getPlatform();
15
48
  this.isNative = () => ['android', 'ios'].indexOf(Capacitor.getPlatform()) !== -1;
16
- this.addLog = (log) => {
17
- if (!this.onLog) {
18
- return;
19
- }
20
- this.onLog(log);
21
- };
49
+ this.addNotif = this.notif.register;
50
+ this.cancelNotif = this.notif.cancel;
51
+ this.getNotifs = this.notif.getList;
22
52
  this.vibrate = (p) => __awaiter(this, void 0, void 0, function* () {
23
53
  if (p.pattern) {
24
54
  yield this.vibratePattern(p.pattern);
@@ -27,6 +57,9 @@ export class AIOCapacitor {
27
57
  this.vibrateImpact(p.density);
28
58
  }
29
59
  });
60
+ this.addLog = this.logs.addLog;
61
+ this.removeLog = this.logs.remove;
62
+ this.getLogs = this.logs.getLogs;
30
63
  this.vibratePattern = (pattern) => __awaiter(this, void 0, void 0, function* () {
31
64
  try {
32
65
  for (const duration of pattern) {
@@ -52,34 +85,34 @@ export class AIOCapacitor {
52
85
  }
53
86
  });
54
87
  this.getPermissions = (permissionNames) => __awaiter(this, void 0, void 0, function* () {
55
- var _a, _b, _c, _d, _e;
56
88
  for (const permission of permissionNames) {
57
89
  try {
58
90
  switch (permission) {
59
91
  case "CAMERA": {
60
92
  yield Camera.requestPermissions();
61
- (_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'] });
62
94
  break;
63
95
  }
64
96
  case "ACCESS_FINE_LOCATION":
65
97
  case "ACCESS_COARSE_LOCATION": {
66
98
  yield Geolocation.requestPermissions();
67
- (_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'] });
68
100
  break;
69
101
  }
70
102
  case "POST_NOTIFICATIONS": {
71
103
  yield PushNotifications.requestPermissions();
72
- (_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'] });
73
105
  break;
74
106
  }
75
107
  default:
76
- (_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'] });
77
109
  }
78
110
  }
79
111
  catch (err) {
80
- (_e = this.addLog) === null || _e === void 0 ? void 0 : _e.call(this, {
112
+ this.addLog({
81
113
  message: `Permission error for ${permission}: ${err === null || err === void 0 ? void 0 : err.message}`,
82
- status: "error"
114
+ status: "error",
115
+ tags: ['permission']
83
116
  });
84
117
  }
85
118
  }
@@ -137,17 +170,73 @@ export class AIOCapacitor {
137
170
  return '';
138
171
  }
139
172
  });
140
- 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
+ };
141
176
  this.uriToSrc = (uri) => __awaiter(this, void 0, void 0, function* () { return Capacitor.convertFileSrc(uri); });
142
177
  this.pathToUri = (path, directory) => __awaiter(this, void 0, void 0, function* () { return (yield Filesystem.getUri({ path, directory })).uri; });
143
178
  this.pathToSrc = (path, directory) => __awaiter(this, void 0, void 0, function* () { return yield this.uriToSrc(yield this.pathToUri(path, directory)); });
144
- 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 }); });
145
- 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.isFileExist = (path, location) => __awaiter(this, void 0, void 0, function* () {
202
+ try {
203
+ yield Filesystem.stat({ path, directory: this.getDirectory(location) });
204
+ return true;
205
+ }
206
+ catch (_a) {
207
+ return false;
208
+ }
209
+ });
210
+ this.readFile = (path, def, options) => __awaiter(this, void 0, void 0, function* () {
211
+ const location = options === null || options === void 0 ? void 0 : options.location;
212
+ const isJson = typeof def !== 'string';
213
+ if (!(yield this.isFileExist(path, location))) {
214
+ if (options === null || options === void 0 ? void 0 : options.writeDef) {
215
+ yield this.writeFile(isJson ? JSON.stringify(def) : def, path, { location, utf8: isJson ? true : options === null || options === void 0 ? void 0 : options.utf8 });
216
+ }
217
+ return def;
218
+ }
219
+ const res = yield Filesystem.readFile({
220
+ path, directory: this.getDirectory(location),
221
+ encoding: isJson || (options === null || options === void 0 ? void 0 : options.utf8) ? Encoding.UTF8 : undefined
222
+ });
223
+ return isJson ? JSON.parse(res.data) : res.data;
224
+ });
225
+ this.writeFile = (data, path, options) => __awaiter(this, void 0, void 0, function* () {
226
+ const res = yield Filesystem.writeFile({
227
+ path,
228
+ data: typeof data === 'string' ? data : JSON.stringify(data),
229
+ directory: this.getDirectory(options === null || options === void 0 ? void 0 : options.location),
230
+ encoding: (options === null || options === void 0 ? void 0 : options.utf8) ? Encoding.UTF8 : undefined
231
+ });
232
+ return res.uri;
233
+ });
234
+ this.save = (data, path, options) => __awaiter(this, void 0, void 0, function* () {
146
235
  try {
147
236
  const fs = new FileClass();
148
237
  if (typeof data === 'string' && !fs.isUrl(data)) {
149
238
  try {
150
- yield this.writeFile(data, path, true);
239
+ yield this.writeFile(data, path, options);
151
240
  return { success: true, message: '' };
152
241
  }
153
242
  catch (err) {
@@ -163,7 +252,8 @@ export class AIOCapacitor {
163
252
  if (!res2.success) {
164
253
  return { success: false, message: res2.message };
165
254
  }
166
- yield this.writeFile(res2.result, path);
255
+ alert(res2.result.slice(0, 50));
256
+ yield this.writeFile(res2.result, path, options);
167
257
  return { success: true, message: '' };
168
258
  }
169
259
  }
@@ -180,6 +270,26 @@ export class AIOCapacitor {
180
270
  return { success: false, error: (err === null || err === void 0 ? void 0 : err.message) || err };
181
271
  }
182
272
  });
273
+ this.getExtensions = (type) => {
274
+ const extensions = {
275
+ image: [
276
+ 'jpg', 'jpeg', 'png', 'gif', 'webp',
277
+ 'bmp', 'svg', 'ico', 'tiff', 'tif', 'avif'
278
+ ],
279
+ audio: [
280
+ 'mp3', 'wav', 'flac', 'aac', 'm4a',
281
+ 'ogg', 'oga', 'opus', 'wma', 'aiff', 'aif',
282
+ 'alac', 'amr', 'mid', 'midi'
283
+ ],
284
+ video: [
285
+ 'mp4', 'webm', 'mkv', 'avi', 'mov',
286
+ 'wmv', 'flv', 'm4v', '3gp', '3g2',
287
+ 'mpeg', 'mpg', 'mts', 'm2ts', 'ts',
288
+ 'ogv', 'vob'
289
+ ]
290
+ };
291
+ return extensions[type];
292
+ };
183
293
  this.shareFile = (file_1, ...args_2) => __awaiter(this, [file_1, ...args_2], void 0, function* (file, fileName = `file_${Date.now()}`) {
184
294
  try {
185
295
  const res = yield new FileClass().toDataUrl(file);
@@ -249,7 +359,7 @@ export class AIOCapacitor {
249
359
  const _isAwake = yield this.isAwake();
250
360
  _awake = !_isAwake;
251
361
  }
252
- if (_awake) {
362
+ if (!_awake) {
253
363
  yield KeepAwake.allowSleep();
254
364
  }
255
365
  else {
@@ -257,126 +367,98 @@ export class AIOCapacitor {
257
367
  }
258
368
  return _awake;
259
369
  });
260
- this.isAwake = () => __awaiter(this, void 0, void 0, function* () { return yield KeepAwake.isKeptAwake(); });
261
- this.onLog = p === null || p === void 0 ? void 0 : p.onLog;
262
- }
263
- }
264
- export class NotificationService {
265
- constructor(db) { this.db = db; }
266
- // -------------------------
267
- // INIT (CRITICAL)
268
- // -------------------------
269
- init() {
270
- return __awaiter(this, void 0, void 0, function* () {
271
- yield LocalNotifications.requestPermissions();
272
- yield this.resync();
370
+ this.isAwake = () => __awaiter(this, void 0, void 0, function* () {
371
+ const res = yield KeepAwake.isKeptAwake();
372
+ return !!res.isKeptAwake;
273
373
  });
374
+ this.notif = new NotificationService(p === null || p === void 0 ? void 0 : p.notificationActionCallBack);
274
375
  }
275
- // -------------------------
276
- // CREATE NOTIFICATION
277
- // -------------------------
278
- notifyAt(date, title, body) {
279
- return __awaiter(this, void 0, void 0, function* () {
280
- const id = Date.now();
281
- const item = {
282
- id,
283
- title,
284
- body,
285
- fireAt: date,
286
- status: 'pending'
287
- };
288
- yield this.db.save(item);
289
- yield this.schedule(item);
290
- return id;
291
- });
292
- }
293
- // -------------------------
294
- // SCHEDULE TO OS
295
- // -------------------------
296
- schedule(item) {
297
- return __awaiter(this, void 0, void 0, function* () {
298
- if (item.fireAt <= Date.now()) {
299
- yield this.fireNow(item);
300
- return;
301
- }
302
- yield LocalNotifications.schedule({
303
- notifications: [
304
- {
305
- id: item.id,
306
- title: item.title,
307
- body: item.body,
308
- schedule: {
309
- at: new Date(item.fireAt)
310
- }
311
- }
312
- ]
313
- });
314
- yield this.db.update(item.id, {
315
- status: 'scheduled'
376
+ }
377
+ class Logs {
378
+ constructor(p) {
379
+ this.logs = [];
380
+ this.removeExpiredLogs = (logs) => {
381
+ return logs.filter((o) => {
382
+ if (!o.expiredByHours) {
383
+ return true;
384
+ }
385
+ const currentTime = Date.now();
386
+ const delta = currentTime - o.date;
387
+ return delta < o.expiredByHours * 60 * 60 * 1000;
316
388
  });
317
- });
318
- }
319
- // -------------------------
320
- // IMMEDIATE NOTIFICATION
321
- // -------------------------
322
- fireNow(item) {
323
- return __awaiter(this, void 0, void 0, function* () {
324
- yield LocalNotifications.schedule({
325
- notifications: [
326
- {
327
- id: item.id,
328
- title: item.title,
329
- body: item.body,
330
- schedule: { at: new Date() }
389
+ };
390
+ this.addLog = (log) => {
391
+ let newLogs = [...this.logs, Object.assign(Object.assign({}, log), { date: Date.now(), id: log.id === undefined ? GenerateId('number') : log.id })];
392
+ if (log.repeat) {
393
+ const newReverseLogs = [];
394
+ let count = 0;
395
+ for (let i = newLogs.length - 1; i >= 0; i--) {
396
+ if (newLogs[i].id === log.id && count < log.repeat) {
397
+ newReverseLogs.push(newLogs[i]);
398
+ count++;
331
399
  }
332
- ]
333
- });
334
- yield this.db.update(item.id, {
335
- status: 'done'
336
- });
337
- });
338
- }
339
- // -------------------------
340
- // RESYNC AFTER RESTART
341
- // -------------------------
342
- resync() {
343
- return __awaiter(this, void 0, void 0, function* () {
344
- const all = yield this.db.getAll();
345
- const pending = all.filter(i => i.status !== 'done');
346
- for (const item of pending) {
347
- yield this.schedule(item);
400
+ else {
401
+ newReverseLogs.push(this.logs[i]);
402
+ }
403
+ }
404
+ newLogs = newReverseLogs.reverse();
348
405
  }
349
- });
350
- }
351
- // -------------------------
352
- // CANCEL
353
- // -------------------------
354
- cancel(id) {
355
- return __awaiter(this, void 0, void 0, function* () {
356
- yield LocalNotifications.cancel({
357
- notifications: [{ id }]
358
- });
359
- yield this.db.update(id, {
360
- status: 'done'
406
+ newLogs = this.removeExpiredLogs(newLogs);
407
+ this.logs = newLogs;
408
+ return newLogs;
409
+ };
410
+ this.remove = (p) => {
411
+ let newLogs = this.logs;
412
+ newLogs = newLogs.filter((o) => {
413
+ if (p.id !== undefined && o.id !== p.id) {
414
+ return false;
415
+ }
416
+ if (p.tags && p.tags.length) {
417
+ const dic = this.getTagsDic(p.tags);
418
+ return this.isTagsMatch(dic, o);
419
+ }
420
+ return true;
361
421
  });
362
- });
363
- }
364
- // -------------------------
365
- // LIST (DEBUG)
366
- // -------------------------
367
- list() {
368
- return __awaiter(this, void 0, void 0, function* () {
369
- return yield LocalNotifications.getPending();
370
- });
422
+ newLogs = this.removeExpiredLogs(newLogs);
423
+ this.logs = newLogs;
424
+ return newLogs;
425
+ };
426
+ this.getTagsDic = (tags) => {
427
+ const dic = {};
428
+ for (let i = 0; i < tags.length; i++) {
429
+ dic[tags[i]] = true;
430
+ }
431
+ return dic;
432
+ };
433
+ this.isTagsMatch = (tagsDic, log) => {
434
+ if (!log.tags || !log.tags.length) {
435
+ return false;
436
+ }
437
+ for (let i = 0; i < log.tags.length; i++) {
438
+ if (!tagsDic[log.tags[i]]) {
439
+ return false;
440
+ }
441
+ }
442
+ return true;
443
+ };
444
+ this.getLogs = (filter) => {
445
+ if (!filter) {
446
+ return this.logs;
447
+ }
448
+ let res = this.logs;
449
+ if (filter.tags) {
450
+ const dic = this.getTagsDic(filter.tags);
451
+ res = res.filter((o) => this.isTagsMatch(dic, o));
452
+ }
453
+ if (filter.status) {
454
+ res = res.filter((o) => o.status === filter.status);
455
+ }
456
+ return res;
457
+ };
458
+ this.load = p.load;
459
+ this.save = p.save;
371
460
  }
372
461
  }
373
- // const notifications = new NotificationService(db);
374
- // await notifications.init();
375
- // await notifications.notifyAt(
376
- // Date.now() + 10000,
377
- // "Hello",
378
- // "This is persistent notification"
379
- // );
380
462
  export class Tracker {
381
463
  constructor(p) {
382
464
  this.watchId = null;
@@ -423,3 +505,241 @@ export class Tracker {
423
505
  return !!this.watchId;
424
506
  }
425
507
  }
508
+ export class NotificationService {
509
+ constructor(actionCallBack) {
510
+ this.notificationFile = 'notifications.json';
511
+ this.init = (actionCallBack) => __awaiter(this, void 0, void 0, function* () {
512
+ yield LocalNotifications.requestPermissions();
513
+ yield LocalNotifications.addListener('localNotificationReceived', (notification) => __awaiter(this, void 0, void 0, function* () { yield this.handleReceived(notification.id); }));
514
+ yield LocalNotifications.addListener('localNotificationActionPerformed', (event) => __awaiter(this, void 0, void 0, function* () {
515
+ var _a;
516
+ const actions = (_a = event.notification.extra) === null || _a === void 0 ? void 0 : _a.actions;
517
+ const action = actions === null || actions === void 0 ? void 0 : actions.find((action) => action === event.actionId);
518
+ if (!action || !actionCallBack)
519
+ return;
520
+ actionCallBack(action);
521
+ }));
522
+ yield this.resync();
523
+ });
524
+ this.handleReceived = (id) => __awaiter(this, void 0, void 0, function* () {
525
+ const items = yield this.getList();
526
+ const item = items.find(item => item.id === id);
527
+ if (!item)
528
+ return;
529
+ item.showInExpired = false;
530
+ if (item.keepUntil === undefined) {
531
+ yield this.save(items.filter(item => item.id !== id));
532
+ return;
533
+ }
534
+ yield this.save(items);
535
+ });
536
+ this.getChannelId = (item) => {
537
+ var _a, _b;
538
+ return [
539
+ (_a = item.importance) !== null && _a !== void 0 ? _a : 'default',
540
+ (_b = item.sound) !== null && _b !== void 0 ? _b : 'none',
541
+ item.vibration ? 'vibration' : 'no-vibration'
542
+ ].join('-');
543
+ };
544
+ this.registerChannel = (channel) => __awaiter(this, void 0, void 0, function* () {
545
+ yield LocalNotifications.createChannel({
546
+ id: channel.id,
547
+ name: channel.name,
548
+ description: channel.description,
549
+ importance: this.getImportance(channel.importance),
550
+ sound: channel.sound,
551
+ vibration: channel.vibration
552
+ });
553
+ });
554
+ this.register = (_item) => __awaiter(this, void 0, void 0, function* () {
555
+ const items = yield this.getList();
556
+ const id = items.length ? Math.max(...items.map(item => item.id)) + 1 : 1;
557
+ const item = Object.assign(Object.assign({}, _item), { id });
558
+ items.push(item);
559
+ yield this.save(items);
560
+ if (item.fireAt <= Date.now()) {
561
+ if (item.showInExpired) {
562
+ yield this.schedule(item, true);
563
+ item.showInExpired = false;
564
+ yield this.save(items);
565
+ }
566
+ return id;
567
+ }
568
+ yield this.schedule(item);
569
+ return id;
570
+ });
571
+ this.cancel = (p) => __awaiter(this, void 0, void 0, function* () {
572
+ if (p.ids !== undefined) {
573
+ yield this.cancelByIds(p.ids);
574
+ }
575
+ if (p.tags !== undefined) {
576
+ yield this.cancelByTags(p.tags);
577
+ }
578
+ });
579
+ this.cancelByIds = (ids) => __awaiter(this, void 0, void 0, function* () {
580
+ for (const id of ids) {
581
+ yield this.cancelById(id);
582
+ }
583
+ });
584
+ this.cancelById = (id) => __awaiter(this, void 0, void 0, function* () {
585
+ yield LocalNotifications.cancel({ notifications: [{ id }] });
586
+ const items = yield this.getList();
587
+ const newItems = items.filter(item => item.id !== id);
588
+ if (newItems.length !== items.length) {
589
+ yield this.save(newItems);
590
+ }
591
+ });
592
+ this.cancelByTag = (tag) => __awaiter(this, void 0, void 0, function* () {
593
+ const items = yield this.getList();
594
+ const tagItems = items.filter(item => { var _a; return (_a = item.tags) === null || _a === void 0 ? void 0 : _a.includes(tag); });
595
+ for (const item of tagItems) {
596
+ yield this.cancelById(item.id);
597
+ }
598
+ });
599
+ this.cancelByTags = (tags) => __awaiter(this, void 0, void 0, function* () {
600
+ for (const tag of tags) {
601
+ yield this.cancelByTag(tag);
602
+ }
603
+ });
604
+ this.resync = () => __awaiter(this, void 0, void 0, function* () {
605
+ const items = yield this.getList();
606
+ const now = Date.now();
607
+ const pending = yield LocalNotifications.getPending();
608
+ const pendingIds = new Set(pending.notifications.map(notification => notification.id));
609
+ const validItems = [];
610
+ for (const item of items) {
611
+ if (item.keepUntil !== undefined && item.keepUntil <= now) {
612
+ yield LocalNotifications.cancel({ notifications: [{ id: item.id }] });
613
+ continue;
614
+ }
615
+ if (item.fireAt <= now) {
616
+ if (pendingIds.has(item.id)) {
617
+ validItems.push(item);
618
+ continue;
619
+ }
620
+ if (item.showInExpired) {
621
+ yield this.schedule(item, true);
622
+ item.showInExpired = false;
623
+ }
624
+ if (item.keepUntil !== undefined) {
625
+ validItems.push(item);
626
+ }
627
+ continue;
628
+ }
629
+ validItems.push(item);
630
+ if (!pendingIds.has(item.id)) {
631
+ yield this.schedule(item);
632
+ }
633
+ }
634
+ yield this.save(validItems);
635
+ });
636
+ this.schedule = (item, atNow) => __awaiter(this, void 0, void 0, function* () {
637
+ yield this.registerActionType(item);
638
+ const channelId = this.getChannelId(item);
639
+ yield this.registerChannel({ id: channelId, name: channelId, importance: item.importance, sound: item.sound, vibration: item.vibration });
640
+ yield LocalNotifications.schedule({
641
+ notifications: [{
642
+ id: item.id, title: item.title, body: item.body, channelId,
643
+ actionTypeId: this.getActionTypeId(item),
644
+ extra: { actions: item.actions },
645
+ schedule: !atNow ? { at: new Date(item.fireAt) } : undefined
646
+ }]
647
+ });
648
+ });
649
+ this.registerActionType = (item) => __awaiter(this, void 0, void 0, function* () {
650
+ var _b;
651
+ if (!((_b = item.actions) === null || _b === void 0 ? void 0 : _b.length))
652
+ return;
653
+ yield LocalNotifications.registerActionTypes({
654
+ types: [{ id: this.getActionTypeId(item), actions: item.actions.map(action => ({ id: action, title: action })) }]
655
+ });
656
+ });
657
+ this.getActionTypeId = (item) => `notification-${item.id}`;
658
+ this.getImportance = (importance) => {
659
+ switch (importance) {
660
+ case 'low': return 2;
661
+ case 'high': return 4;
662
+ default: return 3;
663
+ }
664
+ };
665
+ this.tagsMatch = (tagsDic, itemTags) => {
666
+ if (!itemTags || !itemTags.length) {
667
+ return false;
668
+ }
669
+ return itemTags.filter((itemTag) => {
670
+ if (!tagsDic[itemTag]) {
671
+ return false;
672
+ }
673
+ });
674
+ return true;
675
+ };
676
+ this.getTagsDic = (tags) => {
677
+ if (!tags) {
678
+ return {};
679
+ }
680
+ const res = {};
681
+ for (let i = 0; i < tags.length; i++) {
682
+ res[tags[i]] = true;
683
+ }
684
+ return res;
685
+ };
686
+ this.getList = (filter) => __awaiter(this, void 0, void 0, function* () {
687
+ try {
688
+ const result = yield Filesystem.readFile({ path: this.notificationFile, directory: Directory.Data, encoding: Encoding.UTF8 });
689
+ const res = JSON.parse(result.data);
690
+ if (!filter) {
691
+ return res;
692
+ }
693
+ else {
694
+ const tagsDic = this.getTagsDic(filter.tags);
695
+ const now = Date.now();
696
+ return res.filter((o) => {
697
+ if (filter.fired !== undefined) {
698
+ const fired = o.fireAt < now;
699
+ if (filter.fired && !fired) {
700
+ return false;
701
+ }
702
+ if (!filter.fired && fired) {
703
+ return false;
704
+ }
705
+ }
706
+ if (filter.tags && filter.tags.length) {
707
+ return this.tagsMatch(tagsDic, filter.tags);
708
+ }
709
+ });
710
+ }
711
+ }
712
+ catch (_c) {
713
+ return [];
714
+ }
715
+ });
716
+ this.save = (items) => __awaiter(this, void 0, void 0, function* () {
717
+ yield Filesystem.writeFile({ path: this.notificationFile, directory: Directory.Data, data: JSON.stringify(items), encoding: Encoding.UTF8 });
718
+ });
719
+ this.init(actionCallBack);
720
+ }
721
+ }
722
+ class AppStorage {
723
+ constructor(props) {
724
+ this.cap = new AIOCapacitor();
725
+ this.save = (data) => __awaiter(this, void 0, void 0, function* () {
726
+ try {
727
+ yield this.cap.writeFile(JSON.stringify(data), this.fileName, { location: this.location, utf8: true });
728
+ }
729
+ catch (err) {
730
+ alert(`AppStorage save error: ${err.message}`);
731
+ }
732
+ });
733
+ this.load = (def) => __awaiter(this, void 0, void 0, function* () {
734
+ try {
735
+ const data = yield this.cap.readFile(this.fileName, { location: this.location, utf8: true });
736
+ }
737
+ catch (err) {
738
+ console.error('storageLoad error:', err);
739
+ return def;
740
+ }
741
+ });
742
+ this.fileName = props.fileName;
743
+ this.location = props.location;
744
+ }
745
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aio-capacitor",
3
- "version": "2.2.0",
3
+ "version": "2.2.3",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -8,7 +8,19 @@
8
8
  "test": "echo \"Error: no test specified\" && exit 1"
9
9
  },
10
10
  "dependencies": {
11
- "aio-capacitor-deps": "latest",
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",
12
24
  "aio-class":"latest"
13
25
  },
14
26
  "repository": {