sagor-fca 0.0.10 → 0.0.11

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.
@@ -3,7 +3,7 @@ const fs = require("fs");
3
3
  const path = require("path");
4
4
  const { exec } = require("child_process");
5
5
  const https = require("https");
6
- const pkgName = "sagor-nx-fca";
6
+ const pkgName = "@dongdev/fca-unofficial";
7
7
 
8
8
  let axios = null;
9
9
  try {
package/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- declare module 'sagor-nx-fca' {
1
+ declare module '@dongdev/fca-unofficial' {
2
2
  import type EventEmitter from "events";
3
3
  import type { Duplex, Readable, Transform } from "stream";
4
4
 
@@ -989,7 +989,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
989
989
  }
990
990
  }
991
991
  if (html.includes("/checkpoint/block/?next")) {
992
- logger("Appstate die, vui lòng thay cái mới!", "error");
992
+ logger("App state is dead, please replace it with a new one!", "error");
993
993
  throw new Error("Checkpoint");
994
994
  }
995
995
 
@@ -1087,7 +1087,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1087
1087
  }
1088
1088
  }
1089
1089
  } else if (userID) {
1090
- logger(`ID người dùng: ${userID}`, "info");
1090
+ logger(`User ID: ${userID}`, "info");
1091
1091
  }
1092
1092
  } catch (userDataErr) {
1093
1093
  // If error is from our validation, rethrow it
@@ -1120,7 +1120,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1120
1120
  logger(`Database connection failed: ${errorMsg}`, "warn");
1121
1121
  }
1122
1122
  });
1123
- logger("FCA FIXED BY SAGOR 🍒", "info");
1123
+ logger("fca fix/update by SaGor", "info");
1124
1124
  const emitter = new EventEmitter();
1125
1125
  const ctxMain = {
1126
1126
  userID,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "sagor-fca",
3
- "version": "0.0.10",
4
- "description": "Unofficial Facebook Chat API for Node.js - Interact with Facebook Messenger programmatically",
3
+ "version": "0.0.11",
4
+ "description": "Unofficial Facebook Chat API for Node.js with Auto-Update System - modify by SaGor ☄️",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
7
7
  "exports": {
@@ -11,13 +11,24 @@
11
11
  "types": "./index.d.ts"
12
12
  }
13
13
  },
14
+ "files": [
15
+ "index.js",
16
+ "index.d.ts",
17
+ "module/",
18
+ "func/",
19
+ "src/",
20
+ "DOCS.md",
21
+ "README.md",
22
+ "LICENSE",
23
+ "CHANGELOG.md"
24
+ ],
14
25
  "scripts": {
15
26
  "test": "mocha",
16
27
  "lint": "eslint ."
17
28
  },
18
29
  "repository": {
19
30
  "type": "git",
20
- "url": "git+https://github.com/SAGOR-KINGx/fca-unofficial.git"
31
+ "url": "git+https://github.com/SAGOR-KINGx/sagor-fca.git"
21
32
  },
22
33
  "keywords": [
23
34
  "facebook",
@@ -32,7 +43,7 @@
32
43
  "facebook-messenger",
33
44
  "chatbot",
34
45
  "nodejs",
35
- "fca"
46
+ "sagor-fca"
36
47
  ],
37
48
  "author": {
38
49
  "name": "SaGor",
@@ -46,9 +57,9 @@
46
57
  ],
47
58
  "license": "MIT",
48
59
  "bugs": {
49
- "url": "https://github.com/SAGOR-KINGx/fca-unofficial/issues"
60
+ "url": "https://github.com/SAGOR-KINGx/sagor-fca/issues"
50
61
  },
51
- "homepage": "https://github.com/SAGOR-KINGx/fca-unofficial#readme",
62
+ "homepage": "https://github.com/SAGOR-KINGx/sagor-fca#readme",
52
63
  "engines": {
53
64
  "node": ">=12.0.0"
54
65
  },
@@ -6,7 +6,7 @@ let sequelize = null;
6
6
  let models = {};
7
7
 
8
8
  try {
9
- const databasePath = path.join(process.cwd(), "Sagor_Database");
9
+ const databasePath = path.join(process.cwd(), "SAGOR_DATA");
10
10
  if (!fs.existsSync(databasePath)) {
11
11
  fs.mkdirSync(databasePath, { recursive: true });
12
12
  }
package/.gitattributes DELETED
@@ -1,2 +0,0 @@
1
- # Auto detect text files and perform LF normalization
2
- * text=auto
@@ -1,22 +0,0 @@
1
- name: "publish npm by SaGor"
2
-
3
- on: push
4
-
5
- jobs:
6
- publish:
7
- runs-on: ubuntu-latest
8
- steps:
9
- - name: Checkout
10
- uses: actions/checkout@v2
11
-
12
- - name: Setup Node.js
13
- uses: actions/setup-node@v2
14
- with:
15
- node-version: 16
16
- registry-url: https://registry.npmjs.org
17
-
18
- - name: Publish to NPM
19
- run: npm publish --access public
20
- env:
21
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
22
-
package/LICENSE-MIT DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Phạm Minh Đồng (DongDev)
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
package/README.md DELETED
@@ -1,524 +0,0 @@
1
- <div align="center">
2
-
3
- # sagor-nx-fca
4
-
5
- **Unofficial Facebook Chat API for Node.js** - Interact with Facebook Messenger programmatically
6
-
7
- [Features](#-features) • [Installation](#-installation) • [Quick Start](#-quick-start) • [Documentation](#-documentation) • [Support](#-author--support)
8
-
9
- </div>
10
-
11
- ---
12
-
13
- ## 📋 Table of Contents
14
-
15
- - [⚠️ Disclaimer & Support Policy](#️-disclaimer--support-policy)
16
- - [⚡ Why this fork?](#-why-this-fork)
17
- - [✨ Features](#-features)
18
- - [🔍 Introduction](#-introduction)
19
- - [📦 Installation](#-installation)
20
- - [🚀 Quick Start](#-quick-start)
21
- - [📝 Message Types](#-message-types)
22
- - [💾 AppState Management](#-appstate-management)
23
- - [🔄 Auto Login](#-auto-login)
24
- - [👂 Listening for Messages](#-listening-for-messages)
25
- - [🎯 API Quick Reference](#-api-quick-reference)
26
- - [📚 Documentation](#-documentation)
27
- - [🛠️ Projects Using This API](#️-projects-using-this-api)
28
- - [🤝 Contributing](#-contributing)
29
- - [📄 License](#-license)
30
- - [👨‍💻 Author & Support](#-author--support)
31
-
32
- ---
33
-
34
- ## ⚠️ Disclaimer & Support Policy
35
-
36
- <div align="center">
37
-
38
- **READ THIS BEFORE USING OR OPENING AN ISSUE.**
39
-
40
- </div>
41
-
42
- This repository is provided **"AS IS"** and is entirely open-source. By using this project, you explicitly agree to the following terms:
43
-
44
- 1. **Use at your own risk:** We are NOT responsible if your account gets banned for spammy activities (sending messages too fast, unsolicited mass messaging, suspicious URLs, or rapid login/logout).
45
- 2. **No Spoon-Feeding:** This is a tool for developers. If you cannot read source code, navigate directories, or use basic search tools (`Ctrl + Shift + F`), you should not be using this library.
46
- 3. **No Free Programming Lessons:** I maintain the core updates and security patches for the community for free. I do **not** provide free JavaScript/TypeScript tutorials, nor will I tell you exactly which line of code to edit for your specific bot.
47
- 4. **Custom Features = Paid Service:** Brainpower and time are not free. If you need me to write custom logic, reverse-engineer specific endpoints, or provide 1-on-1 support for your personal project, **that is a paid service**.
48
-
49
- If you don't like this policy, feel free to fork the repository and maintain it yourself.
50
-
51
- **Recommendations to avoid bans:**
52
-
53
- - Use **Firefox** or the [fca.dongdev.id.vn](https://fca.dongdev.id.vn) flow to reduce logout issues (especially on iOS).
54
- - Prefer **AppState** over email/password when possible.
55
- - Use strict **rate limiting** in your bots.
56
-
57
- ---
58
-
59
- ## ⚡ Why this fork?
60
-
61
- Unlike other outdated forks, `@sagor/fca-unofficial` is built with a focus on **real-world practicality and performance**:
62
-
63
- - **Performance First:** Stripped out legacy, redundant code that causes technical debt.
64
- - **Modernized Architecture:** Adapted to the latest Facebook backend structure.
65
- - **Clean Logic:** No messy wrappers. The codebase is straightforward and easy to navigate if you actually open the files.
66
-
67
- ---
68
-
69
- ## ✨ Features
70
-
71
- - ✅ **Full Messenger API** - Send messages, files, stickers, and more
72
- - ✅ **Real-time Events** - Listen to messages, reactions, and thread events
73
- - ✅ **User Account Support** - Works with personal Facebook accounts (not just Pages)
74
- - ✅ **AppState Support** - Save login state to avoid re-authentication
75
- - ✅ **MQTT Protocol** - Real-time messaging via MQTT
76
- - ✅ **TypeScript Support** - Includes TypeScript definitions
77
- - ✅ **Active Development** - Regularly updated and maintained
78
-
79
- ---
80
-
81
- ## 🔍 Introduction
82
-
83
- Facebook provides an [official API for chat bots](https://developers.facebook.com/docs/messenger-platform), but it's **only available for Facebook Pages**.
84
-
85
- `@sagor/fca-unofficial` is the API that allows you to automate chat functionalities on a **user account** by emulating the browser. This means:
86
-
87
- - 🔄 Making the exact same GET/POST requests as a browser
88
- - 🔐 Does not work with auth tokens
89
- - 📝 Requires Facebook account credentials (email/password) or AppState
90
-
91
- **Perfect for:**
92
-
93
- - 🤖 Building chatbots
94
- - 📱 Automating message responses
95
- - 🔔 Creating notification systems
96
- - 🎮 Building interactive games
97
- - 📊 Analytics and monitoring
98
-
99
- ---
100
-
101
- ## 📦 Installation
102
-
103
- ```bash
104
- npm install @sagor/fca-unofficial@latest
105
- ```
106
-
107
- **Requirements:**
108
-
109
- - Node.js >= 12.0.0
110
- - Active Facebook account
111
-
112
- ---
113
-
114
- ## 🚀 Quick Start
115
-
116
- ### 1️⃣ Login and Simple Echo Bot
117
-
118
- ```javascript
119
- const login = require("@sagor/fca-unofficial");
120
-
121
- login({ appState: [] }, (err, api) => {
122
- if (err) return console.error(err);
123
-
124
- api.listenMqtt((err, event) => {
125
- if (err) return console.error(err);
126
-
127
- // Echo back the received message
128
- if (event.type === "message") {
129
- api.sendMessage(event.body, event.threadID);
130
- }
131
- });
132
- });
133
- ```
134
-
135
- ### 2️⃣ Send Text Message
136
-
137
- ```javascript
138
- const login = require("@sagor/fca-unofficial");
139
-
140
- login({ appState: [] }, (err, api) => {
141
- if (err) {
142
- console.error("Login Error:", err);
143
- return;
144
- }
145
-
146
- const yourID = "000000000000000"; // Replace with actual Facebook ID
147
- const msg = "Hey! 👋";
148
-
149
- api.sendMessage(msg, yourID, (err) => {
150
- if (err) console.error("Message Sending Error:", err);
151
- else console.log("✅ Message sent successfully!");
152
- });
153
- });
154
- ```
155
-
156
- > **💡 Tip:** To find your Facebook ID, look inside the cookies under the name `c_user`
157
-
158
- ### 3️⃣ Send File/Image
159
-
160
- ```javascript
161
- const login = require("@sagor/fca-unofficial");
162
- const fs = require("fs");
163
-
164
- login({ appState: [] }, (err, api) => {
165
- if (err) {
166
- console.error("Login Error:", err);
167
- return;
168
- }
169
-
170
- const yourID = "000000000000000";
171
- const imagePath = __dirname + "/image.jpg";
172
-
173
- // Check if file exists
174
- if (!fs.existsSync(imagePath)) {
175
- console.error("❌ Error: Image file not found!");
176
- return;
177
- }
178
-
179
- const msg = {
180
- body: "Check out this image! 📷",
181
- attachment: fs.createReadStream(imagePath),
182
- };
183
-
184
- api.sendMessage(msg, yourID, (err) => {
185
- if (err) console.error("Message Sending Error:", err);
186
- else console.log("✅ Image sent successfully!");
187
- });
188
- });
189
- ```
190
-
191
- ---
192
-
193
- ## 📝 Message Types
194
-
195
- | Type | Usage | Example |
196
- | ---------------- | ------------------------------------------- | -------------------------------------------------- |
197
- | **Regular text** | `{ body: "message text" }` | `{ body: "Hello!" }` |
198
- | **Sticker** | `{ sticker: "sticker_id" }` | `{ sticker: "369239263222822" }` |
199
- | **File/Image** | `{ attachment: fs.createReadStream(path) }` | `{ attachment: fs.createReadStream("image.jpg") }` |
200
- | **URL** | `{ url: "https://example.com" }` | `{ url: "https://github.com" }` |
201
- | **Large emoji** | `{ emoji: "👍", emojiSize: "large" }` | `{ emoji: "👍", emojiSize: "large" }` |
202
-
203
- > **📌 Note:** A message can only be a regular message (which can be empty) and optionally **one of the following**: a sticker, an attachment, or a URL.
204
-
205
- **Emoji sizes:** `small` | `medium` | `large`
206
-
207
- ---
208
-
209
- ## 💾 AppState Management
210
-
211
- ### Save AppState
212
-
213
- Save your login session to avoid re-authentication:
214
-
215
- ```javascript
216
- const fs = require("fs");
217
- const login = require("@sagor/fca-unofficial");
218
-
219
- const credentials = { email: "YOUR_EMAIL", password: "YOUR_PASSWORD" }; // Or use existing appState
220
-
221
- login(credentials, (err, api) => {
222
- if (err) {
223
- console.error("Login Error:", err);
224
- return;
225
- }
226
-
227
- try {
228
- const appState = JSON.stringify(api.getAppState(), null, 2);
229
- fs.writeFileSync("appstate.json", appState);
230
- console.log("✅ AppState saved successfully!");
231
- } catch (error) {
232
- console.error("❌ Error saving AppState:", error);
233
- }
234
- });
235
- ```
236
-
237
- ### Use Saved AppState
238
-
239
- Load your saved AppState for faster login:
240
-
241
- ```javascript
242
- const fs = require("fs");
243
- const login = require("@sagor/fca-unofficial");
244
-
245
- login(
246
- { appState: JSON.parse(fs.readFileSync("appstate.json", "utf8")) },
247
- (err, api) => {
248
- if (err) {
249
- console.error("Login Error:", err);
250
- return;
251
- }
252
-
253
- console.log("✅ Logged in successfully!");
254
- // Your code here
255
- },
256
- );
257
- ```
258
-
259
- ---
260
-
261
- ## 🔄 Auto Login
262
-
263
- When your session (AppState) expires, the library can **automatically re-login** using credentials from a config file, so your bot can keep running without manual intervention.
264
-
265
- 1. Create **`fca-config.json`** in your project root (same folder as where you run `node`):
266
-
267
- ```json
268
- {
269
- "autoLogin": true,
270
- "apiServer": "https://minhdong.site",
271
- "apiKey": "",
272
- "credentials": {
273
- "email": "YOUR_EMAIL_OR_PHONE",
274
- "password": "YOUR_PASSWORD",
275
- "twofactor": ""
276
- }
277
- }
278
- ```
279
-
280
- 2. **Log in with AppState** as usual. If the session later expires (e.g. Facebook invalidates cookies), the library will use `credentials` (and optionally the external `apiServer`) to log in again and retry the request.
281
-
282
- - Set **`autoLogin`** to `false` to disable automatic re-login.
283
- - **`twofactor`**: Base32 secret for 2FA (not the 6-digit code). Leave empty if you do not use 2FA.
284
- - **`apiServer`** / **`apiKey`**: Optional; used for external iOS-style login. Default server is `https://minhdong.site`.
285
-
286
- Keep **`fca-config.json`** out of version control (add it to `.gitignore`) since it contains credentials.
287
-
288
- ---
289
-
290
- ## 🔐 Security, Trust & Supply Chain
291
-
292
- - Published via **GitHub Actions** using `npm publish --provenance`, so the tarball on npm can be cryptographically tied back to this repo.
293
- - Core runtime code in `module/` and `src/` is **readable JavaScript** with no obfuscated logic.
294
- - Legacy forks (such as Horizon) are kept only for reference and are **not** shipped in the npm package.
295
- - No telemetry or hidden network calls:
296
- - All HTTP traffic is implemented in `src/utils/request.js` and `module/loginHelper.js`.
297
- - External URLs (such as `apiServer` or proxies) are fully user‑configurable.
298
- - The npm publish account uses **2FA** and dedicated automation tokens.
299
-
300
- See `SECURITY.md` for more details.
301
-
302
- ---
303
-
304
- ## 👂 Listening for Messages
305
-
306
- ### Echo Bot with Stop Command
307
-
308
- ```javascript
309
- const fs = require("fs");
310
- const login = require("@sagor/fca-unofficial");
311
-
312
- login(
313
- { appState: JSON.parse(fs.readFileSync("appstate.json", "utf8")) },
314
- (err, api) => {
315
- if (err) return console.error("Login Error:", err);
316
-
317
- // Enable listening to events (join/leave, title change, etc.)
318
- api.setOptions({ listenEvents: true });
319
-
320
- const stopListening = api.listenMqtt((err, event) => {
321
- if (err) return console.error("Listen Error:", err);
322
-
323
- // Mark as read
324
- api.markAsRead(event.threadID, (err) => {
325
- if (err) console.error("Mark as read error:", err);
326
- });
327
-
328
- // Handle different event types
329
- switch (event.type) {
330
- case "message":
331
- if (event.body && event.body.trim().toLowerCase() === "/stop") {
332
- api.sendMessage("Goodbye… 👋", event.threadID);
333
- stopListening();
334
- return;
335
- }
336
- api.sendMessage(`🤖 BOT: ${event.body}`, event.threadID);
337
- break;
338
-
339
- case "event":
340
- console.log("📢 Event Received:", event);
341
- break;
342
- }
343
- });
344
- },
345
- );
346
- ```
347
-
348
- ### Listen Options
349
-
350
- Configure listening behavior:
351
-
352
- ```javascript
353
- api.setOptions({
354
- listenEvents: true, // Receive events (join/leave, rename, etc.)
355
- selfListen: true, // Receive messages from yourself
356
- logLevel: "silent", // Disable logs (silent/error/warn/info/verbose)
357
- });
358
- ```
359
-
360
- ---
361
-
362
- ## 🎯 API Quick Reference
363
-
364
- _(For full details, please read the source code or `DOCS.md`)_
365
-
366
- ### 📨 Messaging
367
-
368
- `sendMessage`, `sendTypingIndicator`, `getMessage`, `editMessage`, `deleteMessage`, `unsendMessage`, `setMessageReaction`, `forwardAttachment`, `uploadAttachment`, `createPoll`
369
-
370
- ### 📬 Read Receipt & Delivery
371
-
372
- `markAsRead`, `markAsReadAll`, `markAsDelivered`, `markAsSeen`
373
-
374
- ### 👥 Thread Management
375
-
376
- `getThreadInfo`, `getThreadList`, `getThreadHistory`, `deleteThread`, `changeThreadColor`, `changeThreadEmoji`, `changeGroupImage`, `setTitle`, `changeNickname`
377
-
378
- ### 👤 User & Group Management
379
-
380
- `getUserInfo`, `getFriendsList`, `getCurrentUserID`, `createNewGroup`, `addUserToGroup`, `removeUserFromGroup`, `changeAdminStatus`
381
-
382
- ### ⚙️ Thread Settings & Actions
383
-
384
- `muteThread`, `changeArchivedStatus`, `changeBlockedStatus`, `handleMessageRequest`, `changeAvatar`, `changeBio`, `handleFriendRequest`, `unfriend`
385
-
386
- ### 🔐 Auth & Listening
387
-
388
- `logout`, `getAppState`, `setOptions`, `listenMqtt`
389
-
390
- ---
391
- ## 🎛 Event Hooks & Remote Control (Advanced)
392
-
393
- Starting from `3.x`, the API instance also behaves like an **EventEmitter** for lifecycle and remote‑control events:
394
-
395
- - **Lifecycle events**:
396
- - `sessionExpired` — login session is no longer valid, auto‑login will be attempted (if configured).
397
- - `autoLoginSuccess` — auto‑login succeeded and the failed request will be retried.
398
- - `autoLoginFailed` — auto‑login could not recover the session.
399
- - `checkpoint` — generic checkpoint, with subtype in `{ type: "282" | "956" | "scraping_warning" }`.
400
- - `checkpoint_282`, `checkpoint_956` — more specific checkpoint events.
401
- - `loginBlocked` — Facebook actively blocked the login (error `1357001`).
402
- - `rateLimit` — HTTP 429 detected on Facebook endpoints.
403
- - `networkError` — network‑level failure (timeouts, DNS, connection reset, etc.).
404
-
405
- Usage:
406
-
407
- ```javascript
408
- api.on("checkpoint_956", ({ res }) => {
409
- console.error("Checkpoint 956 detected, manual action required.");
410
- });
411
-
412
- api.on("rateLimit", ({ url, method }) => {
413
- console.warn("Rate limit hit on", method, url);
414
- });
415
- ```
416
-
417
- - **Remote control events** (when `remoteControl.enabled` is `true` in `fca-config.json`):
418
- - `remoteConnected` / `remoteDisconnected`
419
- - `remoteStop`
420
- - `remoteBroadcast`
421
- - `remoteMessage` (raw messages from your WS backend)
422
-
423
- See `examples/remote-control.js` for a concrete integration example.
424
-
425
- ---
426
-
427
- ## 🌐 Proxy Configuration & Broadcast Helper
428
-
429
- - **Proxy support**:
430
- - You can pass a proxy per‑login:
431
-
432
- ```javascript
433
- login({ appState }, (err, api) => {
434
- if (err) return console.error(err);
435
- api.setOptions({ proxy: "http://user:pass@host:port" });
436
- });
437
- ```
438
-
439
- - Or define a default in `fca-config.json`:
440
-
441
- ```json
442
- {
443
- "proxy": "http://user:pass@host:port"
444
- }
445
- ```
446
-
447
- - All HTTP calls go through this proxy using `https-proxy-agent`.
448
-
449
- - **Broadcast helper** (optional util):
450
- - Not part of the public API surface on purpose (to avoid encouraging spam).
451
- - You can use it manually:
452
-
453
- ```javascript
454
- const broadcast = require("@sagor/fca-unofficial/src/utils/broadcast");
455
-
456
- const threads = ["1000...", "2000..."];
457
- await broadcast(api, threads, { body: "Hello!" }, {
458
- delayMs: 1200,
459
- skipBlocked: true
460
- });
461
- ```
462
-
463
- ---
464
-
465
- ## 📚 Documentation
466
-
467
- - **[DOCS.md](./DOCS.md)** — Full API reference, examples, and best practices.
468
- - **[docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md)** — Codebase structure and modules (for contributors).
469
- - For implementation details, the `src/` folder is the authoritative reference.
470
-
471
- ---
472
-
473
- ## 🛠️ Projects Using This API
474
-
475
- Here are some awesome projects built with `@sagor/fca-unofficial`:
476
- _(See [GitHub Repository](https://github.com/SAGOR-KINGx/fca-unofficial) for the full list)._
477
-
478
- ---
479
-
480
- ## 🤝 Contributing
481
-
482
- Contributions are welcome! If you want to optimize something or fix a bug:
483
-
484
- 1. 🍴 Fork the repository
485
- 2. 🌿 Create a new branch
486
- 3. 💾 Commit your changes
487
- 4. 📤 Push to the branch
488
- 5. 🔄 Open a Pull Request
489
-
490
- **Rule:** Keep it clean, minimal, and performant. No bloated dependencies.
491
-
492
- ---
493
-
494
- ## 📄 License
495
-
496
- This project is licensed under the **MIT License** - see the [LICENSE-MIT](./LICENSE-MIT) file for details.
497
-
498
- ---
499
-
500
- ## 👨‍💻 Author & Support
501
-
502
- <div align="center">
503
-
504
- **Maintained by SaGor**
505
-
506
- </div>
507
-
508
- ### 🛠️ Need Custom Work?
509
-
510
- If you have the budget and need specialized features, API reverse-engineering, or private bot development, reach out to me directly via Facebook. **Do not contact me for free coding lessons.**
511
-
512
- ### 🔗 Links
513
-
514
- - 📦 [NPM Package](https://www.npmjs.com/package/@sagor/fca-unofficial)
515
- - 🐙 [GitHub Repository](https://github.com/SAGOR- KINGx/fca-unofficial)
516
- - 🐛 [Issue Tracker](https://github.com/SAGOR-KINGx/fca-unofficial/issues)
517
-
518
- ---
519
-
520
- <div align="center">
521
-
522
- Made with ❤️ (and a lot of caffeine) for the developer community.
523
-
524
- </div>
Binary file
@@ -1,142 +0,0 @@
1
- # Architecture Overview
2
-
3
- This document describes the codebase structure of **sagor-nx-fca** for contributors and developers who need to navigate or extend the project.
4
-
5
- ---
6
-
7
- ## Entry point and public API
8
-
9
- - **`index.js`** — Exports the `login` function (CommonJS and ESM interop: `default`, `login`).
10
- - **`index.d.ts`** — TypeScript declarations for `login`, credentials, `IFCAU_API`, event types, and options.
11
-
12
- The only public API is `login(credentials, options?, callback?)`. All other functionality is exposed on the `api` object passed to the login callback.
13
-
14
- ---
15
-
16
- ## Login flow
17
-
18
- | File | Role |
19
- |------|------|
20
- | `module/login.js` | Entry for login: normalizes callback/promise, merges options, optionally runs auto-update, then delegates to `loginHelper`. |
21
- | `module/loginHelper.js` | Core login logic: AppState validation, cookie/session handling, optional external API login (iOS), GraphQL and MQTT setup, builds and returns the `api` object. |
22
- | `module/config.js` | Loads `fca-config.json` (autoUpdate, mqtt, autoLogin, apiServer, apiKey, credentials). |
23
- | `module/options.js` | `setOptions()`: applies boolean and special options (userAgent, proxy) used globally. |
24
-
25
- Options include: `selfListen`, `listenEvents`, `listenTyping`, `updatePresence`, `forceLogin`, `autoMarkRead`, `autoReconnect`, `online`, `emitReady`, `userAgent`, `proxy`.
26
-
27
- ---
28
-
29
- ## HTTP layer
30
-
31
- - **`src/utils/request.js`** — Shared `get`/`post` helpers, cookie jar, proxy support, defaults.
32
- - **`src/api/http/httpGet.js`** — GET requests.
33
- - **`src/api/http/httpPost.js`** — POST (e.g. GraphQL).
34
- - **`src/api/http/postFormData.js`** — Form-data POST (e.g. uploads).
35
- - **`src/utils/headers.js`** — Request headers.
36
- - **`src/utils/cookies.js`** — Cookie handling.
37
- - **`src/utils/client.js`** — Session/client state, `getAppState`, `saveCookies`, `parseAndCheckLogin`.
38
-
39
- ---
40
-
41
- ## API modules (`src/api/`)
42
-
43
- API functions are attached to the `api` object in the login flow. They use the shared context (`ctx`), default funcs (`get`, `post`), and optional callback/promise.
44
-
45
- ### Messaging (`src/api/messaging/`)
46
-
47
- - **sendMessage.js** — Send text, stickers, attachments, URLs, mentions.
48
- - **editMessage.js**, **deleteMessage.js**, **unsendMessage.js** — Edit, delete, unsend.
49
- - **getMessage.js** — Fetch a message by ID.
50
- - **sendTypingIndicator.js** — Typing indicator.
51
- - **setMessageReaction.js** — Message reactions.
52
- - **forwardAttachment.js**, **uploadAttachment.js** — Attachments.
53
- - **markAsRead.js**, **markAsReadAll.js**, **markAsDelivered.js**, **markAsSeen.js** — Read/delivery state.
54
- - **createPoll.js** — Polls.
55
- - **scheduler.js** — Scheduled messages (in-memory).
56
-
57
- ### Threads (`src/api/threads/`)
58
-
59
- - **getThreadInfo.js**, **getThreadList.js**, **getThreadHistory.js**, **getThreadPictures.js** — Thread data and history.
60
-
61
- ### Thread/group actions (in `messaging/`)
62
-
63
- - **getThreadInfo**, **getThreadList**, **getThreadHistory**, **getThreadPictures** (see threads).
64
- - **setTitle.js**, **changeThreadColor.js**, **changeThreadEmoji.js**, **changeGroupImage.js** — Group appearance.
65
- - **createNewGroup.js**, **addUserToGroup.js**, **removeUserFromGroup.js**, **changeAdminStatus.js**, **changeNickname.js** — Members and roles.
66
- - **muteThread.js**, **deleteThread.js**, **changeArchivedStatus.js**, **changeBlockedStatus.js**, **handleMessageRequest.js** — Thread state and moderation.
67
- - **searchForThread.js** — Search conversations.
68
-
69
- ### Users (`src/api/users/`)
70
-
71
- - **getUserInfo.js**, **getUserInfoV2.js** — User profile data.
72
- - **getUserID.js** — Resolve user ID from name/URL.
73
-
74
- ### Action / account (`src/api/action/`)
75
-
76
- - **getCurrentUserID.js**, **logout.js** — Session.
77
- - **changeAvatar.js**, **changeBio.js** — Profile.
78
- - **handleFriendRequest.js**, **unfriend.js** — Friends.
79
- - **enableAutoSaveAppState.js** — Periodic AppState save.
80
- - **refreshFb_dtsg.js** — Token refresh.
81
- - **addExternalModule.js**, **setPostReaction.js** — Extensions and reactions.
82
-
83
- ---
84
-
85
- ## Real-time (MQTT / WebSocket)
86
-
87
- Real-time events (messages, typing, read receipts, etc.) are delivered via MQTT. The listener is started with `api.listenMqtt(callback)` and can be stopped via the returned function.
88
-
89
- | Path | Role |
90
- |------|------|
91
- | `src/api/socket/listenMqtt.js` | Wires MQTT connection, seq ID, middleware, and callback; exposes `stopListening`. |
92
- | `src/api/socket/core/connectMqtt.js` | MQTT connection and message handling. |
93
- | `src/api/socket/core/getSeqID.js` | Fetches sequence ID for MQTT. |
94
- | `src/api/socket/core/parseDelta.js` | Parses MQTT payloads into event objects and optionally updates DB-backed statistics (e.g. thread message counts). |
95
- | `src/api/socket/core/getTaskResponseData.js` | Task response handling. |
96
- | `src/api/socket/core/emitAuth.js` | Emits auth-related errors (e.g. not logged in, blocked). |
97
- | `src/api/socket/detail/buildStream.js` | Builds WebSocket/MQTT stream (with optional proxy). |
98
- | `src/api/socket/detail/constants.js` | MQTT topics and constants. |
99
- | `src/api/socket/middleware/index.js` | Middleware pipeline: events pass through middleware before reaching the user callback. |
100
-
101
- Event types include: `message`, `message_reply`, `event` (thread log events), `typ`, `read`, `read_receipt`, `message_reaction`, `presence`, `message_unsend`.
102
-
103
- ---
104
-
105
- ## Utilities and shared code
106
-
107
- - **`src/utils/format.js`** — Type checking and formatting helpers.
108
- - **`src/utils/constants.js`** — `getFrom`, `isReadableStream`.
109
- - **`src/utils/loginParser.js`** — Login response parsing and auto-login / checkpoint detection (emits lifecycle events via `ctx._emitter`).
110
- - **`src/utils/messageFormat.js`** — Message formatting.
111
- - **`func/logger.js`** — Colored console logger.
112
- - **`func/checkUpdate.js`** — Optional version check / auto-update.
113
-
114
- ---
115
-
116
- ## Database (optional)
117
-
118
- - **`src/database/models/`** — Sequelize models (e.g. `user.js`, `thread.js`).
119
- - **`src/database/models/index.js`** — Model registration.
120
- - **`src/database/threadData.js`**, **userData.js** — Data access using those models (used by anti-get-info features and realtime statistics).
121
-
122
- The core API can operate without a database, but when enabled it:
123
-
124
- - Caches expensive calls such as `getUserInfo`/`getThreadInfo` to reduce Facebook API pressure.
125
- - Tracks per-thread statistics (e.g. `messageCount`, `timestamp`) to support higher-level analytics and dashboards.
126
-
127
- ---
128
-
129
- ## Data flow (simplified)
130
-
131
- 1. **Login** — User calls `login(credentials, options?, callback)`. `loginHelper` validates AppState or performs email/password (or external API) login, then builds session (cookies, `fb_dtsg`, etc.) and the `api` object.
132
- 2. **API calls** — Each `api.*` method uses `defaultFuncs.get`/`post` and shared `ctx` (cookies, options). Most methods support both callback and Promise.
133
- 3. **Real-time** — `api.listenMqtt(callback)` starts MQTT, fetches seq ID, parses deltas, runs middleware, then invokes the callback for each event. `stopListening()` closes the listener.
134
-
135
- ---
136
-
137
- ## Configuration
138
-
139
- - **Runtime options** — Set via `api.setOptions({ ... })` (see `module/options.js`).
140
- - **File config** — Optional `fca-config.json` in the current working directory (see `module/config.js`): `autoUpdate`, `mqtt`, `autoLogin`, `apiServer`, `apiKey`, `credentials`.
141
-
142
- For full API usage and examples, see [DOCS.md](../DOCS.md) and [README.md](../README.md).
@@ -1,85 +0,0 @@
1
- "use strict";
2
-
3
- // Example: Remote control + lifecycle events
4
- // Run this with a proper fca-config.json where:
5
- // {
6
- // "remoteControl": {
7
- // "enabled": true,
8
- // "url": "wss://your-dashboard.example/ws",
9
- // "token": "optional-auth-token"
10
- // }
11
- // }
12
-
13
- const fs = require("fs");
14
- const login = require("sagor-nx-fca");
15
-
16
- function loadAppState() {
17
- try {
18
- return JSON.parse(fs.readFileSync("appstate.json", "utf8"));
19
- } catch {
20
- return null;
21
- }
22
- }
23
-
24
- login({ appState: loadAppState() || [] }, (err, api) => {
25
- if (err) {
26
- console.error("Login error:", err);
27
- return;
28
- }
29
-
30
- console.log("[remote-demo] Logged in as:", api.getCurrentUserID());
31
-
32
- // Lifecycle hooks
33
- api.on("sessionExpired", () => {
34
- console.warn("[remote-demo] Session expired, auto-login will be attempted.");
35
- });
36
-
37
- api.on("autoLoginSuccess", () => {
38
- console.log("[remote-demo] Auto-login succeeded, requests will be retried.");
39
- });
40
-
41
- api.on("autoLoginFailed", (info) => {
42
- console.error("[remote-demo] Auto-login failed:", info && info.error && info.error.message);
43
- });
44
-
45
- api.on("checkpoint", ({ type }) => {
46
- console.error(`[remote-demo] Checkpoint detected (${type}). You should handle this manually.`);
47
- });
48
-
49
- // Remote control events
50
- api.on("remoteConnected", (info) => {
51
- console.log("[remote-demo] Remote controller connected:", info);
52
- });
53
-
54
- api.on("remoteDisconnected", () => {
55
- console.log("[remote-demo] Remote controller disconnected.");
56
- });
57
-
58
- api.on("remoteStop", () => {
59
- console.log("[remote-demo] Remote requested stop. Exiting process.");
60
- process.exit(0);
61
- });
62
-
63
- api.on("remoteBroadcast", async ({ threadIDs, message }) => {
64
- console.log("[remote-demo] Remote broadcast request:", { threadIDs, message });
65
- try {
66
- const broadcast = require("../src/utils/broadcast");
67
- await broadcast(api, threadIDs, message, { delayMs: 1200 });
68
- console.log("[remote-demo] Broadcast done.");
69
- } catch (e) {
70
- console.error("[remote-demo] Broadcast error:", e);
71
- }
72
- });
73
-
74
- // Normal listen loop
75
- api.listenMqtt((err, event) => {
76
- if (err) {
77
- console.error("listenMqtt error:", err);
78
- return;
79
- }
80
- if (event.type === "message" && event.body === "!ping") {
81
- api.sendMessage("pong", event.threadID);
82
- }
83
- });
84
- });
85
-