fb2cal-fork 2.0.1__py3-none-any.whl

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.
fb2cal/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ """
2
+ fb2cal - Facebook birthday exporter
3
+ Original project by Mo Beigi; fork maintained by Alessandro Digilio
4
+ This is a modified version of the original fb2cal project.
5
+ Modifications Copyright (C) 2026 Alessandro Digilio.
6
+
7
+ This program is free software: you can redistribute it and/or modify it under
8
+ the terms of the GNU General Public License as published by the Free Software
9
+ Foundation, either version 3 of the License, or (at your option) any later
10
+ version.
11
+
12
+ This program is distributed in the hope that it will be useful, but WITHOUT
13
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14
+ FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15
+ You should have received a copy of the GNU General Public License along with
16
+ this program. If not, see <http://www.gnu.org/licenses/>.
17
+ """
18
+
19
+ from .__meta__ import *
fb2cal/__main__.py ADDED
@@ -0,0 +1,189 @@
1
+ #!/usr/bin/env python3
2
+ """Command-line entry point for fb2cal."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import logging
9
+ import sys
10
+
11
+ from .errors import (
12
+ AuthenticationError,
13
+ ConfigurationError,
14
+ CookieFileError,
15
+ FacebookError,
16
+ GraphQLQueryError,
17
+ GraphQLSchemaError,
18
+ TokenExtractionError,
19
+ )
20
+ from .facebook_client import FacebookClient
21
+ from .facebook_session import FacebookSession
22
+ from .ics_writer import ICSWriter
23
+ from .json_exporter import JSONExporter
24
+ from .logger import Logger
25
+ from .pipeline import extract_birthdays, summarize_contacts
26
+ from .transformer import Transformer
27
+ from .vcard_exporter import VCardExporter
28
+
29
+
30
+ def build_parser():
31
+ parser = argparse.ArgumentParser(
32
+ prog="fb2cal", description="Export Facebook birthdays"
33
+ )
34
+ subparsers = parser.add_subparsers(dest="command")
35
+ export = subparsers.add_parser("export", help="fetch birthdays and export them")
36
+ _add_auth_args(export)
37
+ export.add_argument("--format", choices=("ics", "json", "vcf"), default="ics")
38
+ export.add_argument(
39
+ "--vcard-version",
40
+ choices=("4.0", "3.0"),
41
+ default="4.0",
42
+ help="vCard version for --format vcf (default: 4.0; use 3.0 for legacy clients)",
43
+ )
44
+ export.add_argument(
45
+ "--output", help="output path; omit to write the selected format to stdout"
46
+ )
47
+ doctor = subparsers.add_parser(
48
+ "doctor", help="validate auth, token, query, and response schema"
49
+ )
50
+ _add_auth_args(doctor)
51
+ doctor.add_argument(
52
+ "--json", action="store_true", help="emit machine-readable diagnostics"
53
+ )
54
+ return parser
55
+
56
+
57
+ def _add_auth_args(parser):
58
+ parser.add_argument(
59
+ "--cookies",
60
+ required=True,
61
+ help="explicit JSON cookie export; browser profiles are never scanned automatically",
62
+ )
63
+ parser.add_argument(
64
+ "--log-level",
65
+ choices=("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"),
66
+ default="INFO",
67
+ help="logging verbosity (default: INFO)",
68
+ )
69
+
70
+
71
+ def _configure_logging(level="INFO"):
72
+ logger = Logger("fb2cal").getLogger()
73
+ try:
74
+ logger.setLevel(getattr(logging, level.upper()))
75
+ except AttributeError as exc:
76
+ raise ConfigurationError(f"Invalid logging level: {level}") from exc
77
+ logging.getLogger().setLevel(logger.level)
78
+ return logger
79
+
80
+
81
+ def _create_client(args):
82
+ _configure_logging(args.log_level)
83
+ if not args.cookies:
84
+ raise ConfigurationError(
85
+ "Provide an explicit browser cookie export with --cookies"
86
+ )
87
+ return FacebookClient(session=FacebookSession.from_cookie_file(args.cookies))
88
+
89
+
90
+ def _export_contacts(contacts, output_format, output_path, vcard_version="4.0"):
91
+ if not contacts:
92
+ raise GraphQLSchemaError("Facebook returned no birthday contacts")
93
+ if output_format == "json":
94
+ writer = JSONExporter(contacts)
95
+ content = writer.export()
96
+ elif output_format == "vcf":
97
+ writer = VCardExporter(contacts, version=vcard_version)
98
+ content = writer.export()
99
+ else:
100
+ writer = ICSWriter(contacts)
101
+ writer.generate()
102
+ content = writer.export()
103
+ if output_path:
104
+ writer.write(output_path)
105
+ else:
106
+ print(content, end="")
107
+
108
+
109
+ def _print_recap(contacts):
110
+ summary = summarize_contacts(contacts)
111
+ print(
112
+ "Extraction summary:\n"
113
+ f" friends with visible birthdays: {summary.contacts}\n"
114
+ f" birthdays with year: {summary.with_year}\n"
115
+ f" birthdays without year: {summary.without_year}\n"
116
+ " total profile friends: unavailable from the birthday query",
117
+ file=sys.stderr,
118
+ )
119
+
120
+
121
+ def run_export(args):
122
+ client = _create_client(args)
123
+ client.validate_session()
124
+ contacts = extract_birthdays(client)
125
+ _export_contacts(contacts, args.format, args.output, args.vcard_version)
126
+ _print_recap(contacts)
127
+ return 0
128
+
129
+
130
+ def run_doctor(args):
131
+ client = _create_client(args)
132
+ validation = client.validate_session()
133
+ response = client.query_graph_ql_birthday_comet_monthly(0)
134
+ Transformer().transform_birthday_comet_monthly_to_birthdays(response)
135
+ result = {
136
+ "session": validation.status,
137
+ "user_id": validation.user_id,
138
+ "fb_dtsg": "present",
139
+ "graphql": "ok",
140
+ "schema": "ok",
141
+ }
142
+ if args.json:
143
+ print(json.dumps(result))
144
+ else:
145
+ print(
146
+ "Session: authenticated\nfb_dtsg: present\nGraphQL query: ok\nBirthday schema: ok"
147
+ )
148
+ return 0
149
+
150
+
151
+ def _exit_code(error):
152
+ if isinstance(error, (ConfigurationError, CookieFileError)):
153
+ return 2
154
+ if isinstance(error, AuthenticationError):
155
+ return 3
156
+ if isinstance(error, TokenExtractionError):
157
+ return 4
158
+ if isinstance(error, GraphQLQueryError):
159
+ return 5
160
+ if isinstance(error, GraphQLSchemaError):
161
+ return 6
162
+ return 1
163
+
164
+
165
+ def main(argv=None):
166
+ argv = list(sys.argv[1:] if argv is None else argv)
167
+ try:
168
+ if not argv:
169
+ build_parser().print_help()
170
+ return 2
171
+ args = build_parser().parse_args(argv)
172
+ if args.command == "export":
173
+ return run_export(args)
174
+ if args.command == "doctor":
175
+ return run_doctor(args)
176
+ build_parser().print_help()
177
+ return 2
178
+ except FacebookError as exc:
179
+ print(f"fb2cal: {exc}", file=sys.stderr)
180
+ return _exit_code(exc)
181
+ except ValueError as exc:
182
+ print(f"fb2cal: invalid configuration: {exc}", file=sys.stderr)
183
+ return 2
184
+ finally:
185
+ logging.shutdown()
186
+
187
+
188
+ if __name__ == "__main__":
189
+ raise SystemExit(main())
fb2cal/__meta__.py ADDED
@@ -0,0 +1,41 @@
1
+ __author__ = "Alessandro Digilio"
2
+ __copyright__ = (
3
+ "Copyright 2019-2020 Mo Beigi; modifications Copyright 2026 Alessandro Digilio"
4
+ )
5
+ __description__ = "Fetch Facebook birthdays and export calendar/contact files"
6
+ __email__ = ""
7
+ __keywords__ = ["facebook", "birthday", "calendar", "export", "ics"]
8
+ __license__ = "GPL-3.0-or-later"
9
+ __maintainer__ = "Alessandro Digilio"
10
+ __status__ = "Production"
11
+ __title__ = "fb2cal"
12
+ __version_info__ = (2, 0, 1)
13
+ __version__ = ".".join(map(str, __version_info__))
14
+
15
+ __github_url__ = "https://github.com/alsd4git/fb2cal"
16
+ __github_short_url__ = __github_url__
17
+ __github_assets_absolute_url__ = (
18
+ "https://raw.githubusercontent.com/alsd4git/fb2cal/main"
19
+ )
20
+ __download_url__ = f"https://github.com/alsd4git/fb2cal/archive/v{__version__}.tar.gz"
21
+ __upstream_url__ = "https://github.com/mobeigi/fb2cal"
22
+
23
+
24
+ # Make metadata public to script
25
+ __all__ = [
26
+ "__author__",
27
+ "__copyright__",
28
+ "__description__",
29
+ "__download_url__",
30
+ "__email__",
31
+ "__github_assets_absolute_url__",
32
+ "__github_short_url__",
33
+ "__github_url__",
34
+ "__license__",
35
+ "__maintainer__",
36
+ "__status__",
37
+ "__title__",
38
+ "__upstream_url__",
39
+ "__version__",
40
+ "__version_info__",
41
+ ]
fb2cal/contact.py ADDED
@@ -0,0 +1,46 @@
1
+ """Facebook-independent birthday contact model."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class BirthdayContact:
11
+ id: str
12
+ name: str
13
+ profile_url: str | None
14
+ picture_url: str | None
15
+ birthday_day: int
16
+ birthday_month: int
17
+ birthday_year: int | None = None
18
+ source: str = "facebook"
19
+
20
+ def __str__(self) -> str:
21
+ year = "????" if self.birthday_year is None else f"{self.birthday_year:04}"
22
+ return f"{self.name} ({self.birthday_day:02}/{self.birthday_month:02}/{year})"
23
+
24
+ def __lt__(self, other: Any) -> bool:
25
+ if not isinstance(other, BirthdayContact):
26
+ return NotImplemented
27
+ return (self.birthday_month, self.birthday_day, self.name, self.id) < (
28
+ other.birthday_month,
29
+ other.birthday_day,
30
+ other.name,
31
+ other.id,
32
+ )
33
+
34
+ def to_dict(self) -> dict[str, Any]:
35
+ return {
36
+ "id": self.id,
37
+ "name": self.name,
38
+ "profile_url": self.profile_url,
39
+ "picture_url": self.picture_url,
40
+ "birthday": {
41
+ "day": self.birthday_day,
42
+ "month": self.birthday_month,
43
+ "year": self.birthday_year,
44
+ },
45
+ "source": self.source,
46
+ }
fb2cal/errors.py ADDED
@@ -0,0 +1,41 @@
1
+ """Typed errors raised by the Facebook extraction pipeline."""
2
+
3
+
4
+ class FacebookError(Exception):
5
+ """Base class for expected, user-facing fb2cal failures."""
6
+
7
+
8
+ class ConfigurationError(FacebookError):
9
+ """The supplied configuration is missing or invalid."""
10
+
11
+
12
+ class CookieFileError(FacebookError):
13
+ """The explicit cookie/session file cannot be loaded safely."""
14
+
15
+
16
+ class AuthenticationError(FacebookError):
17
+ """Facebook rejected the supplied authentication state."""
18
+
19
+
20
+ class SessionExpiredError(AuthenticationError):
21
+ """The session is no longer authenticated."""
22
+
23
+
24
+ class FacebookCheckpointError(AuthenticationError):
25
+ """Facebook requires a checkpoint or additional verification."""
26
+
27
+
28
+ class TokenExtractionError(FacebookError):
29
+ """The birthday page did not contain a usable ``fb_dtsg`` token."""
30
+
31
+
32
+ class GraphQLQueryError(FacebookError):
33
+ """The birthday GraphQL request failed."""
34
+
35
+
36
+ class PersistedQueryError(GraphQLQueryError):
37
+ """Facebook no longer recognises the persisted birthday query."""
38
+
39
+
40
+ class GraphQLSchemaError(FacebookError):
41
+ """Facebook returned JSON whose birthday schema is not understood."""
@@ -0,0 +1,89 @@
1
+ """Facebook HTTP client, independent from authentication creation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+
9
+ import requests
10
+
11
+ from .__init__ import __title__, __version__
12
+ from .errors import FacebookCheckpointError, GraphQLQueryError, SessionExpiredError
13
+ from .facebook_queries import (
14
+ GRAPHQL_ENDPOINT,
15
+ build_birthday_payload,
16
+ parse_birthday_response,
17
+ )
18
+ from .facebook_token import FacebookDTSGParser
19
+
20
+ BIRTHDAY_PAGE_URL = "https://www.facebook.com/events/birthdays/"
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class SessionValidation:
25
+ status: str
26
+ user_id: str | None
27
+ fb_dtsg: str
28
+
29
+
30
+ class FacebookClient:
31
+ def __init__(self, session: requests.Session | None = None):
32
+ self.logger = logging.getLogger("fb2cal")
33
+ self.session = session if session is not None else requests.Session()
34
+ self.session.headers["User-Agent"] = f"{__title__}/{__version__}"
35
+ self._cached_token: str | None = None
36
+
37
+ def get_token(self) -> str:
38
+ if self._cached_token:
39
+ return self._cached_token
40
+ response = self.session.get(BIRTHDAY_PAGE_URL)
41
+ self._raise_for_auth_response(response)
42
+ self._cached_token = FacebookDTSGParser.extract(response.text)
43
+ return self._cached_token
44
+
45
+ def validate_session(self) -> SessionValidation:
46
+ response = self.session.get(BIRTHDAY_PAGE_URL)
47
+ self._raise_for_auth_response(response)
48
+ token = FacebookDTSGParser.extract(response.text)
49
+ self._cached_token = token
50
+ user_id = self.session.cookies.get("c_user")
51
+ return SessionValidation(status="authenticated", user_id=user_id, fb_dtsg=token)
52
+
53
+ def is_authenticated(self) -> bool:
54
+ try:
55
+ self.validate_session()
56
+ except (SessionExpiredError, FacebookCheckpointError):
57
+ return False
58
+ return True
59
+
60
+ def query_graph_ql_birthday_comet_monthly(
61
+ self, offset_month: int
62
+ ) -> dict[str, Any]:
63
+ payload = build_birthday_payload(offset_month, self.get_token())
64
+ response = self.session.post(GRAPHQL_ENDPOINT, data=payload)
65
+ if response.status_code != 200:
66
+ raise GraphQLQueryError(
67
+ f"Facebook GraphQL request returned HTTP {response.status_code}"
68
+ )
69
+ return parse_birthday_response(response.text)
70
+
71
+ def _raise_for_auth_response(self, response: Any) -> None:
72
+ text = response.text or ""
73
+ url = str(getattr(response, "url", ""))
74
+ if getattr(response, "status_code", 0) in (401, 403) or "/login" in url:
75
+ raise SessionExpiredError(
76
+ "Facebook session is expired or login is required"
77
+ )
78
+ if "checkpointSubmitButton" in text or "/two_step_verification/" in text:
79
+ raise FacebookCheckpointError(
80
+ "Facebook requires checkpoint or two-step verification"
81
+ )
82
+ if "login_form" in text and "DTSGInitialData" not in text:
83
+ raise SessionExpiredError(
84
+ "Facebook session is expired or login is required"
85
+ )
86
+ if getattr(response, "status_code", 0) != 200:
87
+ raise SessionExpiredError(
88
+ f"Facebook birthday page returned HTTP {response.status_code}"
89
+ )
@@ -0,0 +1,60 @@
1
+ """Persisted Facebook GraphQL birthday query definition and parsing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ from .errors import GraphQLQueryError, GraphQLSchemaError, PersistedQueryError
9
+ from .utils import remove_anti_hijacking_protection
10
+
11
+ GRAPHQL_ENDPOINT = "https://www.facebook.com/api/graphql/"
12
+ BIRTHDAY_QUERY_NAME = "BirthdayCometMonthlyBirthdaysRefetchQuery"
13
+ BIRTHDAY_QUERY_DOC_ID = 5347559575302259
14
+
15
+
16
+ def build_birthday_payload(offset_month: int, fb_dtsg: str) -> dict[str, str | int]:
17
+ if offset_month not in (0, 3, 6, 9):
18
+ raise ValueError("offset_month must be one of 0, 3, 6, or 9")
19
+ variables = {"offset_month": offset_month, "scale": 1.5}
20
+ return {
21
+ "fb_api_req_friendly_name": BIRTHDAY_QUERY_NAME,
22
+ "variables": json.dumps(variables, separators=(",", ":")),
23
+ "doc_id": BIRTHDAY_QUERY_DOC_ID,
24
+ "fb_dtsg": fb_dtsg,
25
+ "__a": "1",
26
+ }
27
+
28
+
29
+ def parse_birthday_response(text: str) -> dict[str, Any]:
30
+ try:
31
+ response = json.loads(remove_anti_hijacking_protection(text))
32
+ except (TypeError, json.JSONDecodeError) as exc:
33
+ raise GraphQLQueryError("Facebook returned invalid GraphQL JSON") from exc
34
+
35
+ if not isinstance(response, dict):
36
+ raise GraphQLSchemaError("Facebook GraphQL response is not an object")
37
+ if response.get("error") is not None or response.get("errors"):
38
+ summary = (
39
+ response.get("errorSummary")
40
+ or response.get("errorDescription")
41
+ or "unknown GraphQL error"
42
+ )
43
+ message = str(summary)
44
+ if (
45
+ "doc" in message.lower()
46
+ or "persist" in message.lower()
47
+ or "query" in message.lower()
48
+ ):
49
+ raise PersistedQueryError(
50
+ f"Facebook persisted query {BIRTHDAY_QUERY_NAME} (doc_id {BIRTHDAY_QUERY_DOC_ID}) "
51
+ "may be obsolete; update the query definition."
52
+ )
53
+ raise GraphQLQueryError(f"Facebook birthday GraphQL request failed: {message}")
54
+
55
+ data = response.get("data")
56
+ if not isinstance(data, dict):
57
+ raise GraphQLSchemaError(
58
+ "Facebook GraphQL response does not contain a data object"
59
+ )
60
+ return response
@@ -0,0 +1,101 @@
1
+ """Explicit Facebook session loading.
2
+
3
+ The loader intentionally accepts a file supplied by the user. It never reads
4
+ browser profiles, decrypts browser databases, or discovers cookies implicitly.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import stat
12
+ import warnings
13
+ from collections.abc import Mapping
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ import requests
18
+
19
+ from .errors import CookieFileError
20
+
21
+
22
+ class FacebookSession(requests.Session):
23
+ """A requests session with a safe, explicit cookie-file loader."""
24
+
25
+ @classmethod
26
+ def from_cookie_file(cls, path: str | os.PathLike[str]) -> FacebookSession:
27
+ cookie_path = Path(path).expanduser()
28
+ if not cookie_path.is_file():
29
+ raise CookieFileError(f"Cookie file does not exist: {cookie_path}")
30
+
31
+ try:
32
+ mode = stat.S_IMODE(cookie_path.stat().st_mode)
33
+ if mode & 0o077:
34
+ warnings.warn(
35
+ f"Cookie file {cookie_path} is readable by other users; "
36
+ "restrict its permissions (for example chmod 600).",
37
+ UserWarning,
38
+ stacklevel=2,
39
+ )
40
+ except OSError as exc:
41
+ raise CookieFileError(
42
+ f"Could not inspect cookie file: {cookie_path}"
43
+ ) from exc
44
+
45
+ try:
46
+ raw = json.loads(cookie_path.read_text(encoding="utf-8"))
47
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
48
+ raise CookieFileError(f"Could not read cookie JSON: {cookie_path}") from exc
49
+
50
+ cookies = raw.get("cookies") if isinstance(raw, Mapping) else raw
51
+ if not isinstance(cookies, list):
52
+ raise CookieFileError(
53
+ "Cookie JSON must be a list or an object with a 'cookies' list"
54
+ )
55
+
56
+ session = cls()
57
+ for item in cookies:
58
+ cookie = cls._cookie_from_mapping(item)
59
+ session.cookies.set_cookie(cookie)
60
+
61
+ if not session.cookies.get("c_user"):
62
+ raise CookieFileError(
63
+ "Cookie file does not contain the required c_user cookie"
64
+ )
65
+ return session
66
+
67
+ @staticmethod
68
+ def _cookie_from_mapping(item: Any) -> requests.cookies.Cookie:
69
+ if not isinstance(item, Mapping):
70
+ raise CookieFileError("Each cookie must be an object")
71
+ name = item.get("name")
72
+ value = item.get("value")
73
+ if not isinstance(name, str) or not name or not isinstance(value, str):
74
+ raise CookieFileError("Each cookie requires string name and value fields")
75
+
76
+ domain = item.get("domain", ".facebook.com")
77
+ path = item.get("path", "/")
78
+ if not isinstance(domain, str) or not isinstance(path, str):
79
+ raise CookieFileError(f"Invalid domain/path for cookie {name}")
80
+
81
+ kwargs: dict[str, Any] = {
82
+ "domain": domain,
83
+ "path": path,
84
+ "secure": bool(item.get("secure", True)),
85
+ }
86
+ if item.get("expirationDate") is not None:
87
+ try:
88
+ kwargs["expires"] = int(item["expirationDate"])
89
+ except (TypeError, ValueError) as exc:
90
+ raise CookieFileError(
91
+ f"Invalid expirationDate for cookie {name}"
92
+ ) from exc
93
+ elif item.get("expires") is not None:
94
+ try:
95
+ kwargs["expires"] = int(item["expires"])
96
+ except (TypeError, ValueError) as exc:
97
+ raise CookieFileError(
98
+ f"Invalid expires value for cookie {name}"
99
+ ) from exc
100
+
101
+ return requests.cookies.create_cookie(name=name, value=value, **kwargs)
@@ -0,0 +1,31 @@
1
+ """Strategies for extracting Facebook's ``fb_dtsg`` token from HTML."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ import re
7
+
8
+ from .errors import TokenExtractionError
9
+
10
+
11
+ class FacebookDTSGParser:
12
+ """Extract a CSRF token using a small, ordered set of known strategies."""
13
+
14
+ _PATTERNS = (
15
+ re.compile(r'\["DTSGInitialData",\[\],\{"token":"([^"]+)"'),
16
+ re.compile(r'"DTSGInitialData"\s*,\s*\[\]\s*,\s*\{\s*"token"\s*:\s*"([^"]+)"'),
17
+ re.compile(r'"token"\s*:\s*"([^"]+)"[^\n]{0,120}"DTSGInitialData"'),
18
+ )
19
+
20
+ @classmethod
21
+ def extract(cls, html_text: str) -> str:
22
+ if not isinstance(html_text, str):
23
+ raise TokenExtractionError("Facebook birthday page is not text")
24
+ candidate_text = html.unescape(html_text)
25
+ for pattern in cls._PATTERNS:
26
+ match = pattern.search(candidate_text)
27
+ if match and match.group(1):
28
+ return match.group(1)
29
+ raise TokenExtractionError(
30
+ "Could not extract fb_dtsg from the Facebook birthday page"
31
+ )