339 Commits
1.5.0 ... 1.7.0

Author SHA1 Message Date
MartinBraquet
7e924c2741 Release 2025-11-23 14:22:54 +01:00
MartinBraquet
241b851c02 Fix 2025-11-20 21:13:38 +01:00
MartinBraquet
2ba9949035 Add get it on google play 2025-11-20 21:09:42 +01:00
MartinBraquet
3d4b76ffc3 Fix message fetching after sending 2025-11-19 21:04:08 +01:00
Nicholas Chamberlain
f7fb0c6c82 Test/e2e login auth (#19)
* Add basic test for login and auth state

* Remove test file

* Change login setup

* Apply suggestions from code review

Co-authored-by: Martin Braquet <martin.braquet@gmail.com>

* Change signin structure to use UI

* Fix URL loading

* Spin up backend server as well for E2E

---------

Co-authored-by: Martin Braquet <martin.braquet@gmail.com>
2025-11-18 23:17:00 +01:00
MartinBraquet
e5fc734b90 Fix question refresh too quick 2025-11-15 16:32:55 +01:00
MartinBraquet
10fa659e52 Add favicon.svg 2025-11-15 16:18:27 +01:00
MartinBraquet
0ac315b017 Merge remote-tracking branch 'origin/main' 2025-11-15 16:12:36 +01:00
MartinBraquet
bbfbd2daae Remove 2025-11-15 16:04:16 +01:00
MartinBraquet
cd2c4d3314 Load favicon from local webview assets 2025-11-15 15:55:01 +01:00
MartinBraquet
37ee7752c2 Fix build-web-view 2025-11-15 15:53:07 +01:00
Okechi Jones-Williams
6b11e6b060 Add minor changes to tests (#20)
* setting up test structure

* .

* added playwright config file, deleted original playwright folder and moved "some.test" file

* continued test structure setup

* Updating test folder structure

* Added database seeding script and backend testing folder structure

* removed the database test

* Replaced db seeding script

* Updated userInformation.ts to use values from choices.tsx

* merge prep

* removing extra unit test, moving api test to correct folder
2025-11-15 15:35:45 +01:00
MartinBraquet
f650ab7394 Clean 2025-11-15 14:20:14 +01:00
MartinBraquet
fead7459d4 Clean 2025-11-15 14:12:06 +01:00
MartinBraquet
bbf3970121 Update todo 2025-11-15 14:06:15 +01:00
MartinBraquet
26fb810840 Add docs links 2025-11-15 14:01:45 +01:00
MartinBraquet
af9074af6e Add users link to stats 2025-11-15 13:53:35 +01:00
MartinBraquet
4229c2a4fa Merge remote-tracking branch 'origin/main' 2025-11-15 13:52:14 +01:00
MartinBraquet
fd58602e6d Add "core" 2025-11-15 13:52:05 +01:00
MartinBraquet
af26397ad7 Rounded dropdown 2025-11-15 13:51:58 +01:00
MartinBraquet
859d01594a Allow for skipping unanswered questions in /compatibility 2025-11-15 13:51:48 +01:00
MartinBraquet
09a37058e6 Fix tabs index caching 2025-11-15 13:22:48 +01:00
MartinBraquet
edc7366b1d Improve docs 2025-11-15 13:05:26 +01:00
MartinBraquet
7306cb335b Add chalk 2025-11-15 12:24:06 +01:00
Martin Braquet
1e13cc4294 Update README.md 2025-11-15 10:16:44 +01:00
Martin Braquet
a88e5a9ec8 Update README.md 2025-11-15 09:20:46 +01:00
MartinBraquet
09d743c603 Fix 2025-11-15 01:04:41 +01:00
MartinBraquet
36c1ec528a Include all ts/tsx files in coverage 2025-11-15 00:52:37 +01:00
MartinBraquet
aec9600036 Clean 2025-11-15 00:48:37 +01:00
MartinBraquet
6e1306bdd6 Merge coverage files 2025-11-15 00:41:48 +01:00
MartinBraquet
37f5c95716 Fix coverage 2025-11-15 00:33:25 +01:00
MartinBraquet
0d48c541a0 Add tests runs to all packages 2025-11-15 00:27:30 +01:00
MartinBraquet
8928cd1667 Update test structure 2025-11-15 00:14:12 +01:00
MartinBraquet
780f935fea Fix webview live update 2025-11-14 18:53:25 +01:00
MartinBraquet
5bf095178d Add live updates for the webview app 2025-11-14 18:12:29 +01:00
MartinBraquet
e135293b43 Lowercase new 2025-11-14 18:12:05 +01:00
MartinBraquet
be7e009909 Fix 2025-11-14 16:03:01 +01:00
MartinBraquet
ada8a713c1 Fix 2025-11-14 16:01:21 +01:00
MartinBraquet
eb7391dae0 Skip for now 2025-11-14 15:24:19 +01:00
MartinBraquet
8bdbd5e4fe Add code coverage 2025-11-14 15:23:56 +01:00
MartinBraquet
137d15ae71 Clean 2025-11-14 14:37:01 +01:00
MartinBraquet
8a2ed6f8ff Improve docs 2025-11-14 14:32:30 +01:00
MartinBraquet
7766b43187 Fix 2025-11-14 14:14:52 +01:00
MartinBraquet
b9a637fdac Fix 2025-11-14 14:13:34 +01:00
MartinBraquet
3096dbc922 Add Next.js.md 2025-11-14 14:12:07 +01:00
MartinBraquet
d6b0bb4378 Ignore getServerSideProps on mobile 2025-11-14 12:26:37 +01:00
MartinBraquet
43ef43ba72 Little fixes 2025-11-13 20:38:16 +01:00
MartinBraquet
314037dd06 Add /compatibility page to browse all the questions 2025-11-13 20:10:53 +01:00
MartinBraquet
7c4d66bbf5 Fix 2025-11-13 16:27:58 +01:00
MartinBraquet
49d28961ef Improve UI for filters 2025-11-13 15:53:39 +01:00
MartinBraquet
9d649daee5 Add profile field and filter: MBTI 2025-11-13 15:12:11 +01:00
MartinBraquet
7598a47283 Add local logging 2025-11-13 14:11:50 +01:00
MartinBraquet
c9f7230d27 Fix 2025-11-13 13:54:23 +01:00
MartinBraquet
716633c6df Remove trailing empty paragraphs 2025-11-13 13:53:11 +01:00
MartinBraquet
8a215a765f Add AI assistant rules 2025-11-13 13:13:17 +01:00
MartinBraquet
e2ff41a0b1 Ignore 2025-11-13 13:12:57 +01:00
MartinBraquet
d790fae74a Add e2e script for local development 2025-11-13 13:11:53 +01:00
MartinBraquet
1a17862f45 Clean choice constants 2025-11-12 18:39:56 +01:00
MartinBraquet
acd4c36531 Add profile field and filter: relationship status 2025-11-12 18:29:28 +01:00
MartinBraquet
f623450f08 Clean 2025-11-11 22:13:07 +01:00
MartinBraquet
ce681cfb67 Add profile field and filter: languages 2025-11-11 22:02:16 +01:00
MartinBraquet
a0a6523a25 Move stats up 2025-11-11 21:07:51 +01:00
MartinBraquet
8e2fa36d0e Fix 2025-11-11 21:07:40 +01:00
MartinBraquet
c953a84c1f Clean choices 2025-11-11 21:06:56 +01:00
MartinBraquet
2b403f0761 Move log 2025-11-11 21:06:44 +01:00
Okechi Jones-Williams
f954e3b2d7 Add database seeding script and backend testing folder structure (#18)
* setting up test structure

* added playwright config file, deleted original playwright folder and moved "some.test" file

* continued test structure setup

* Updating test folder structure

* Added database seeding script and backend testing folder structure

* removed the database test

* Replaced db seeding script

* Updated userInformation.ts to use values from choices.tsx
2025-11-11 19:00:07 +01:00
MartinBraquet
24ee2a206e Back to up 2025-11-10 18:59:15 +01:00
MartinBraquet
02d165829f Move to / 2025-11-10 18:54:09 +01:00
MartinBraquet
b4d996bd14 Fix 2025-11-10 18:49:22 +01:00
MartinBraquet
60989faa03 Add TEST_DOWNTIME 2025-11-10 18:45:07 +01:00
MartinBraquet
4aeda8a1a7 Clean 2025-11-09 22:13:01 +01:00
MartinBraquet
023a20f263 Add script to add test user to db 2025-11-09 20:20:22 +01:00
MartinBraquet
62821ed803 Release 2025-11-08 20:52:41 +01:00
MartinBraquet
903d62ed57 Add error comment 2025-11-08 19:55:13 +01:00
MartinBraquet
adef626b34 Cache build ID 2025-11-08 19:46:42 +01:00
MartinBraquet
11a933cc04 Comment 2025-11-08 19:46:21 +01:00
MartinBraquet
4b5ce99bb1 Fix avatar link not working on mobile 2025-11-08 19:46:13 +01:00
MartinBraquet
f8dff77cee Do not use ID filtering anymore as loaded messages may be deleted or edited 2025-11-08 18:50:23 +01:00
MartinBraquet
0a9b08803e Add comment 2025-11-08 18:48:47 +01:00
MartinBraquet
39a8568663 Fix orderBy that must be filtered out 2025-11-08 18:12:13 +01:00
MartinBraquet
e1502440eb Increase debounce since moved back to free plan (1 / sec) 2025-11-07 23:31:18 +01:00
MartinBraquet
5834d032c3 Android release 2025-11-07 23:26:46 +01:00
MartinBraquet
0a28a2af61 Allow editing old messages 2025-11-07 23:26:38 +01:00
MartinBraquet
259f56bd26 Fix typescript / linting warnings 2025-11-07 23:17:16 +01:00
MartinBraquet
011ad66a3f Fix emoji location (2) 2025-11-07 23:13:32 +01:00
MartinBraquet
281c72f88d Merge remote-tracking branch 'origin/main' 2025-11-07 22:53:07 +01:00
Okechi Jones-Williams
1293523ebf Added further playwright structure (#17)
* setting up test structure

* .

* added playwright config file, deleted original playwright folder and moved "some.test" file

* continued test structure setup

* Updating test folder structure
2025-11-07 22:52:19 +01:00
MartinBraquet
67e5d34f39 Fix emoji location 2025-11-07 22:48:38 +01:00
MartinBraquet
8b3dec6116 Merge remote-tracking branch 'origin/main' 2025-11-07 21:52:25 +01:00
MartinBraquet
3359f49f0a Add edit, delete and emojis on messages 2025-11-07 21:51:56 +01:00
Okechi Jones-Williams
9715cae587 Setting up test file structure (#16)
* setting up test structure

* .
2025-11-07 14:28:07 +01:00
MartinBraquet
4b122bd907 Increase version 2025-11-05 20:52:19 +01:00
MartinBraquet
edefa36c8a Comments 2025-11-05 20:46:56 +01:00
MartinBraquet
e40a352aed When clicking on the DM notif, go to the DM chat 2025-11-05 20:46:41 +01:00
MartinBraquet
70267f0623 Add demo fix
Hope it works finally
2025-11-04 17:51:38 +01:00
MartinBraquet
c19ed7f6d5 Add demo
Hope it works finally
2025-11-04 17:37:49 +01:00
MartinBraquet
e2fb0f2ee8 Line clamp notif to 5 2025-11-04 13:07:57 +01:00
MartinBraquet
f9e208a7e0 Add createAndroidTestNotifications 2025-11-04 13:04:06 +01:00
MartinBraquet
ee2b8a60a2 Increase notif lines 2025-11-04 13:03:43 +01:00
MartinBraquet
5651f17e96 Increase android version 2025-11-04 12:46:17 +01:00
MartinBraquet
9679b3722a Show error 2025-11-04 01:25:19 +01:00
MartinBraquet
6cb736a10d Upgrade 2025-11-03 23:55:37 +01:00
MartinBraquet
ac5c3b421d Upgrade 2025-11-03 23:45:53 +01:00
MartinBraquet
f01fad5fa6 Improve message rendering on webview (fix 2) 2025-11-03 23:45:03 +01:00
MartinBraquet
110b727cbc Improve message rendering on webview (fix) 2025-11-03 23:13:56 +01:00
MartinBraquet
1dba2debc5 Clean 2025-11-03 20:27:32 +01:00
MartinBraquet
8fec73341f Comment 2025-11-03 18:39:56 +01:00
MartinBraquet
33c76de397 Improve bio tips 2025-11-03 17:19:37 +01:00
MartinBraquet
d409eb1126 Refactor news 2025-11-03 16:53:50 +01:00
MartinBraquet
69d53591c8 Load cached remote page data from webview 2025-11-03 16:44:41 +01:00
MartinBraquet
4cf783f07f Add proxy 2025-11-03 16:19:10 +01:00
MartinBraquet
a971c121cc Allow any origin 2025-11-03 16:04:50 +01:00
MartinBraquet
b4abfb6aa4 Simplify build-id 2025-11-03 15:53:44 +01:00
MartinBraquet
8f760081a5 Add build-id/route.ts 2025-11-03 15:25:11 +01:00
MartinBraquet
c15934f210 Render home icon if logged out 2025-11-03 15:17:14 +01:00
MartinBraquet
c7e1bb4463 People is more human than profiles 2025-11-03 12:15:18 +01:00
MartinBraquet
4ac97fc476 Make webview go back one page instead of closing the app 2025-11-02 22:26:22 +01:00
MartinBraquet
a5dda01ffd Clean 2025-11-02 22:20:49 +01:00
MartinBraquet
9db4937e54 Fix layout 2025-11-02 22:07:56 +01:00
MartinBraquet
3dc50a384e Add title when loading 2025-11-02 22:05:36 +01:00
MartinBraquet
ccc48620b8 Fix profile page not switching between users 2025-11-02 21:41:23 +01:00
MartinBraquet
943c3960e1 Comment logs 2025-11-02 21:39:17 +01:00
MartinBraquet
9a84a67555 Improve margins for mobile 2025-11-02 21:29:51 +01:00
MartinBraquet
2241e3c7d3 Log pixel top and bottom 2025-11-02 21:27:07 +01:00
MartinBraquet
03042dae96 Do not disclose exact last online time for privacy reasons 2025-11-02 21:26:17 +01:00
MartinBraquet
3df9d067d6 Clean posthog 2025-11-02 21:15:09 +01:00
MartinBraquet
c5f3e8b3c2 Clean css 2025-11-02 20:26:39 +01:00
MartinBraquet
3a3e8c0e10 Add get pixel height 2025-11-02 20:26:29 +01:00
MartinBraquet
f010bf7eed Fix 2025-11-02 13:14:20 +01:00
MartinBraquet
b22d6a77b0 Update readme 2025-11-02 13:09:14 +01:00
MartinBraquet
f91d9125e4 Ignore getStaticProps and getStaticPaths for mobile webview build 2025-11-02 13:09:00 +01:00
MartinBraquet
625eedef1e Add middleware template 2025-11-02 13:04:10 +01:00
MartinBraquet
61dd33187a Use SSR/ISR only for web app (load client side on mobile app) 2025-11-02 13:03:22 +01:00
MartinBraquet
817640c7d0 Update reserved path 2025-11-02 00:21:25 +01:00
MartinBraquet
aa15d5a6df Comment 2025-11-02 00:21:15 +01:00
MartinBraquet
60857007bd Fix 2025-11-01 22:11:50 +01:00
MartinBraquet
cfd0c5d846 versionCode 4 2025-11-01 22:05:43 +01:00
MartinBraquet
71ec88d235 Add mobile icons 2025-11-01 22:05:28 +01:00
MartinBraquet
902ea583bd Remove AD_ID 2025-11-01 21:27:36 +01:00
MartinBraquet
fb6b54fba0 Delete mobile subscriptions if not set up 2025-11-01 21:26:43 +01:00
MartinBraquet
9dfc56987c Add Child Sexual Abuse and Exploitation (CSAE) 2025-11-01 20:30:42 +01:00
MartinBraquet
b982a02717 V2 2025-11-01 18:47:55 +01:00
MartinBraquet
15a0d8ee16 Add /delete-account 2025-11-01 17:20:31 +01:00
MartinBraquet
9ca03132db Rename to com.compassconnections.com 2025-11-01 17:14:08 +01:00
MartinBraquet
f908ba3ea3 Update terms 2025-11-01 17:09:15 +01:00
MartinBraquet
79ea09bd91 Skip web service-worker.js on native mobile 2025-11-01 16:25:55 +01:00
MartinBraquet
c743a4f1fe Comment unused google auth 2025-11-01 16:22:09 +01:00
MartinBraquet
ccd1fc5c10 Fix data not in notif 2025-11-01 16:06:22 +01:00
MartinBraquet
2f82a64dbe Add isNativeMobile 2025-11-01 16:06:07 +01:00
MartinBraquet
71c6eae9c4 Fix googleNativeLogin 2025-11-01 16:05:58 +01:00
MartinBraquet
28894a08cc Add capgo-capacitor-social-login to gradle 2025-11-01 16:05:42 +01:00
MartinBraquet
41e366dcc4 Output export for webview 2025-11-01 16:05:26 +01:00
MartinBraquet
6ee11a6b2d Skip getStaticProps in webview 2025-11-01 16:05:03 +01:00
MartinBraquet
ab82c66f83 Add bridge for social 2025-11-01 16:04:36 +01:00
MartinBraquet
f94820f45e Fix favicon not showing in webview 2025-11-01 16:03:39 +01:00
MartinBraquet
fe03e1ca68 Use local assets for prod 2025-11-01 16:03:26 +01:00
MartinBraquet
44ee6951c9 Comment usused deep link 2025-11-01 16:02:52 +01:00
MartinBraquet
40194f7204 Update readme 2025-11-01 16:02:37 +01:00
MartinBraquet
40eefef9a2 Use full ico path for webview 2025-11-01 16:02:25 +01:00
MartinBraquet
d8ab44ebb5 Install @capgo/capacitor-social-login 2025-11-01 16:01:47 +01:00
MartinBraquet
f875539f2e Move to unused 2025-11-01 16:01:36 +01:00
MartinBraquet
d9c2d142cb Format 2025-11-01 16:00:11 +01:00
MartinBraquet
51d5715f04 Clean 404 2025-11-01 12:38:01 +01:00
MartinBraquet
8ad81b1d50 Add bottom margin 2025-11-01 12:37:55 +01:00
MartinBraquet
6d4083d8a7 Move hosting constants to new file 2025-11-01 11:19:36 +01:00
MartinBraquet
bb120afea2 Clean web build 2025-11-01 11:17:20 +01:00
MartinBraquet
cebcc20c26 Add email verif link in welcome email 2025-11-01 10:53:10 +01:00
MartinBraquet
0522e787cd Add Forgot Password? 2025-10-31 20:41:57 +01:00
MartinBraquet
81e01f1485 Change tag 2025-10-31 20:32:09 +01:00
MartinBraquet
9b2b93d56f Update faq 2025-10-31 20:31:40 +01:00
MartinBraquet
133b402e2b Add IS_WEBVIEW_BUILD 2025-10-31 13:36:41 +01:00
MartinBraquet
9a91eab13f Catch user not found 2025-10-31 11:52:32 +01:00
MartinBraquet
5f6722b917 Add message notif 2025-10-31 11:52:24 +01:00
MartinBraquet
fdcd4d46ac Add allowNavigation 2025-10-31 11:52:06 +01:00
MartinBraquet
27a72170b8 Url redirect 2025-10-31 11:51:58 +01:00
MartinBraquet
b3021e60ec Add sync_android.sh 2025-10-31 10:41:22 +01:00
MartinBraquet
6d8834bd87 Add little emoji 2025-10-31 10:41:12 +01:00
MartinBraquet
ab8a9d95d8 Add notif perms 2025-10-31 00:15:42 +01:00
MartinBraquet
563ee3f5df Remove unused social login 2025-10-31 00:15:34 +01:00
MartinBraquet
c3389a7fcf Uncomment 2025-10-31 00:14:57 +01:00
MartinBraquet
e824bbb533 Add webview push notif 2025-10-30 23:45:04 +01:00
MartinBraquet
7de0e351f3 Skip notif verif in client 2025-10-30 23:44:41 +01:00
MartinBraquet
2df5f55390 Add androidpush check 2025-10-30 23:31:57 +01:00
MartinBraquet
21038cc5ac Clean and refactor oauth redirect 2025-10-30 23:28:18 +01:00
MartinBraquet
d6749bcd41 Add way to access profiles without log in during dev 2025-10-30 23:18:50 +01:00
MartinBraquet
005c9ccdef Add info 2025-10-30 23:18:31 +01:00
MartinBraquet
d47cb53e59 Fix filter top touching top nav bar 2025-10-30 23:18:18 +01:00
MartinBraquet
adfb3ca4f0 Add build_sync_android.sh 2025-10-30 23:03:16 +01:00
MartinBraquet
88b7e4edda Update android readmes 2025-10-30 22:59:09 +01:00
MartinBraquet
e33b57f0fd Comment sensitive logs 2025-10-30 22:52:33 +01:00
MartinBraquet
777825b73f Better log 2025-10-30 22:50:16 +01:00
MartinBraquet
04ca9b6f9a Remove PKCE as using google client secret 2025-10-30 22:39:10 +01:00
MartinBraquet
7f3d3eeb9c Hide background in bottom nav bar 2025-10-30 22:24:47 +01:00
MartinBraquet
75ac16d43c Rename 2025-10-30 21:59:33 +01:00
MartinBraquet
5f1120c718 Fix 2025-10-30 21:55:21 +01:00
MartinBraquet
806a0694c6 Add status bar 2025-10-30 21:50:36 +01:00
MartinBraquet
c506ae3242 Fix statusbard 2025-10-30 21:48:31 +01:00
MartinBraquet
444fa529fb Fix margin 2025-10-30 21:47:17 +01:00
MartinBraquet
62ced3eb04 Add top and bottom margin for mobile 2025-10-30 21:40:36 +01:00
MartinBraquet
31718f1c4d Refactor redirect url 2025-10-30 20:37:12 +01:00
MartinBraquet
98ab8971b4 Clean 2025-10-30 19:52:55 +01:00
MartinBraquet
870c86f9af Cleanup 2025-10-30 19:39:03 +01:00
MartinBraquet
a4f6aabee9 Cleanup 2025-10-30 19:37:11 +01:00
MartinBraquet
5584ad0a10 Remove unused cst 2025-10-30 19:26:26 +01:00
MartinBraquet
6b4932b4c5 Add error handling 2025-10-30 19:26:19 +01:00
MartinBraquet
7f1cb0aaf3 Add firebase login after receiving tokens 2025-10-30 19:26:08 +01:00
MartinBraquet
d42a5a48e9 Send code verifier to backend 2025-10-30 18:44:22 +01:00
MartinBraquet
8a1b762c35 Fix readme 2025-10-30 18:44:12 +01:00
MartinBraquet
d2d1de41d2 Fix 2025-10-30 18:08:22 +01:00
MartinBraquet
d1366af2a0 Fix 2025-10-30 18:06:14 +01:00
MartinBraquet
cae4b15bbb Fix 2025-10-30 18:01:49 +01:00
MartinBraquet
e41bc64b0c Fix 2025-10-30 17:21:19 +01:00
MartinBraquet
3d03ebe487 Fix 2025-10-30 17:18:00 +01:00
MartinBraquet
1fcb431d1b Fix bridge 2025-10-30 17:15:49 +01:00
MartinBraquet
4f321490af Fix 2025-10-30 17:11:53 +01:00
MartinBraquet
04c7469e68 Fix 2025-10-30 17:06:19 +01:00
MartinBraquet
98bc0a9309 Fix 2025-10-30 17:01:21 +01:00
MartinBraquet
6e537f4cdf Fix 2025-10-30 16:48:52 +01:00
MartinBraquet
b121d61852 Fix 2025-10-30 16:24:22 +01:00
MartinBraquet
6ba3c3ffbd Fix 2025-10-30 13:53:59 +01:00
MartinBraquet
67b3efad4c Fix 2025-10-30 13:50:05 +01:00
MartinBraquet
1282e468e3 Fix 2025-10-30 13:47:12 +01:00
MartinBraquet
67b2e78a63 Fix oauthRedirect 2025-10-30 13:44:40 +01:00
MartinBraquet
213c56f945 Fix 2025-10-30 13:20:27 +01:00
MartinBraquet
ccde6e4f4b Fix 2025-10-30 12:46:25 +01:00
MartinBraquet
2c1c94d24c Update android webview 2025-10-30 12:40:20 +01:00
MartinBraquet
56edb51f36 Add bridge 2025-10-30 12:40:00 +01:00
MartinBraquet
b6ed2c7dd8 Change GOOGLE_CLIENT_ID 2025-10-30 12:25:46 +01:00
MartinBraquet
74c7c5c423 Fix GOOGLE_CLIENT_ID 2025-10-30 12:00:04 +01:00
MartinBraquet
314d774bde Fix 2025-10-30 11:51:56 +01:00
MartinBraquet
d94091ae4e Add webviewGoogleSignin 2025-10-30 11:33:23 +01:00
MartinBraquet
8bf3c4fcd7 Remove sign up button if logged in 2025-10-29 20:43:36 +01:00
MartinBraquet
4358c15432 Update TODOS 2025-10-29 20:30:56 +01:00
MartinBraquet
fdf8d649fe Link logo to /home page 2025-10-29 20:04:50 +01:00
MartinBraquet
a4e22ec4b1 Add email change 2025-10-29 20:01:42 +01:00
MartinBraquet
783bc43547 Move delete pinned photo 2025-10-29 19:23:33 +01:00
MartinBraquet
2e6aec175a Comment 2025-10-29 17:51:22 +01:00
MartinBraquet
ee41aaa112 Use WithPrivateUser 2025-10-29 17:51:12 +01:00
MartinBraquet
32e8a8b1b9 Add donation name 2025-10-29 17:30:57 +01:00
MartinBraquet
6b3def230b Add liberapay donation link 2025-10-29 17:20:47 +01:00
MartinBraquet
51c46db106 Fix 2025-10-29 17:06:39 +01:00
MartinBraquet
64c18179ac Fix 2025-10-29 16:50:06 +01:00
MartinBraquet
5ee0b39e07 Hide settings when logged out 2025-10-29 16:29:14 +01:00
MartinBraquet
6470319fd6 Add settings page 2025-10-29 16:25:03 +01:00
MartinBraquet
4ca3f3c8ee Delete auth user right away 2025-10-29 16:24:49 +01:00
MartinBraquet
07e2d2d509 Fix red color 2025-10-29 16:21:58 +01:00
MartinBraquet
07d2a143a2 Create base settings page 2025-10-29 12:24:08 +01:00
MartinBraquet
968845492f Comment unused function 2025-10-29 12:23:53 +01:00
MartinBraquet
c2106b64f9 Add webview_oauth_signin.md 2025-10-29 12:08:20 +01:00
MartinBraquet
0d73d1d258 Delete 2025-10-28 18:43:39 +01:00
MartinBraquet
423d425950 Roolback 2025-10-28 18:42:37 +01:00
MartinBraquet
7ab0093fec Sign in failing for android 2025-10-28 18:41:54 +01:00
MartinBraquet
56d2757448 Add styles 2025-10-28 18:32:21 +01:00
MartinBraquet
f5b6037367 Move log 2025-10-28 18:02:45 +01:00
MartinBraquet
2c4ce6c8d1 Add isAndroidWebView 2025-10-28 17:33:25 +01:00
MartinBraquet
f9ccd3628a Add logs 2025-10-28 16:56:45 +01:00
MartinBraquet
abef2b394e Add aiexclude 2025-10-28 16:51:00 +01:00
MartinBraquet
97ff6f1de9 Add base android webview app 2025-10-28 16:05:22 +01:00
MartinBraquet
7fad4435cb Add android readme 2025-10-28 15:16:19 +01:00
MartinBraquet
92a97209ca Add yarn build-web 2025-10-28 15:16:13 +01:00
MartinBraquet
e7c3f083b4 Update NEXT_PUBLIC_LOCAL_ANDROID check 2025-10-28 15:16:02 +01:00
MartinBraquet
7b5961f941 Add log 2025-10-28 01:34:29 +01:00
MartinBraquet
85d4b411b5 Add log 2025-10-28 01:10:51 +01:00
MartinBraquet
c9ec32aca7 Fix APK discrimination 2025-10-28 00:37:02 +01:00
MartinBraquet
13a3013a8e Add @capgo/capacitor-social-login 2025-10-28 00:16:28 +01:00
MartinBraquet
0dd3bac855 Add googleNativeLogin 2025-10-28 00:10:44 +01:00
MartinBraquet
d7a716a5cb Add -H 0.0.0.0 2025-10-28 00:04:02 +01:00
MartinBraquet
0bbc9cbe81 Add IS_LOCAL_ANDROID 2025-10-28 00:03:54 +01:00
MartinBraquet
df766d8d1f Fix typo 2025-10-28 00:02:28 +01:00
MartinBraquet
20a150a228 Remove ; 2025-10-27 21:45:17 +01:00
MartinBraquet
010292a440 Remove cached dataa 2025-10-27 21:44:29 +01:00
MartinBraquet
394dae18e9 Move FCM inside 2025-10-27 21:44:19 +01:00
MartinBraquet
f1676c52f0 Add mobile push notifications 2025-10-27 16:12:51 +01:00
MartinBraquet
05f6f3c79b Install capacitor android 2025-10-27 13:13:52 +01:00
MartinBraquet
9942b488ea Serve mobile app from url 2025-10-27 13:13:41 +01:00
MartinBraquet
5d83f4bf2d Add build web script 2025-10-27 13:13:25 +01:00
MartinBraquet
d9afd914ff Make SEA description dynamic 2025-10-27 12:56:06 +01:00
MartinBraquet
990d8160f8 Use SSR for news 2025-10-27 12:49:08 +01:00
MartinBraquet
80c321b66f Remove log 2025-10-27 12:48:12 +01:00
MartinBraquet
67b45f3e5c Add capacitor 2025-10-27 11:49:39 +01:00
MartinBraquet
ca3cee5673 Move paragraph 2025-10-27 01:47:23 +01:00
MartinBraquet
ae0d170244 Improve wording 2025-10-27 01:46:10 +01:00
MartinBraquet
9a31cfa938 Fixes 2025-10-27 01:34:30 +01:00
MartinBraquet
cdbc9c305e Allow null for profiles 2025-10-27 01:23:20 +01:00
MartinBraquet
cdbce13c49 Sort zod types 2025-10-27 00:39:48 +01:00
MartinBraquet
0a41ebbcda Add an option to disable your profile 2025-10-27 00:37:54 +01:00
MartinBraquet
476fe1602b Clean 2025-10-27 00:37:18 +01:00
MartinBraquet
2f482e9afc Fix links 2025-10-26 18:50:14 +01:00
MartinBraquet
d59e6e0691 Fix news link (open in no tab) 2025-10-26 18:37:44 +01:00
MartinBraquet
7ec6866f26 Add news to FAQ 2025-10-26 16:37:16 +01:00
MartinBraquet
3686e7facf Remove changelog 2025-10-26 16:32:00 +01:00
MartinBraquet
1aba1894ea Remove unused react 2025-10-26 16:24:38 +01:00
MartinBraquet
14503c9b8f Fix header color 2025-10-26 16:24:12 +01:00
MartinBraquet
a315668d31 Fix format 2025-10-26 16:19:42 +01:00
MartinBraquet
db9ea63210 Add what's new page 2025-10-26 16:07:57 +01:00
MartinBraquet
51ecbd5b53 Add dark swagger docs 2025-10-26 15:45:47 +01:00
MartinBraquet
45ef0d9809 Add /donate to /support 2025-10-26 14:37:05 +01:00
MartinBraquet
356702b50d Hide local endpoints when deployed 2025-10-26 14:34:09 +01:00
MartinBraquet
e72ce5376c Remove unused pages 2025-10-26 14:24:48 +01:00
MartinBraquet
0d35f3fbd2 Add bottom margin 2025-10-26 14:24:17 +01:00
MartinBraquet
28c22c1eae Add qr code to FAQ 2025-10-26 14:24:04 +01:00
MartinBraquet
7cf83f65c3 Cache vote creators 2025-10-26 13:53:46 +01:00
MartinBraquet
4c4f2e720d Add status on proposals 2025-10-26 10:51:52 +01:00
MartinBraquet
0fa562e6fd Rename order by 2025-10-26 10:01:36 +01:00
MartinBraquet
bcd0f778cf Rename vote title 2025-10-26 10:01:20 +01:00
MartinBraquet
401ab9f706 Add bottom margin 2025-10-26 09:42:20 +01:00
MartinBraquet
8b09a81d5a Add keyword example 2025-10-25 23:54:50 +02:00
MartinBraquet
86718cc406 Sleep more more more 2025-10-25 23:20:17 +02:00
MartinBraquet
ccb72364e1 Sleep more 2025-10-25 23:08:55 +02:00
MartinBraquet
bfd6a59d87 Increase cache check 2025-10-25 23:08:48 +02:00
MartinBraquet
af4caa455a Fix typos 2025-10-25 23:00:54 +02:00
MartinBraquet
d511e4a75c Comment log 2025-10-25 23:00:46 +02:00
MartinBraquet
8fd906223c Re enable dev cache 2025-10-25 23:00:40 +02:00
MartinBraquet
deadb56aaa Try to load profiles times if not found 2025-10-25 23:00:25 +02:00
MartinBraquet
1ff867879c Throttle discord message 2025-10-25 23:00:02 +02:00
MartinBraquet
f3630dd868 Send generic error message instead of error log 2025-10-25 22:30:08 +02:00
MartinBraquet
39143525c3 Revalidates ISR pages 2025-10-25 22:18:48 +02:00
MartinBraquet
e8dd1f8f8b Add log 2025-10-25 21:48:25 +02:00
MartinBraquet
28e5d2e3f2 Fix profile not found due to cache 2025-10-25 21:40:29 +02:00
MartinBraquet
21def91427 Fix plus icon color 2025-10-25 21:22:29 +02:00
MartinBraquet
bc5d04c662 Set user_id?: string 2025-10-25 16:57:51 +02:00
MartinBraquet
c736227448 Add response to send test email 2025-10-25 16:52:11 +02:00
MartinBraquet
168285cb64 Add contact info to /contact 2025-10-25 16:37:15 +02:00
MartinBraquet
3411f50d29 Add /local/send-test-email endpoint 2025-10-25 16:33:30 +02:00
MartinBraquet
319c14b0e0 Add react import in email
Required since using tsx watch src/serve.ts and not nodemon
2025-10-25 16:32:55 +02:00
MartinBraquet
64c077396f Rename fromEmail 2025-10-25 16:32:07 +02:00
MartinBraquet
65f0d448a1 Fix messages not sent 2025-10-25 15:48:42 +02:00
MartinBraquet
2fdaa464dd Remove import 2025-10-25 15:33:23 +02:00
MartinBraquet
f86a6a10ac Add political_details 2025-10-25 15:32:16 +02:00
MartinBraquet
08a2438e79 Add Animist 2025-10-25 15:31:53 +02:00
MartinBraquet
60cc47f7ca Improve rendering of religion in about me 2025-10-25 14:45:53 +02:00
MartinBraquet
7e4f606492 Improve filter formatting for politics and religion 2025-10-25 14:36:55 +02:00
MartinBraquet
8ff58534d9 Update docs 2025-10-25 14:24:14 +02:00
MartinBraquet
a4bb184e95 Add filter: religion 2025-10-25 14:22:11 +02:00
MartinBraquet
940c1f5692 Add profile field: religion 2025-10-25 14:21:58 +02:00
MartinBraquet
0430733b58 Add internal endpoints to API docs 2025-10-25 13:44:00 +02:00
MartinBraquet
33136816af Improve API docs 2025-10-25 13:31:44 +02:00
MartinBraquet
469a235799 Remove logs 2025-10-25 04:40:11 +02:00
MartinBraquet
2d71c827b3 Fix 2025-10-25 04:30:21 +02:00
276 changed files with 11257 additions and 1882 deletions

420
.cursor/rules/dev-rules.mdc Normal file
View File

@@ -0,0 +1,420 @@
---
alwaysApply: true
---
## Project Structure
- next.js react tailwind frontend `/web`
- broken down into pages, components, hooks, lib
- express node api server `/backend/api`
- one off scripts, like migrations `/backend/scripts`
- supabase postgres. schema in `/backend/supabase`
- supabase-generated types in `/backend/supabase/schema.ts`
- files shared between backend directories `/backend/shared`
- anything in `/backend` can import from `shared`, but not vice versa
- files shared between the frontend and backend in `/common`
- `/common` has lots of type definitions for our data structures, like User. It also contains many useful utility functions. We try not to add package dependencies to common. `/web` and `/backend` are allowed to import from `/common`, but not vice versa.
## Deployment
- The project has both dev and prod environments.
- Backend is on GCP (Google Cloud Platform). Deployment handled by terraform.
- Project ID is `compass-130ba`.
## Code Guidelines
---
Here's an example component from web in our style:
```tsx
import clsx from 'clsx'
import Link from 'next/link'
import { isAdminId, isModId } from 'common/envs/constants'
import { type Headline } from 'common/news'
import { EditNewsButton } from 'web/components/news/edit-news-button'
import { Carousel } from 'web/components/widgets/carousel'
import { useUser } from 'web/hooks/use-user'
import { track } from 'web/lib/service/analytics'
import { DashboardEndpoints } from 'web/components/dashboard/dashboard-page'
import { removeEmojis } from 'common/util/string'
export function HeadlineTabs(props: {
headlines: Headline[]
currentSlug: string
endpoint: DashboardEndpoints
hideEmoji?: boolean
notSticky?: boolean
className?: string
}) {
const { headlines, endpoint, currentSlug, hideEmoji, notSticky, className } =
props
const user = useUser()
return (
<div
className={clsx(
className,
'bg-canvas-50 w-full',
!notSticky && 'sticky top-0 z-50'
)}
>
<Carousel labelsParentClassName="gap-px">
{headlines.map(({ id, slug, title }) => (
<Tab
key={id}
label={hideEmoji ? removeEmojis(title) : title}
href={`/${endpoint}/${slug}`}
active={slug === currentSlug}
/>
))}
{user && <Tab label="More" href="/dashboard" />}
{user && (isAdminId(user.id) || isModId(user.id)) && (
<EditNewsButton endpoint={endpoint} defaultDashboards={headlines} />
)}
</Carousel>
</div>
)
}
```
---
We prefer to have many smaller components that each represent one logical unit, rather than one very large component that does everything. Then we compose and reuse the components.
It's best to export the main component at the top of the file. We also try to name the component the same as the file name (headline-tabs.tsx) so that it's easy to find.
Here's another example in `home.tsx` that calls our api. We have an endpoint called 'headlines', which is being cached by NextJS:
```ts
import { api } from 'web/lib/api/api'
// More imports...
export async function getStaticProps() {
try {
const headlines = await api('headlines', {})
return {
props: {
headlines,
revalidate: 30 * 60, // 30 minutes
},
}
} catch (err) {
return { props: { headlines: [] }, revalidate: 60 }
}
}
export default function Home(props: { headlines: Headline[] }) { ... }
```
---
If we are calling the API on the client, prefer using the `useAPIGetter` hook:
```ts
export const YourTopicsSection = (props: {
user: User
className?: string
}) => {
const { user, className } = props
const { data, refresh } = useAPIGetter('get-followed-groups', {
userId: user.id,
})
const followedGroups = data?.groups ?? []
...
```
This stores the result in memory, and allows you to call refresh() to get an updated version.
---
We frequently use `usePersistentInMemoryState` or `usePersistentLocalState` as an alternative to `useState`. These cache data. Most of the time you want in-memory caching so that navigating back to a page will preserve the same state and appear to load instantly.
Here's the definition of usePersistentInMemoryState:
```ts
export const usePersistentInMemoryState = <T>(initialValue: T, key: string) => {
const [state, setState] = useStateCheckEquality<T>(
safeJsonParse(store[key]) ?? initialValue
)
useEffect(() => {
const storedValue = safeJsonParse(store[key]) ?? initialValue
setState(storedValue as T)
}, [key])
const saveState = useEvent((newState: T | ((prevState: T) => T)) => {
setState((prevState) => {
const updatedState = isFunction(newState) ? newState(prevState) : newState
store[key] = JSON.stringify(updatedState)
return updatedState
})
})
return [state, saveState] as const
}
```
---
For live updates, we use websockets. In `use-api-subscription.ts`, we have this hook:
```ts
export function useApiSubscription(opts: SubscriptionOptions) {
useEffect(() => {
const ws = client
if (ws != null) {
if (opts.enabled ?? true) {
ws.subscribe(opts.topics, opts.onBroadcast).catch(opts.onError)
return () => {
ws.unsubscribe(opts.topics, opts.onBroadcast).catch(opts.onError)
}
}
}
}, [opts.enabled, JSON.stringify(opts.topics)])
}
```
In `use-bets`, we have this hook to get live updates with useApiSubscription:
```ts
export const useContractBets = (
contractId: string,
opts?: APIParams<'bets'> & { enabled?: boolean }
) => {
const { enabled = true, ...apiOptions } = {
contractId,
...opts,
}
const optionsKey = JSON.stringify(apiOptions)
const [newBets, setNewBets] = usePersistentInMemoryState<Bet[]>(
[],
`${optionsKey}-bets`
)
const addBets = (bets: Bet[]) => {
setNewBets((currentBets) => {
const uniqueBets = sortBy(
uniqBy([...currentBets, ...bets], 'id'),
'createdTime'
)
return uniqueBets.filter((b) => !betShouldBeFiltered(b, apiOptions))
})
}
const isPageVisible = useIsPageVisible()
useEffect(() => {
if (isPageVisible && enabled) {
api('bets', apiOptions).then(addBets)
}
}, [optionsKey, enabled, isPageVisible])
useApiSubscription({
topics: [`contract/${contractId}/new-bet`],
onBroadcast: (msg) => {
addBets(msg.data.bets as Bet[])
},
enabled,
})
return newBets
}
```
---
Here are all the topics we broadcast, from `backend/shared/src/websockets/helpers.ts`
```ts
export function broadcastUpdatedPrivateUser(userId: string) {
// don't send private user info because it's private and anyone can listen
broadcast(`private-user/${userId}`, {})
}
export function broadcastUpdatedUser(user: Partial<User> & { id: string }) {
broadcast(`user/${user.id}`, { user })
}
export function broadcastUpdatedComment(comment: Comment) {
broadcast(`user/${comment.onUserId}/comment`, { comment })
}
```
---
We have our scripts in the directory `/backend/scripts`.
To write a script, run it inside the helper function called `runScript` that automatically fetches any secret keys and loads them into process.env.
Example from `/backend/scripts/manicode.ts`
```ts
import { runScript } from 'run-script'
runScript(async ({ pg }) => {
const userPrompt = process.argv[2]
await pg.none(...)
})
```
Generally scripts should be run by me, especially if they modify backend state or schema.
But if you need to run a script, you can use `bun`. For example:
```sh
bun run manicode.ts "Generate a page called cowp, which has cows that make noises!"
```
if that doesn't work, try
```sh
bun x ts-node manicode.ts "Generate a page called cowp, which has cows that make noises!"
```
---
Our backend is mostly a set of endpoints. We create new endpoints by adding to the schema in `/common/src/api/schema.ts`.
E.g. Here is a hypothetical bet schema:
```ts
bet: {
method: 'POST',
authed: true,
returns: {} as CandidateBet & { betId: string },
props: z
.object({
contractId: z.string(),
amount: z.number().gte(1),
replyToCommentId: z.string().optional(),
limitProb: z.number().gte(0.01).lte(0.99).optional(),
expiresAt: z.number().optional(),
// Used for binary and new multiple choice contracts (cpmm-multi-1).
outcome: z.enum(['YES', 'NO']).default('YES'),
//Multi
answerId: z.string().optional(),
dryRun: z.boolean().optional(),
})
.strict(),
}
```
Then, we define the bet endpoint in `backend/api/src/place-bet.ts`
```ts
export const placeBet: APIHandler<'bet'> = async (props, auth) => {
const isApi = auth.creds.kind === 'key'
return await betsQueue.enqueueFn(
() => placeBetMain(props, auth.uid, isApi),
[props.contractId, auth.uid]
)
}
```
And finally, you need to register the handler in `backend/api/src/routes.ts`
```ts
import { placeBet } from './place-bet'
...
const handlers = {
bet: placeBet,
...
}
```
---
We have two ways to access our postgres database.
```ts
import { db } from 'web/lib/supabase/db'
db.from('profiles').select('*').eq('user_id', userId)
```
and
```ts
import { createSupabaseDirectClient } from 'shared/supabase/init'
const pg = createSupabaseDirectClient()
pg.oneOrNone<Row<'profiles'>>('select * from profiles where user_id = $1', [userId])
```
The supabase client just uses the supabase client library, which is a wrapper around postgREST. It allows us to query and update the database directly from the frontend.
`createSupabaseDirectClient` is used on the backend. it lets us specify sql strings to run directly on our database, using the pg-promise library. The client (code in web) does not have permission to do this.
Another example using the direct client:
```ts
export const getUniqueBettorIds = async (
contractId: string,
pg: SupabaseDirectClient
) => {
const res = await pg.manyOrNone(
'select distinct user_id from contract_bets where contract_id = $1',
[contractId]
)
return res.map((r) => r.user_id as string)
}
```
(you may notice we write sql in lowercase)
We have a few helper functions for updating and inserting data into the database.
```ts
import {
buikInsert,
bulkUpdate,
bulkUpdateData,
bulkUpsert,
insert,
update,
updateData,
} from 'shared/supabase/utils'
...
const pg = createSupabaseDirectClient()
// you are encouraged to use tryCatch for these
const { data, error } = await tryCatch(
insert(pg, 'profiles', { user_id: auth.uid, ...body })
)
if (error) throw APIError(500, 'Error creating profile: ' + error.message)
await update(pg, 'profiles', 'user_id', { user_id: auth.uid, age: 99 })
await updateData(pg, 'private_users', { id: userId, notifications: { ... } })
```
The sqlBuilder from `shared/supabase/sql-builder.ts` can be used to construct SQL queries with re-useable parts. All it does is sanitize and output sql query strings. It has several helper functions including:
- `select`: Specifies the columns to select
- `from`: Specifies the table to query
- `where`: Adds WHERE clauses
- `orderBy`: Specifies the order of results
- `limit`: Limits the number of results
- `renderSql`: Combines all parts into a final SQL string
Example usage:
```typescript
const query = renderSql(
select('distinct user_id'),
from('contract_bets'),
where('contract_id = ${id}', { id }),
orderBy('created_time desc'),
limitValue != null && limit(limitValue)
)
const res = await pg.manyOrNone(query)
```
Use these functions instead of string concatenation.

2
.github/FUNDING.yml vendored
View File

@@ -6,7 +6,7 @@ open_collective: compass-connection # Replace with a single Open Collective user
ko_fi: compassconnections # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
liberapay: CompassConnections # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username

View File

@@ -32,29 +32,63 @@ jobs:
run: npm run lint
- name: Run Jest tests
run: npm run test tests/jest
env:
NEXT_PUBLIC_FIREBASE_ENV: DEV
run: |
yarn test:coverage
# npm install -g lcov-result-merger
# mkdir coverage
# lcov-result-merger \
# "backend/api/coverage/lcov.info" \
# "backend/shared/coverage/lcov.info" \
# "backend/email/coverage/lcov.info" \
# "common/coverage/lcov.info" \
# "web/coverage/lcov.info" \
# > coverage/lcov.info
# - name: Build app
# - name: Build app
# env:
# DATABASE_URL: ${{ secrets.DATABASE_URL }}
# run: npm run build
# Optional: Playwright E2E tests
- name: Install Playwright deps
run: npx playwright install --with-deps
# npm install @playwright/test
# npx playwright install
run: |
npx playwright install --with-deps
# npm install @playwright/test
- name: Run E2E tests
env:
NEXT_PUBLIC_API_URL: localhost:8088
NEXT_PUBLIC_FIREBASE_ENV: PROD
NEXT_PUBLIC_FIREBASE_ENV: DEV
NEXT_PUBLIC_FIREBASE_API_KEY: ${{ secrets.NEXT_PUBLIC_FIREBASE_API_KEY }}
NEXT_PUBLIC_SUPABASE_KEY: ${{ secrets.NEXT_PUBLIC_SUPABASE_KEY }}
run: |
yarn --cwd=web serve &
npx nyc --reporter=lcov yarn --cwd=web serve &
npx nyc --reporter=lcov yarn --cwd=backend/api dev &
npx wait-on http://localhost:3000
npx playwright test tests/playwright
npx playwright test tests/e2e
SERVER_PID=$(fuser -k 3000/tcp)
echo $SERVER_PID
kill $SERVER_PID
SERVER_PID=$(fuser -k 8088/tcp)
echo $SERVER_PID
kill $SERVER_PID
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v5
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: |
backend/api/coverage/lcov.info
backend/shared/coverage/lcov.info
backend/email/coverage/lcov.info
common/coverage/lcov.info
web/coverage/lcov.info
flags: unit
fail_ci_if_error: true
slug: CompassConnections/Compass
env:
CI: true

16
.gitignore vendored
View File

@@ -13,6 +13,10 @@
# testing
/coverage
# Playwright
/tests/reports/playwright-report
/tests/e2e/web/.auth/
# next.js
/.next/
/out/
@@ -61,7 +65,7 @@ email-preview
*.last-run.json
*lock.hcl
/web/pages/test.tsx
/web/pages/_test.tsx
*.png
*.jpg
@@ -71,6 +75,7 @@ email-preview
*.ico
*.mp4
*.mov
*.webp
*.avi
*.wmv
*.mp3
@@ -87,3 +92,12 @@ email-preview
*.terraform
/backups/firebase/auth/data/
/backups/firebase/storage/data/
android/app/release*
icons/
*.bak
test-results
/.nyc_output/
**/coverage

422
.windsurf/rules/compass.md Normal file
View File

@@ -0,0 +1,422 @@
---
trigger: always_on
description:
globs:
---
## Project Structure
- next.js react tailwind frontend `/web`
- broken down into pages, components, hooks, lib
- express node api server `/backend/api`
- one off scripts, like migrations `/backend/scripts`
- supabase postgres. schema in `/backend/supabase`
- supabase-generated types in `/backend/supabase/schema.ts`
- files shared between backend directories `/backend/shared`
- anything in `/backend` can import from `shared`, but not vice versa
- files shared between the frontend and backend in `/common`
- `/common` has lots of type definitions for our data structures, like User. It also contains many useful utility functions. We try not to add package dependencies to common. `/web` and `/backend` are allowed to import from `/common`, but not vice versa.
## Deployment
- The project has both dev and prod environments.
- Backend is on GCP (Google Cloud Platform). Deployment handled by terraform.
- Project ID is `compass-130ba`.
## Code Guidelines
---
Here's an example component from web in our style:
```tsx
import clsx from 'clsx'
import Link from 'next/link'
import { isAdminId, isModId } from 'common/envs/constants'
import { type Headline } from 'common/news'
import { EditNewsButton } from 'web/components/news/edit-news-button'
import { Carousel } from 'web/components/widgets/carousel'
import { useUser } from 'web/hooks/use-user'
import { track } from 'web/lib/service/analytics'
import { DashboardEndpoints } from 'web/components/dashboard/dashboard-page'
import { removeEmojis } from 'common/util/string'
export function HeadlineTabs(props: {
headlines: Headline[]
currentSlug: string
endpoint: DashboardEndpoints
hideEmoji?: boolean
notSticky?: boolean
className?: string
}) {
const { headlines, endpoint, currentSlug, hideEmoji, notSticky, className } =
props
const user = useUser()
return (
<div
className={clsx(
className,
'bg-canvas-50 w-full',
!notSticky && 'sticky top-0 z-50'
)}
>
<Carousel labelsParentClassName="gap-px">
{headlines.map(({ id, slug, title }) => (
<Tab
key={id}
label={hideEmoji ? removeEmojis(title) : title}
href={`/${endpoint}/${slug}`}
active={slug === currentSlug}
/>
))}
{user && <Tab label="More" href="/dashboard" />}
{user && (isAdminId(user.id) || isModId(user.id)) && (
<EditNewsButton endpoint={endpoint} defaultDashboards={headlines} />
)}
</Carousel>
</div>
)
}
```
---
We prefer to have many smaller components that each represent one logical unit, rather than one very large component that does everything. Then we compose and reuse the components.
It's best to export the main component at the top of the file. We also try to name the component the same as the file name (headline-tabs.tsx) so that it's easy to find.
Here's another example in `home.tsx` that calls our api. We have an endpoint called 'headlines', which is being cached by NextJS:
```ts
import { api } from 'web/lib/api/api'
// More imports...
export async function getStaticProps() {
try {
const headlines = await api('headlines', {})
return {
props: {
headlines,
revalidate: 30 * 60, // 30 minutes
},
}
} catch (err) {
return { props: { headlines: [] }, revalidate: 60 }
}
}
export default function Home(props: { headlines: Headline[] }) { ... }
```
---
If we are calling the API on the client, prefer using the `useAPIGetter` hook:
```ts
export const YourTopicsSection = (props: {
user: User
className?: string
}) => {
const { user, className } = props
const { data, refresh } = useAPIGetter('get-followed-groups', {
userId: user.id,
})
const followedGroups = data?.groups ?? []
...
```
This stores the result in memory, and allows you to call refresh() to get an updated version.
---
We frequently use `usePersistentInMemoryState` or `usePersistentLocalState` as an alternative to `useState`. These cache data. Most of the time you want in-memory caching so that navigating back to a page will preserve the same state and appear to load instantly.
Here's the definition of usePersistentInMemoryState:
```ts
export const usePersistentInMemoryState = <T>(initialValue: T, key: string) => {
const [state, setState] = useStateCheckEquality<T>(
safeJsonParse(store[key]) ?? initialValue
)
useEffect(() => {
const storedValue = safeJsonParse(store[key]) ?? initialValue
setState(storedValue as T)
}, [key])
const saveState = useEvent((newState: T | ((prevState: T) => T)) => {
setState((prevState) => {
const updatedState = isFunction(newState) ? newState(prevState) : newState
store[key] = JSON.stringify(updatedState)
return updatedState
})
})
return [state, saveState] as const
}
```
---
For live updates, we use websockets. In `use-api-subscription.ts`, we have this hook:
```ts
export function useApiSubscription(opts: SubscriptionOptions) {
useEffect(() => {
const ws = client
if (ws != null) {
if (opts.enabled ?? true) {
ws.subscribe(opts.topics, opts.onBroadcast).catch(opts.onError)
return () => {
ws.unsubscribe(opts.topics, opts.onBroadcast).catch(opts.onError)
}
}
}
}, [opts.enabled, JSON.stringify(opts.topics)])
}
```
In `use-bets`, we have this hook to get live updates with useApiSubscription:
```ts
export const useContractBets = (
contractId: string,
opts?: APIParams<'bets'> & { enabled?: boolean }
) => {
const { enabled = true, ...apiOptions } = {
contractId,
...opts,
}
const optionsKey = JSON.stringify(apiOptions)
const [newBets, setNewBets] = usePersistentInMemoryState<Bet[]>(
[],
`${optionsKey}-bets`
)
const addBets = (bets: Bet[]) => {
setNewBets((currentBets) => {
const uniqueBets = sortBy(
uniqBy([...currentBets, ...bets], 'id'),
'createdTime'
)
return uniqueBets.filter((b) => !betShouldBeFiltered(b, apiOptions))
})
}
const isPageVisible = useIsPageVisible()
useEffect(() => {
if (isPageVisible && enabled) {
api('bets', apiOptions).then(addBets)
}
}, [optionsKey, enabled, isPageVisible])
useApiSubscription({
topics: [`contract/${contractId}/new-bet`],
onBroadcast: (msg) => {
addBets(msg.data.bets as Bet[])
},
enabled,
})
return newBets
}
```
---
Here are all the topics we broadcast, from `backend/shared/src/websockets/helpers.ts`
```ts
export function broadcastUpdatedPrivateUser(userId: string) {
// don't send private user info because it's private and anyone can listen
broadcast(`private-user/${userId}`, {})
}
export function broadcastUpdatedUser(user: Partial<User> & { id: string }) {
broadcast(`user/${user.id}`, { user })
}
export function broadcastUpdatedComment(comment: Comment) {
broadcast(`user/${comment.onUserId}/comment`, { comment })
}
```
---
We have our scripts in the directory `/backend/scripts`.
To write a script, run it inside the helper function called `runScript` that automatically fetches any secret keys and loads them into process.env.
Example from `/backend/scripts/manicode.ts`
```ts
import { runScript } from 'run-script'
runScript(async ({ pg }) => {
const userPrompt = process.argv[2]
await pg.none(...)
})
```
Generally scripts should be run by me, especially if they modify backend state or schema.
But if you need to run a script, you can use `bun`. For example:
```sh
bun run manicode.ts "Generate a page called cowp, which has cows that make noises!"
```
if that doesn't work, try
```sh
bun x ts-node manicode.ts "Generate a page called cowp, which has cows that make noises!"
```
---
Our backend is mostly a set of endpoints. We create new endpoints by adding to the schema in `/common/src/api/schema.ts`.
E.g. Here is a hypothetical bet schema:
```ts
bet: {
method: 'POST',
authed: true,
returns: {} as CandidateBet & { betId: string },
props: z
.object({
contractId: z.string(),
amount: z.number().gte(1),
replyToCommentId: z.string().optional(),
limitProb: z.number().gte(0.01).lte(0.99).optional(),
expiresAt: z.number().optional(),
// Used for binary and new multiple choice contracts (cpmm-multi-1).
outcome: z.enum(['YES', 'NO']).default('YES'),
//Multi
answerId: z.string().optional(),
dryRun: z.boolean().optional(),
})
.strict(),
}
```
Then, we define the bet endpoint in `backend/api/src/place-bet.ts`
```ts
export const placeBet: APIHandler<'bet'> = async (props, auth) => {
const isApi = auth.creds.kind === 'key'
return await betsQueue.enqueueFn(
() => placeBetMain(props, auth.uid, isApi),
[props.contractId, auth.uid]
)
}
```
And finally, you need to register the handler in `backend/api/src/routes.ts`
```ts
import { placeBet } from './place-bet'
...
const handlers = {
bet: placeBet,
...
}
```
---
We have two ways to access our postgres database.
```ts
import { db } from 'web/lib/supabase/db'
db.from('profiles').select('*').eq('user_id', userId)
```
and
```ts
import { createSupabaseDirectClient } from 'shared/supabase/init'
const pg = createSupabaseDirectClient()
pg.oneOrNone<Row<'profiles'>>('select * from profiles where user_id = $1', [userId])
```
The supabase client just uses the supabase client library, which is a wrapper around postgREST. It allows us to query and update the database directly from the frontend.
`createSupabaseDirectClient` is used on the backend. it lets us specify sql strings to run directly on our database, using the pg-promise library. The client (code in web) does not have permission to do this.
Another example using the direct client:
```ts
export const getUniqueBettorIds = async (
contractId: string,
pg: SupabaseDirectClient
) => {
const res = await pg.manyOrNone(
'select distinct user_id from contract_bets where contract_id = $1',
[contractId]
)
return res.map((r) => r.user_id as string)
}
```
(you may notice we write sql in lowercase)
We have a few helper functions for updating and inserting data into the database.
```ts
import {
buikInsert,
bulkUpdate,
bulkUpdateData,
bulkUpsert,
insert,
update,
updateData,
} from 'shared/supabase/utils'
...
const pg = createSupabaseDirectClient()
// you are encouraged to use tryCatch for these
const { data, error } = await tryCatch(
insert(pg, 'profiles', { user_id: auth.uid, ...body })
)
if (error) throw APIError(500, 'Error creating profile: ' + error.message)
await update(pg, 'profiles', 'user_id', { user_id: auth.uid, age: 99 })
await updateData(pg, 'private_users', { id: userId, notifications: { ... } })
```
The sqlBuilder from `shared/supabase/sql-builder.ts` can be used to construct SQL queries with re-useable parts. All it does is sanitize and output sql query strings. It has several helper functions including:
- `select`: Specifies the columns to select
- `from`: Specifies the table to query
- `where`: Adds WHERE clauses
- `orderBy`: Specifies the order of results
- `limit`: Limits the number of results
- `renderSql`: Combines all parts into a final SQL string
Example usage:
```typescript
const query = renderSql(
select('distinct user_id'),
from('contract_bets'),
where('contract_id = ${id}', { id }),
orderBy('created_time desc'),
limitValue != null && limit(limitValue)
)
const res = await pg.manyOrNone(query)
```
Use these functions instead of string concatenation.

View File

@@ -1,13 +1,13 @@
[![CI](https://github.com/CompassConnections/Compass/actions/workflows/ci.yml/badge.svg)](https://github.com/CompassConnections/Compass/actions/workflows/ci.yml)
[![CD](https://github.com/CompassConnections/Compass/actions/workflows/cd.yml/badge.svg)](https://github.com/CompassConnections/Compass/actions/workflows/cd.yml)
![Vercel](https://deploy-badge.vercel.app/vercel/compass)
[![CD](https://github.com/CompassConnections/Compass/actions/workflows/cd.yml/badge.svg)](https://github.com/CompassConnections/Compass/actions/workflows/cd.yml)
[![CI](https://github.com/CompassConnections/Compass/actions/workflows/ci.yml/badge.svg)](https://github.com/CompassConnections/Compass/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/CompassConnections/Compass/branch/main/graph/badge.svg)](https://codecov.io/gh/CompassConnections/Compass)
[![Users](https://img.shields.io/badge/Users-300%2B-blue?logo=myspace)](https://www.compassmeet.com/stats)
# Compass
This repository contains the source code for [Compass](https://compassmeet.com) — an open platform for forming deep, authentic 1-on-1 connections with clarity and efficiency.
**We cant do this alone.** Whatever your skills—coding, design, writing, moderation, marketing, or even small donations—you can make a real difference. [Contribute](https://www.compassmeet.com/support) in any way you can and help our community thrive!
This repository contains the source code for [Compass](https://compassmeet.com) — a transparent platform for forming deep, authentic 1-on-1 connections with clarity and efficiency.
## Features
@@ -21,9 +21,9 @@ This repository contains the source code for [Compass](https://compassmeet.com)
You can find a lot of interesting info in the [About page](https://www.compassmeet.com/about) and the [FAQ](https://www.compassmeet.com/faq) as well.
A detailed description of the early vision is also available in this [blog post](https://martinbraquet.com/meeting-rational) (you can disregard the parts about rationality, as Compass shifted to a more general audience).
<p style="text-align: center;">
<img src="https://firebasestorage.googleapis.com/v0/b/compass-130ba.firebasestorage.app/o/misc%2Fdemo_compass.gif?alt=media&token=e3ae4334-4e3f-4026-b121-c08b4b724cd1" alt="Compass Demo" width="600">
</p>
**We cant do this alone.** Whatever your skills—coding, design, writing, moderation, marketing, or even small donations—you can make a real difference. [Contribute](https://www.compassmeet.com/support) in any way you can and help our community thrive!
![Demo](https://raw.githubusercontent.com/CompassConnections/assets/refs/heads/main/assets/demo-2x.gif)
## To Do
@@ -53,7 +53,9 @@ Here is a tailored selection of things that would be very useful. If you want to
- [x] Search through most profile variables
- [x] Set up chat / direct messaging
- [x] Set up domain name (compassmeet.com)
- [ ] Add mobile app (React Native on Android and iOS)
- [ ] Cover with tests (unit, integration, e2e)
- [x] Add Android mobile app
- [ ] Add iOS mobile app
- [ ] Add better onboarding (tooltips, modals, etc.)
- [ ] Add modules to learn more about each other (personality test, conflict style, love languages, etc.)
- [ ] Add modules to improve interpersonal skills (active listening, nonviolent communication, etc.)
@@ -67,20 +69,19 @@ Everything is open to anyone for collaboration, but the following ones are parti
- [x] Clean up learn more page
- [x] Add dark theme
- [ ] Add profile fields (intellectual interests, cause areas, personality type, conflict style, timezone, etc.)
- [ ] Add filters to search through remaining profile fields (politics, religion, education level, etc.)
- [ ] Cover with tests (crucial, just the test template and framework are ready)
- [x] Add filters to search through remaining profile fields (politics, religion, education level, etc.)
- [ ] Make the app more user-friendly and appealing (UI/UX)
- [ ] Clean up terms and conditions (convert to Markdown)
- [ ] Clean up privacy notice (convert to Markdown)
- [ ] Add other authentication methods (GitHub, Facebook, Apple, phone, etc.)
- [ ] Add email verification
- [ ] Add password reset
- [x] Add email verification
- [x] Add password reset
- [x] Add automated welcome email
- [ ] Security audit and penetration testing
- [ ] Make `deploy-api.sh` run automatically on push to `main` branch
- [ ] Create settings page (change email, password, delete account, etc.)
- [x] Create settings page (change email, password, delete account, etc.)
- [ ] Improve [financials](web/public/md/financials.md) page (donor / acknowledgments, etc.)
- [ ] Improve loading sign (e.g., animation of a compass moving around)
- [x] Improve loading sign (e.g., animation of a compass moving around)
- [ ] Show compatibility score in profile page
## Implementation
@@ -104,38 +105,23 @@ git clone https://github.com/<your-username>/Compass.git
cd Compass
```
Install `opentofu`, `docker`, and `yarn`. Try running this on Linux or macOS for a faster install:
Install `yarn` (if not already installed):
```bash
./setup.sh
npm install --global yarn
```
If it doesn't work, you can install them manually (google how to install `opentofu`, `docker`, and `yarn` for your OS).
Then, install the dependencies for this project:
```bash
yarn install
```
### Environment Variables
Almost all the features will work out of the box, so you can skip this step and come back later if you need to test the following services: email, geolocation.
We can't make the following information public, for security and privacy reasons:
- Database, otherwise anyone could access all the user data (including private messages)
- Firebase, otherwise anyone could remove users or modify the media files
- Email, analytics, and location services, otherwise anyone could use the service plans Compass paid for and run up the bill.
That's why we separate all those services between production and development environments, so that you can code freely without impacting the functioning of the deployed platform.
Contributors should use the default keys for local development. Production uses a separate environment with stricter rules and private keys that are not shared.
If you do need one of the few remaining services, you need to set them up and store your own secrets as environment variables. To do so, simply open `.env` and fill in the variables according to the instructions in the file.
### Tests
Make sure the tests pass:
```bash
yarn test tests/jest/
yarn test
```
TODO: make `yarn test` run all the tests, not just the ones in `tests/jest/`.
If they don't and you can't find out why, simply raise an issue! Sometimes it's something on our end that we overlooked.
### Running the Development Server
@@ -162,7 +148,17 @@ You can also add `console.log()` statements in the code.
If you are new to Typescript or the open-source space, you could start with small changes, such as tweaking some web components or improving wording in some pages. You can find those files in `web/public/md/`.
See [development.md](docs/development.md) for additional instructions, such as adding new profile fields.
##### Resources
There is a lof of documentation in the [docs](docs) folder and across the repo, namely:
- [Next.js.md](docs/Next.js.md) for core fundamentals about our web / page-rendering framework.
- [knowledge.md](docs/knowledge.md) for general information about the project structure.
- [development.md](docs/development.md) for additional instructions, such as adding new profile fields.
- [web](web) for the web.
- [backend/api](backend/api) for the backend API.
- [android](android) for the Android app.
There are a lot of useful scripts you can use in the [scripts](scripts) folder.
### Submission
@@ -189,5 +185,19 @@ git push origin <branch-name>
Finally, open a Pull Request on GitHub from your `fork/<branch-name>``CompassConnections/Compass` main branch.
### Environment Variables
Almost all the features will work out of the box, so you can skip this step and come back later if you need to test the following services: email, geolocation.
We can't make the following information public, for security and privacy reasons:
- Database, otherwise anyone could access all the user data (including private messages)
- Firebase, otherwise anyone could remove users or modify the media files
- Email, analytics, and location services, otherwise anyone could use the service plans Compass paid for and run up the bill.
That's why we separate all those services between production and development environments, so that you can code freely without impacting the functioning of the deployed platform.
Contributors should use the default keys for local development. Production uses a separate environment with stricter rules and private keys that are not shared.
If you do need one of the few remaining services, you need to set them up and store your own secrets as environment variables. To do so, simply open `.env` and fill in the variables according to the instructions in the file.
## Acknowledgements
This project is built on top of [manifold.love](https://github.com/sipec/polylove), an open-source dating platform licensed under the MIT License. We greatly appreciate their work and contributions to open-source, which have significantly aided in the development of some core features such as direct messaging, prompts, and email notifications. We invite the community to explore and contribute to other open-source projects like manifold.love as well, especially if you're interested in functionalities that deviate from Compass' ideals of deep, intentional connections.
This project is built on top of [manifold.love](https://github.com/sipec/polylove), an open-source dating platform licensed under the MIT License. We greatly appreciate their work and contributions to open-source, which have significantly aided in the development of some core features such as direct messaging, prompts, and email notifications. We invite the community to explore and contribute to other open-source projects like manifold.love as well, especially if you're interested in functionalities that deviate from Compass' ideals of deep, intentional connections.

0
android/.aiexclude Normal file
View File

102
android/.gitignore vendored Normal file
View File

@@ -0,0 +1,102 @@
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
# Built application files
*.apk
*.aar
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Uncomment the following line in case you need and you don't have the release build type files in your app
# release/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
# Android Studio 3 in .gitignore file.
.idea/caches
.idea/modules.xml
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
.idea/navEditor.xml
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
.cxx/
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
# Version control
vcs.xml
# lint
lint/intermediates/
lint/generated/
lint/outputs/
lint/tmp/
# lint/reports/
# Android Profiling
*.hprof
# Cordova plugins for Capacitor
capacitor-cordova-android-plugins
# Copied web assets
app/src/main/assets/public
# Generated Config files
app/src/main/assets/capacitor.config.json
app/src/main/assets/capacitor.plugins.json
app/src/main/res/xml/config.xml
/app/release/

413
android/README.md Normal file
View File

@@ -0,0 +1,413 @@
# Compass Android WebView App
This folder contains the source code for the Android application of Compass.
A hybrid mobile app built with **Next.js (TypeScript)** frontend, **Firebase backend**, and wrapped as a **Capacitor WebView** for Android. In the future it may contain native code as well.
This document describes how to:
1. Build and run the web frontend and backend locally
2. Sync and build the Android WebView wrapper
3. Debug, sign, and publish the APK
4. Enable Google Sign-In and push notifications
---
## 1. Project Overview
The app is a Capacitor Android project that loads the local Next.js assests inside a WebView.
During development, it can instead load the local frontend (`http://10.0.2.2:3000`) and backend (`http://10.0.2.2:8088`).
Firebase handles authentication and push notifications.
Google Sign-In is supported natively in the WebView via the Capacitor Social Login plugin.
Project Structure
- `app/src/main/java/com/compass/app`: Contains the Java/Kotlin source code for the Android application.
- `app/src/main/res`: Contains the resources for the application, such as layouts, strings, and images.
- `app/build.gradle`: The Gradle build file for the Android application module.
- `build.gradle`: The top-level Gradle build file for the project.
- `AndroidManifest.xml`: The manifest file that describes essential information about the application.
### **Why Local Is the Default**
- **Performance:** Local assets load instantly, without network latency.
- **Reliability:** Works offline or in poor connectivity environments.
- **App Store policy compliance:** Apple and Google generally prefer that the main experience doesnt depend on a remote site (for security, review, and performance reasons).
- **Version consistency:** The web bundle is versioned with the app, ensuring no breaking updates outside your control.
When Remote (No Local Assets) Is sometimes Used
Loading from a **remote URL** (e.g. `https://compassmeet.com`) is **less common**, but seen in a few cases:
- **Internal enterprise apps** where the WebView just wraps an existing web portal.
- **Dynamic content** or **frequent updates** where pushing a new web build every time through app stores would be too slow.
- To leverage the low latency of ISR and SSR.
However, this approach requires:
- Careful handling of **CORS**, **SSL**, and **login/session** persistence.
- Compliance with **Google Play policies** (they may reject apps that are “just a webview of a website” unless theres meaningful native integration).
**A middle ground we use:**
- The app ships with **local assets** for core functionality.
- The app **fetches remote content or updates** (e.g., via Capacitor Live Updates, Ionic Appflow).
## 2. Prerequisites
### Required Software
| Tool | Version | Purpose |
| -------------- | ------- | ---------------------------------- |
| Node.js | 22+ | For building frontend/backend |
| yarn | latest | Package manager |
| Java | 21 | Required for Android Gradle plugin |
| Android Studio | latest | For building and signing APKs |
| Capacitor CLI | latest | Android bridge |
| OpenJDK | 21 | JDK for Gradle |
### Environment Setup
```bash
sudo apt install openjdk-21-jdk
sudo update-alternatives --config java
# Select Java 21
export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64
java -version
javac -version
````
---
## 3. Build and Run the Web App
```
yarn install
yarn build-web-view
```
### Local mode
If you want the webview to load from your local web version of Compass, run the web app.
In root directory:
```bash
export NEXT_PUBLIC_LOCAL_ANDROID=1
yarn dev # or prod
```
* Runs Next.js frontend at `http://localhost:3000`
* Runs backend at `http://10.0.2.2:8088`
### Deployed mode
If you want the webview to load from the deployed web version of Compass (like at www.compassmeet.com), no web app to run.
---
## 5. Android WebView App Setup
### Install dependencies
```
cd android
./gradlew clean
```
Sync web files and native plugins with Android, for offline fallback. In root:
```
export NEXT_PUBLIC_LOCAL_ANDROID=1 # if running your local web Compass
yarn build-web-view # if you made changes to web app
npx cap sync android
```
### Load from site
During local development, open Android Studio project and run the app on an emulator or your physical device.
To use an emulator:
```
npx cap open android
```
To use a physical device for the local web version, you need your mobile and computer to be on the same network / Wi-Fi and point the URL (`LOCAL_BACKEND_DOMAIN` in the code) to your computer IP address (for example, `192.168.1.3:3000`). You also need to set
```
export NEXT_PUBLIC_WEBVIEW_DEV_PHONE=1
```
Then adb install the app your phone (or simply run it from Android Studio on your phone) and the app should be loading content directly from the local code on your computer. You can make changes in the code and it will refresh instantly on the phone.
Building the Application:
1. Open Android Studio.
2. Click on "Open an existing Android Studio project".
3. Navigate to the `android` folder in this repository and select it.
4. Wait for Android Studio to index the project and download any necessary dependencies.
5. Connect your Android device via USB or set up an Android emulator.
6. Click on the "Run" button (green play button) in Android Studio to build and run the application.
7. Select your device or emulator and click "OK".
8. The application should now build and launch on your device or emulator.
---
## 6. Building the APK
### From Android Studio
- If you want to generate a signed APK for release, go to "Build" > "Generate Signed Bundle / APK..." and follow the prompts.
- Make sure to test the application thoroughly on different devices and Android versions to ensure compatibility.
### Debug build
```bash
cd android
./gradlew assembleDebug
```
Outputs:
```
android/app/build/outputs/apk/debug/app-debug.apk
```
### Install on emulator
```bash
adb install -r app/build/outputs/apk/debug/app-debug.apk
```
### Release build (signed)
1. Generate a release keystore:
```bash
keytool -genkey -v -keystore release-key.keystore -alias compass \
-keyalg RSA -keysize 2048 -validity 10000
```
2. Add signing config to `android/app/build.gradle`
3. Build:
```bash
./gradlew assembleRelease
```
### Release on App Stores
To release on the app stores, you need to submit the .aab files, which are not signed, instead of APK. Google or Apple will then sign it with their own key.
---
## 9. Debugging
Client logs from the emulator on Chrome can be accessed at:
```
chrome://inspect/#devices
```
Backend logs can be accessed from the output of `yarn prod / dev` like in the web application.
Java/Kotlin logs can be accessed via Android Studio's Logcat.
```
adb logcat | grep CompassApp
adb logcat | grep com.compassconnections.app
adb logcat | grep Capacitor
```
You can also add this inside `MainActivity.java`:
```java
webView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Log.d("WebView", consoleMessage.message());
return true;
}
});
```
---
## 10. Deploy to Play Store
1. Sign the release APK or AAB.
2. Verify package name matches Firebase settings (`com.compassconnections.app`).
3. Upload to Google Play Console.
4. Add Privacy Policy and content rating.
5. Submit for review.
---
## 11. Common Issues
| Problem | Cause | Fix |
| -------------------------------------- | -------------------------------------- | ------------------------------------------------------------------- |
| `INSTALL_FAILED_UPDATE_INCOMPATIBLE` | Old APK signed with different key | Uninstall old app first |
| `Account reauth failed [16]` | Missing or incorrect SHA-1 in Firebase | Re-add SHA-1 of keystore |
| App opens in Firefox | Missing `WebViewClient` override | Fix `shouldOverrideUrlLoading` |
| APK > 1 GB | Cached webpack artifacts included | Add `.next/` and `/public/cache` to `.gitignore` and build excludes |
---
## 13. Local Development Workflow
```bash
# Terminal 1
export NEXT_PUBLIC_LOCAL_ANDROID=1
yarn dev # or prod
# Terminal 2: start frontend
export NEXT_PUBLIC_LOCAL_ANDROID=1
yarn build-web-view # if you made changes to web app
npx cap sync android
# Run on emulator or device
```
---
## 14. Deployment Workflow
```bash
# Build web app for production and Sync assets to Android
yarn build-sync-android
# Build signed release APK in Android Studio
```
---
## Live Updates
To avoid releasing to the app stores after every code update in the web pages, we build the new bundle and store it in Capawesome Cloud (an alternative to Ionic).
First, you need to do this one-time setup:
```
npm install -g @capawesome/cli@latest
npx @capawesome/cli login
```
Then, run this to build your local assets and push them to Capawesome. Once done, each mobile app user will receive a notice that there is a new update available, which they can approve to download.
```
yarn build-web-view
npx @capawesome/cli apps:bundles:create --path web/out
```
That's all. So you should run the lines above every time you want your web updates pushed to main (which essentially updates the web app) to update the mobile app as well.
Maybe we should add it to our CD. For example we set a file with `{liveUpdateVersion: 1}` and run the live update each time a push to main increments that counter.
There is a limit of 100 monthly active user per month, though. So we may need to pay or create our custom limit as we scale. Next plan is $9 / month and allows 1000 MAUs.
- ∞ Live Updates
- 100 Monthly Active Users
- 500 MB of Storage (around 10 MB per update, but we just delete the previous ones)
- 5 GB of Bandwidth
---
## 15. Resources
* [Capacitor Docs](https://capacitorjs.com/docs)
* [Firebase Android Setup](https://firebase.google.com/docs/android/setup)
* [FCM HTTP API](https://firebase.google.com/docs/cloud-messaging/send-message)
* [Next.js Deployment](https://nextjs.org/docs/deployment)
# Useful Commands
- To build the project: `./gradlew assembleDebug`
- To run unit tests: `./gradlew test`
- To run instrumentation tests: `./gradlew connectedAndroidTest`
- To clean the project: `./gradlew clean`
- To install dependencies: Open Android Studio and it will handle dependencies automatically.
- To update dependencies: Modify the `build.gradle` files and sync the project in Android Studio.
- To generate a signed APK: Use the "Generate Signed Bundle / APK..." option in Android Studio.
- To lint the project: `./gradlew lint`
- To check for updates to the Android Gradle Plugin: `./gradlew dependencyUpdates`
- To run the application on a connected device or emulator: `./gradlew installDebug`
- To view the project structure: Use the "Project" view in Android Studio.
- To analyze the APK: `./gradlew analyzeRelease`
- To run ProGuard/R8: `./gradlew minifyRelease`
- To generate documentation: `./gradlew javadoc`
# One time setups
Was already done for Compass, so you only need to do the steps below if you create a project separated from Compass.
## Configure Firebase
### In Firebase Console
1. Add a **Web app** → obtain `firebaseConfig`
2. Add an **Android app**
* Package name: `com.compassconnections.app`
* Add your SHA-1 and SHA-256 fingerprints (see below)
* Download `google-services.json` and put it in:
```
android/app/google-services.json
```
### To get SHA-1 for debug keystore
```bash
keytool -list -v \
-keystore ~/.android/debug.keystore \
-alias androiddebugkey \
-storepass android \
-keypass android
```
Add both SHA-1 and SHA-256 to Firebase.
## 7. Google Sign-In (Web + Native)
In Firebase Console:
* Enable **Google** provider under *Authentication → Sign-in method*
* Add your **Android SHA-1**
* Add your **Web OAuth client ID**
In your code:
```ts
import { googleNativeLogin } from 'web/lib/service/android-push'
```
## 8. Push Notifications (FCM)
### Setup FCM
* Add Firebase Cloud Messaging to your project
* Include `google-services.json` under `android/app/`
* Add in `android/build.gradle`:
```gradle
classpath 'com.google.gms:google-services:4.3.15'
```
* Add at the bottom of `android/app/build.gradle`:
```gradle
apply plugin: 'com.google.gms.google-services'
```
### Test notification
```ts
const message = {
notification: {
title: "Test Notification",
body: "Hello from Firebase Admin SDK"
},
token: "..."
};
initAdmin()
await admin.messaging().send(message)
.then(response => console.log("Successfully sent message:", response))
.catch(error => console.error("Error sending message:", error));
```
---
## Deep link / custom scheme
A **custom scheme** is a URL protocol that your app owns.
Example:
```
com.compassconnections.app://auth
```
When Android (or iOS) sees a redirect to one of these URLs, it **launches your app** and passes it the URL data. It's useful to open links in the app instead of the browser. For example, if there's a link to Compass on Discord and we click on it on a mobile device that has the app, we want the link to open in the app instead of the browser.
You register this scheme in your `AndroidManifest.xml` so Android knows which app handles it.

3
android/app/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
/build/*
!/build/.npmkeep
/google-services.json

66
android/app/build.gradle Normal file
View File

@@ -0,0 +1,66 @@
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
namespace "com.compassconnections.app"
compileSdk 36
defaultConfig {
applicationId "com.compassconnections.app"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 14
versionName "1.1.3"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
flatDir{
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation project(':capacitor-android')
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation project(':capacitor-cordova-android-plugins')
// Import the Firebase BoM
implementation platform('com.google.firebase:firebase-bom:34.4.0')
// TODO: Add the dependencies for Firebase products you want to use
// When using the BoM, don't specify versions in Firebase dependencies
implementation 'com.google.firebase:firebase-analytics'
// Add the dependencies for any other desired Firebase products
// https://firebase.google.com/docs/android/setup#available-libraries
implementation 'com.google.android.gms:play-services-auth:21.4.0'
implementation 'com.google.firebase:firebase-auth:24.0.1'
}
apply from: 'capacitor.build.gradle'
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
apply plugin: 'com.google.gms.google-services'
}
} catch(Exception e) {
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}

View File

@@ -0,0 +1,24 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
}
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
implementation project(':capacitor-app')
implementation project(':capacitor-keyboard')
implementation project(':capacitor-push-notifications')
implementation project(':capacitor-status-bar')
implementation project(':capawesome-capacitor-live-update')
implementation project(':capgo-capacitor-social-login')
}
if (hasProperty('postBuildExtras')) {
postBuildExtras()
}

21
android/app/proguard-rules.pro vendored Normal file
View File

@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@@ -0,0 +1,26 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import android.content.Context;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.getcapacitor.app", appContext.getPackageName());
}
}

View File

@@ -0,0 +1,76 @@
<?xml version="1.1" encoding="utf-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:fitsSystemWindows="true"
android:theme="@style/AppTheme">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- <intent-filter>-->
<!-- <action android:name="openapp" />-->
<!-- <category android:name="android.intent.category.DEFAULT" />-->
<!-- <category android:name="android.intent.category.BROWSABLE" />-->
<!-- <data android:scheme="com.compassconnections.app" android:host="details"/>-->
<!-- </intent-filter>-->
<!-- <intent-filter android:autoVerify="true">-->
<!-- <action android:name="android.intent.action.VIEW" />-->
<!-- <category android:name="android.intent.category.DEFAULT" />-->
<!-- <category android:name="android.intent.category.BROWSABLE" />-->
<!-- <data android:scheme="com.compassconnections.app" android:host="auth" />-->
<!-- </intent-filter>-->
</activity>
<!-- <service-->
<!-- android:name=".MyMessagingService"-->
<!-- android:exported="false">-->
<!-- <intent-filter>-->
<!-- <action android:name="com.google.firebase.MESSAGING_EVENT" />-->
<!-- </intent-filter>-->
<!--&lt;!&ndash; <meta-data&ndash;&gt;-->
<!--&lt;!&ndash; android:name="com.google.firebase.messaging.default_notification_channel_id"&ndash;&gt;-->
<!--&lt;!&ndash; android:value="@string/default_notification_channel_id" />&ndash;&gt;-->
<!-- </service>-->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
</provider>
</application>
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="com.google.android.gms.permission.AD_ID" tools:node="remove" />
<!-- Firebase Cloud Messaging -->
<permission android:name="${applicationId}.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />
<!-- Old, can be removed ?-->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
</manifest>

View File

@@ -0,0 +1,173 @@
package com.compassconnections.app;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.ContextCompat;
import com.capacitorjs.plugins.pushnotifications.PushNotificationsPlugin;
import com.getcapacitor.BridgeActivity;
import com.getcapacitor.BridgeWebViewClient;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginHandle;
import org.json.JSONException;
import org.json.JSONObject;
import ee.forgr.capacitor.social.login.GoogleProvider;
import ee.forgr.capacitor.social.login.ModifiedMainActivityForSocialLoginPlugin;
import ee.forgr.capacitor.social.login.SocialLoginPlugin;
//import android.app.NotificationChannel;
//import android.app.NotificationManager;
//import android.os.Build;
//import com.google.firebase.messaging.RemoteMessage;
//import com.capacitorjs.plugins.pushnotifications.MessagingService;
//public class MyMessagingService extends MessagingService {
//
// @Override
// public void onMessageReceived(RemoteMessage remoteMessage) {
// // TODO(developer): Handle FCM messages here.
// // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
// Log.d(TAG, "From: " + remoteMessage.getFrom());
//
// // Check if message contains a data payload.
// if (remoteMessage.getData().size() > 0) {
// Log.d(TAG, "Message data payload: " + remoteMessage.getData());
//
// if (/* Check if data needs to be processed by long running job */ true) {
// // For long-running tasks (10 seconds or more) use WorkManager.
// scheduleJob();
// } else {
// // Handle message within 10 seconds
// handleNow();
// }
//
// }
//
// // Check if message contains a notification payload.
// if (remoteMessage.getNotification() != null) {
// Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
// }
//
// // Also if you intend on generating your own notifications as a result of a received FCM
// // message, here is where that should be initiated. See sendNotification method below.
// }
//}
public class MainActivity extends BridgeActivity implements ModifiedMainActivityForSocialLoginPlugin {
// Declare this at class level
private final ActivityResultLauncher<String> requestPermissionLauncher =
registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
if (isGranted) {
Log.i("CompassApp", "Permission granted");
// Permission granted you can show notifications
} else {
Log.i("CompassApp", "Permission denied");
// Permission denied handle gracefully
}
});
private void askNotificationPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // API 33
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED) {
// Permission not yet granted; request it
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS);
}
}
}
public static class NativeBridge {
@JavascriptInterface
public boolean isNativeApp() {
return true;
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// String data = intent.getDataString();
String endpoint = intent.getStringExtra("endpoint");
Log.i("CompassApp", "onNewIntent called with endpoint: " + endpoint);
if (endpoint != null) {
Log.i("CompassApp", "redirecting to endpoint: " + endpoint);
try {
String payload = new JSONObject().put("endpoint", endpoint).toString();
Log.i("CompassApp", "Payload: " + payload);
bridge.getWebView().post(() -> bridge.getWebView().evaluateJavascript("bridgeRedirect(" + payload + ");", null));
} catch (JSONException e) {
Log.i("CompassApp", "Failed to encode JSON payload", e);
}
} else {
Log.i("CompassApp", "No relevant data");
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i("CompassApp", "onCreate called");
super.onCreate(savedInstanceState);
WebView webView = this.bridge.getWebView();
webView.setWebViewClient(new BridgeWebViewClient(this.bridge));
WebView.setWebContentsDebuggingEnabled(true);
// Set a recognizable User-Agent (always reliable)
WebSettings settings = webView.getSettings();
settings.setUserAgentString(settings.getUserAgentString() + " CompassAppWebView");
settings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new NativeBridge(), "AndroidBridge");
registerPlugin(PushNotificationsPlugin.class);
// Initialize the Bridge with Push Notifications plugin
// this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
// add(com.getcapacitor.plugin.PushNotifications.class);
// }});
askNotificationPermission();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode >= GoogleProvider.REQUEST_AUTHORIZE_GOOGLE_MIN && requestCode < GoogleProvider.REQUEST_AUTHORIZE_GOOGLE_MAX) {
PluginHandle pluginHandle = getBridge().getPlugin("SocialLogin");
if (pluginHandle == null) {
Log.i("CompassApp", "SocialLogin login handle is null");
return;
}
Plugin plugin = pluginHandle.getInstance();
if (!(plugin instanceof SocialLoginPlugin)) {
Log.i("CompassApp", "SocialLogin plugin instance is not SocialLoginPlugin");
return;
}
Log.i("CompassApp", "handleGoogleLoginIntent");
((SocialLoginPlugin) plugin).handleGoogleLoginIntent(requestCode, data);
}
}
// This function will never be called, leave it empty
@Override
public void IHaveModifiedTheMainActivityForTheUseWithSocialLoginPlugin() {
}
}

View File

@@ -0,0 +1,34 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeColor="#00000000"
android:strokeWidth="1">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeColor="#00000000"
android:strokeWidth="1" />
</vector>

View File

@@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#26A69A"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background>
<inset android:drawable="@mipmap/ic_launcher_background" android:inset="16.7%" />
</background>
<foreground>
<inset android:drawable="@mipmap/ic_launcher_foreground" android:inset="16.7%" />
</foreground>
</adaptive-icon>

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background>
<inset android:drawable="@mipmap/ic_launcher_background" android:inset="16.7%" />
</background>
<foreground>
<inset android:drawable="@mipmap/ic_launcher_foreground" android:inset="16.7%" />
</foreground>
</adaptive-icon>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FFFFFF</color>
</resources>

View File

@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">Compass</string>
<string name="title_activity_main">Compass</string>
<string name="package_name">com.compassconnections.app</string>
<string name="custom_url_scheme">com.compassconnections.app</string>
</resources>

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowTranslucentStatus">true</item>
</style>
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="android:background">@drawable/splash</item>
</style>
</resources>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="." />
<cache-path name="my_cache_images" path="." />
</paths>

View File

@@ -0,0 +1,18 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}

29
android/build.gradle Normal file
View File

@@ -0,0 +1,29 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.13.0'
classpath 'com.google.gms:google-services:4.4.4'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply from: "variables.gradle"
allprojects {
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

View File

@@ -0,0 +1,21 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
include ':capacitor-app'
project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/android')
include ':capacitor-keyboard'
project(':capacitor-keyboard').projectDir = new File('../node_modules/@capacitor/keyboard/android')
include ':capacitor-push-notifications'
project(':capacitor-push-notifications').projectDir = new File('../node_modules/@capacitor/push-notifications/android')
include ':capacitor-status-bar'
project(':capacitor-status-bar').projectDir = new File('../node_modules/@capacitor/status-bar/android')
include ':capawesome-capacitor-live-update'
project(':capawesome-capacitor-live-update').projectDir = new File('../node_modules/@capawesome/capacitor-live-update/android')
include ':capgo-capacitor-social-login'
project(':capgo-capacitor-social-login').projectDir = new File('../node_modules/@capgo/capacitor-social-login/android')

22
android/gradle.properties Normal file
View File

@@ -0,0 +1,22 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true

View File

Binary file not shown.

View File

@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

252
android/gradlew vendored Executable file
View File

@@ -0,0 +1,252 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
android/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

5
android/settings.gradle Normal file
View File

@@ -0,0 +1,5 @@
include ':app'
include ':capacitor-cordova-android-plugins'
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
apply from: 'capacitor.settings.gradle'

16
android/variables.gradle Normal file
View File

@@ -0,0 +1,16 @@
ext {
minSdkVersion = 23
compileSdkVersion = 35
targetSdkVersion = 35
androidxActivityVersion = '1.9.2'
androidxAppCompatVersion = '1.7.0'
androidxCoordinatorLayoutVersion = '1.2.0'
androidxCoreVersion = '1.15.0'
androidxFragmentVersion = '1.8.4'
coreSplashScreenVersion = '1.0.1'
androidxWebkitVersion = '1.12.1'
junitVersion = '4.13.2'
androidxJunitVersion = '1.2.1'
androidxEspressoCoreVersion = '3.6.1'
cordovaAndroidVersion = '10.1.1'
}

View File

@@ -27,6 +27,12 @@ gcloud auth login
gcloud config set project YOUR_PROJECT_ID
```
You also need `opentofu` and `docker`. Try running this (from root) on Linux or macOS for a faster install:
```bash
./script/setup.sh
```
If it doesn't work, you can install them manually (google how to install `opentofu` and `docker` for your OS).
### Setup
This section is only for the people who are creating a server from scratch, for instance for a forked project.

View File

@@ -0,0 +1,31 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
rootDir: '.',
testMatch: [
"<rootDir>/tests/**/*.test.ts",
"<rootDir>/tests/**/*.spec.ts"
],
moduleNameMapper: {
"^api/(.*)$": "<rootDir>/src/$1",
"^shared/(.*)$": "<rootDir>/../shared/src/$1",
"^common/(.*)$": "<rootDir>/../../common/src/$1",
"^email/(.*)$": "<rootDir>/../email/emails/$1"
},
moduleFileExtensions: ["ts", "js", "json"],
clearMocks: true,
globals: {
'ts-jest': {
tsconfig: "<rootDir>/tsconfig.test.json"
}
},
collectCoverageFrom: [
"src/**/*.{ts,tsx}",
"!src/**/*.d.ts"
],
};

View File

@@ -11,16 +11,18 @@
"build": "yarn compile && yarn dist:clean && yarn dist:copy",
"build:fast": "yarn compile && yarn dist:copy",
"clean": "rm -rf lib && (cd ../../common && rm -rf lib) && (cd ../shared && rm -rf lib) && (cd ../email && rm -rf lib)",
"compile": "tsc -b && tsc-alias && (cd ../../common && tsc-alias) && (cd ../shared && tsc-alias) && (cd ../email && tsc-alias)",
"compile": "tsc -b && tsc-alias && (cd ../../common && tsc-alias) && (cd ../shared && tsc-alias) && (cd ../email && tsc-alias) && cp -r src/public/ lib/",
"debug": "nodemon -r tsconfig-paths/register --watch src -e ts --watch ../../common/src --watch ../shared/src --exec \"yarn build && node --inspect-brk src/serve.ts\"",
"dist": "yarn dist:clean && yarn dist:copy",
"dist:clean": "rm -rf dist && mkdir -p dist/common/lib dist/backend/shared/lib dist/backend/api/lib dist/backend/email/lib",
"dist:copy": "rsync -a --delete ../../common/lib/ dist/common/lib && rsync -a --delete ../shared/lib/ dist/backend/shared/lib && rsync -a --delete ../email/lib/ dist/backend/email/lib && rsync -a --delete ./lib/* dist/backend/api/lib && cp ../../yarn.lock dist && cp package.json dist && cp package.json dist/backend/api",
"dist:copy": "rsync -a --delete ../../common/lib/ dist/common/lib && rsync -a --delete ../shared/lib/ dist/backend/shared/lib && rsync -a --delete ../email/lib/ dist/backend/email/lib && rsync -a --delete ./lib/* dist/backend/api/lib && cp ../../yarn.lock dist && cp package.json dist && cp package.json dist/backend/api",
"watch": "tsc -w",
"verify": "yarn --cwd=../.. verify",
"verify:dir": "npx eslint . --max-warnings 0",
"regen-types": "cd ../supabase && make ENV=prod regen-types",
"regen-types-dev": "cd ../supabase && make ENV=dev regen-types-dev"
"regen-types-dev": "cd ../supabase && make ENV=dev regen-types-dev",
"test": "jest --config jest.config.js",
"test:coverage": "jest --config jest.config.js --coverage"
},
"engines": {
"node": ">=20.0.0"

View File

@@ -13,6 +13,7 @@ import {getCompatibleProfilesHandler} from './compatible-profiles'
import {createComment} from './create-comment'
import {createCompatibilityQuestion} from './create-compatibility-question'
import {setCompatibilityAnswer} from './set-compatibility-answer'
import {deleteCompatibilityAnswer} from './delete-compatibility-answer'
import {createProfile} from './create-profile'
import {createUser} from './create-user'
import {getCompatibilityQuestions} from './get-compatibililty-questions'
@@ -65,6 +66,13 @@ import {OpenAPIV3} from 'openapi-types';
import {version as pkgVersion} from './../package.json'
import {z, ZodFirstPartyTypeKind, ZodTypeAny} from "zod";
import {getUser} from "api/get-user";
import {localSendTestEmail} from "api/test";
import path from "node:path";
import {saveSubscriptionMobile} from "api/save-subscription-mobile";
import {IS_LOCAL} from "common/hosting/constants";
import {editMessage} from "api/edit-message";
import {reactToMessage} from "api/react-to-message";
import {deleteMessage} from "api/delete-message";
// const corsOptions: CorsOptions = {
// origin: ['*'], // Only allow requests from this domain
@@ -119,12 +127,10 @@ const apiErrorHandler: ErrorRequestHandler = (error, _req, res, _next) => {
export const app = express()
app.use(requestMonitoring)
const schemaCache = new WeakMap<ZodTypeAny, any>();
export function zodToOpenApiSchema(
zodObj: ZodTypeAny,
nameHint?: string
): any { // Prevent infinite recursion
export function zodToOpenApiSchema(zodObj: ZodTypeAny,): any {
if (schemaCache.has(zodObj)) {
return schemaCache.get(zodObj);
}
@@ -140,19 +146,19 @@ export function zodToOpenApiSchema(
switch (typeName) {
case 'ZodString':
schema = { type: 'string' };
schema = {type: 'string'};
break;
case 'ZodNumber':
schema = { type: 'number' };
schema = {type: 'number'};
break;
case 'ZodBoolean':
schema = { type: 'boolean' };
schema = {type: 'boolean'};
break;
case 'ZodEnum':
schema = { type: 'string', enum: def.values };
schema = {type: 'string', enum: def.values};
break;
case 'ZodArray':
schema = { type: 'array', items: zodToOpenApiSchema(def.type) };
schema = {type: 'array', items: zodToOpenApiSchema(def.type)};
break;
case 'ZodObject': {
const shape = def.shape();
@@ -161,14 +167,14 @@ export function zodToOpenApiSchema(
for (const key in shape) {
const child = shape[key];
properties[key] = zodToOpenApiSchema(child, key);
properties[key] = zodToOpenApiSchema(child);
if (!child.isOptional()) required.push(key);
}
schema = {
type: 'object',
properties,
...(required.length ? { required } : {}),
...(required.length ? {required} : {}),
};
break;
}
@@ -181,14 +187,11 @@ export function zodToOpenApiSchema(
case 'ZodIntersection': {
const left = zodToOpenApiSchema(def.left);
const right = zodToOpenApiSchema(def.right);
schema = { allOf: [left, right] };
schema = {allOf: [left, right]};
break;
}
case 'ZodLazy':
// Recursive schema: use a $ref placeholder name
schema = {
$ref: `#/components/schemas/${nameHint ?? 'RecursiveType'}`,
};
schema = {type: 'object', description: 'Lazy schema - details omitted'};
break;
case 'ZodUnion':
schema = {
@@ -196,7 +199,7 @@ export function zodToOpenApiSchema(
};
break;
default:
schema = { type: 'string' }; // fallback for unhandled
schema = {type: 'string'}; // fallback for unhandled
}
Object.assign(placeholder, schema);
@@ -291,15 +294,15 @@ const swaggerDocument: OpenAPIV3.Document = {
scheme: 'bearer',
bearerFormat: 'JWT',
},
ApiKeyAuth: {
type: 'apiKey',
in: 'header',
name: 'x-api-key',
},
},
}
} as OpenAPIV3.Document;
const rootPath = pathWithPrefix("/")
app.get(rootPath, swaggerUi.setup(swaggerDocument))
app.use(rootPath, swaggerUi.serve)
// Triggers Missing parameter name at index 3: *; visit https://git.new/pathToRegexpError for info
// May not be necessary
// app.options('*', allowCorsUnrestricted)
@@ -339,6 +342,7 @@ const handlers: { [k in APIPath]: APIHandler<k> } = {
'hide-comment': hideComment,
'create-compatibility-question': createCompatibilityQuestion,
'set-compatibility-answer': setCompatibilityAnswer,
'delete-compatibility-answer': deleteCompatibilityAnswer,
'create-vote': createVote,
'vote': vote,
'contact': contact,
@@ -356,8 +360,13 @@ const handlers: { [k in APIPath]: APIHandler<k> } = {
'get-messages-count': getMessagesCount,
'set-last-online-time': setLastOnlineTime,
'save-subscription': saveSubscription,
'save-subscription-mobile': saveSubscriptionMobile,
'create-bookmarked-search': createBookmarkedSearch,
'delete-bookmarked-search': deleteBookmarkedSearch,
'delete-message': deleteMessage,
'edit-message': editMessage,
'react-to-message': reactToMessage,
// 'auth-google': authGoogle,
}
Object.entries(handlers).forEach(([path, handler]) => {
@@ -407,6 +416,108 @@ app.post(pathWithPrefix("/internal/send-search-notifications"),
}
);
const responses = {
200: {
description: "Request successful",
content: {
"application/json": {
schema: {
type: "object",
properties: {
status: {type: "string", example: "success"}
},
},
},
},
},
401: {
description: "Unauthorized (e.g., invalid or missing API key)",
content: {
"application/json": {
schema: {
type: "object",
properties: {
error: {type: "string", example: "Unauthorized"},
},
},
},
},
},
500: {
description: "Internal server error during request processing",
content: {
"application/json": {
schema: {
type: "object",
properties: {
error: {type: "string", example: "Internal server error"},
},
},
},
},
},
};
swaggerDocument.paths["/internal/send-search-notifications"] = {
post: {
summary: "Trigger daily search notifications",
description:
"Internal endpoint used by Compass schedulers to send daily notifications for bookmarked searches. Requires a valid `x-api-key` header.",
tags: ["Internal"],
security: [
{
ApiKeyAuth: [],
},
],
requestBody: {
required: false,
},
responses: responses,
},
} as any
// Local Endpoints
if (IS_LOCAL) {
app.post(pathWithPrefix("/local/send-test-email"),
async (req, res) => {
if (!IS_LOCAL) {
return res.status(401).json({error: "Unauthorized"});
}
try {
const result = await localSendTestEmail()
return res.status(200).json(result)
} catch (err) {
return res.status(500).json({error: err});
}
}
);
swaggerDocument.paths["/local/send-test-email"] = {
post: {
summary: "Send a test email",
description: "Local endpoint to send a test email.",
tags: ["Local"],
requestBody: {
required: false,
},
responses: responses,
},
} as any
}
const rootPath = pathWithPrefix("/")
app.get(
rootPath,
swaggerUi.setup(swaggerDocument, {
customSiteTitle: 'Compass API Docs',
customCssUrl: '/swagger.css',
}),
)
app.use(rootPath, swaggerUi.serve)
app.use(express.static(path.join(__dirname, 'public')));
app.use(allowCorsUnrestricted, (req, res) => {
if (req.method === 'OPTIONS') {

View File

@@ -0,0 +1,37 @@
// import {APIError, APIHandler} from './helpers/endpoint'
// import {GOOGLE_CLIENT_ID} from "common/constants";
// import {REDIRECT_URI} from "common/envs/constants";
//
// export const authGoogle: APIHandler<'auth-google'> = async (
// {code},
// _auth
// ) => {
// console.log('Google Auth Codes:', code)
// if (!code) return {success: false, result: {}}
//
// const body = {
// client_id: GOOGLE_CLIENT_ID,
// client_secret: process.env.GOOGLE_CLIENT_SECRET!,
// code: code as string,
// grant_type: 'authorization_code',
// redirect_uri: REDIRECT_URI,
// };
// console.log('Body:', body)
// const tokenRes = await fetch('https://oauth2.googleapis.com/token', {
// method: 'POST',
// headers: {'Content-Type': 'application/x-www-form-urlencoded'},
// body: new URLSearchParams(body),
// });
//
// const tokens = await tokenRes.json();
// if (tokens.error) {
// console.error('Google token error:', tokens);
// throw new APIError(400, 'Google token error: ' + JSON.stringify(tokens))
// }
// console.log('Google Tokens:', tokens);
//
// return {
// success: true,
// result: {tokens},
// }
// }

View File

@@ -25,8 +25,13 @@ export const contact: APIHandler<'contact'> = async (
const continuation = async () => {
try {
let user = null
if (userId) {
user = await pg.oneOrNone(` select name from users where id = $1 `, [userId])
}
const md = jsonToMarkdown(content)
const message: string = `**New Contact Message**\n${md}`
const tile = user ? `New message from ${user.name}` : 'New message'
const message: string = `**${tile}**\n${md}`
await sendDiscordMessage(message, 'contact')
} catch (e) {
console.error('Failed to send discord contact', e)

View File

@@ -4,6 +4,24 @@ import {insertNotificationToSupabase} from 'shared/supabase/notifications'
import {tryCatch} from "common/util/try-catch";
import {Row} from "common/supabase/utils";
export const createAndroidTestNotifications = async () => {
const createdTime = Date.now();
const id = `android-test-${createdTime}`
const notification: Notification = {
id,
userId: 'todo',
createdTime: createdTime,
isSeen: false,
sourceType: 'info',
sourceUpdateType: 'created',
sourceSlug: '/contact',
sourceUserAvatarUrl: 'https://firebasestorage.googleapis.com/v0/b/compass-130ba.firebasestorage.app/o/misc%2Fcompass-192.png?alt=media&token=9fd251c5-fc43-4375-b629-1a8f4bbe8185',
title: 'Android App Ready for Review — Help Us Unlock the Google Play Release',
sourceText: 'To release our app, Google requires a closed test with at least 12 testers for 14 days. Please share your Google Playregistered email address so we can add you as a tester and complete the review process.',
}
return await createNotifications(notification)
}
export const createShareNotifications = async () => {
const createdTime = Date.now();
const id = `share-${createdTime}`

View File

@@ -1,7 +1,7 @@
import { APIError, APIHandler } from 'api/helpers/endpoint'
import { createSupabaseDirectClient } from 'shared/supabase/init'
import { log, getUser } from 'shared/utils'
import { HOUR_MS } from 'common/util/time'
import {HOUR_MS, MINUTE_MS, sleep} from 'common/util/time'
import { removePinnedUrlFromPhotoUrls } from 'shared/profiles/parse-photos'
import { track } from 'shared/analytics'
import { updateUser } from 'shared/supabase/users'
@@ -41,7 +41,7 @@ export const createProfile: APIHandler<'create-profile'> = async (body, auth) =>
throw new APIError(500, 'Error creating user')
}
log('Created user', data)
log('Created profile', data)
const continuation = async () => {
try {
@@ -50,6 +50,10 @@ export const createProfile: APIHandler<'create-profile'> = async (body, auth) =>
console.error('Failed to track create profile', e)
}
try {
// Let the user fill in the optional form with all their info and pictures before notifying discord of their arrival.
// So we can sse their full profile as soon as we get the notif on discord. And that allows OG to pull their pic for the link preview.
// Regardless, you need to wait for at least 5 seconds that the profile is fully in the db—otherwise ISR may cache "profile not created yet"
await sleep(10 * MINUTE_MS)
let message: string = `[**${user.name}**](https://www.compassmeet.com/${user.username}) just created a profile`
if (body.bio) {
const bioText = jsonToMarkdown(body.bio)

View File

@@ -7,7 +7,7 @@ import {APIError, APIHandler} from './helpers/endpoint'
import {getDefaultNotificationPreferences} from 'common/user-notification-preferences'
import {removeUndefinedProps} from 'common/util/object'
import {generateAvatarUrl} from 'shared/helpers/generate-and-update-avatar-urls'
import {IS_LOCAL, RESERVED_PATHS} from 'common/envs/constants'
import {RESERVED_PATHS} from 'common/envs/constants'
import {getUser, getUserByUsername, log} from 'shared/utils'
import {createSupabaseDirectClient} from 'shared/supabase/init'
import {insert} from 'shared/supabase/utils'
@@ -15,6 +15,7 @@ import {convertPrivateUser, convertUser} from 'common/supabase/users'
import {getBucket} from "shared/firebase-utils";
import {sendWelcomeEmail} from "email/functions/helpers";
import {setLastOnlineTimeUser} from "api/set-last-online-time";
import {IS_LOCAL} from "common/hosting/constants";
export const createUser: APIHandler<'create-user'> = async (
props,

View File

@@ -18,6 +18,7 @@ export const createVote: APIHandler<
title,
description,
is_anonymous: isAnonymous,
status: 'voting_open',
})
)

View File

@@ -0,0 +1,30 @@
import {APIHandler} from 'api/helpers/endpoint'
import {createSupabaseDirectClient} from 'shared/supabase/init'
import {APIError} from 'common/api/utils'
export const deleteCompatibilityAnswer: APIHandler<'delete-compatibility-answer'> = async (
{id}, auth) => {
const pg = createSupabaseDirectClient()
// Verify user is the answer author
const item = await pg.oneOrNone(
`SELECT *
FROM compatibility_answers
WHERE id = $1
AND creator_id = $2`,
[id, auth.uid]
)
if (!item) {
throw new APIError(404, 'Item not found')
}
// Delete the answer
await pg.none(
`DELETE
FROM compatibility_answers
WHERE id = $1
AND creator_id = $2`,
[id, auth.uid]
)
}

View File

@@ -4,18 +4,11 @@ import {createSupabaseDirectClient} from 'shared/supabase/init'
import * as admin from "firebase-admin";
import {deleteUserFiles} from "shared/firebase-utils";
export const deleteMe: APIHandler<'me/delete'> = async (body, auth) => {
const {username} = body
export const deleteMe: APIHandler<'me/delete'> = async (_, auth) => {
const user = await getUser(auth.uid)
if (!user) {
throw new APIError(401, 'Your account was not found')
}
if (user.username != username) {
throw new APIError(
400,
`Incorrect username. You are logged in as ${user.username}. Are you sure you want to delete this account?`
)
}
const userId = user.id
if (!userId) {
throw new APIError(400, 'Invalid user ID')
@@ -25,11 +18,6 @@ export const deleteMe: APIHandler<'me/delete'> = async (body, auth) => {
const pg = createSupabaseDirectClient()
await pg.none('DELETE FROM users WHERE id = $1', [userId])
// Should cascade delete in other tables
// await pg.none('DELETE FROM private_users WHERE id = $1', [userId])
// await pg.none('DELETE FROM profiles WHERE user_id = $1', [userId])
// await pg.none('DELETE FROM bookmarked_searches WHERE creator_id = $1', [userId])
// await pg.none('DELETE FROM compatibility_answers WHERE creator_id = $1', [userId])
// May need to also delete from other tables in the future (such as messages, compatibility responses, etc.)
// Delete user files from Firebase Storage
await deleteUserFiles(user.username)

View File

@@ -0,0 +1,64 @@
import {APIError, APIHandler} from './helpers/endpoint'
import {createSupabaseDirectClient} from 'shared/supabase/init'
import {broadcastPrivateMessages} from "api/helpers/private-messages";
// const DELETED_MESSAGE_CONTENT: JSONContent = {
// type: 'doc',
// content: [
// {
// type: 'paragraph',
// content: [
// {
// type: 'text',
// text: '[deleted]',
// },
// ],
// },
// ],
// }
export const deleteMessage: APIHandler<'delete-message'> = async ({messageId}, auth) => {
const pg = createSupabaseDirectClient()
// Verify user is the message author and message is not too old
const message = await pg.oneOrNone(
`SELECT *
FROM private_user_messages
WHERE id = $1
AND user_id = $2`,
[messageId, auth.uid]
)
if (!message) {
throw new APIError(404, 'Message not found')
}
// Soft delete the message
// await pg.none(
// `UPDATE private_user_messages
// SET deleted = TRUE,
// content = $2::jsonb,
// ciphertext = NULL,
// iv = NULL,
// tag = NULL
// WHERE id = $1`,
// [messageId, DELETED_MESSAGE_CONTENT]
// )
// Hard delete the message
await pg.none(
`DELETE
FROM private_user_messages
WHERE id = $1
AND user_id = $2`,
[messageId, auth.uid]
)
void broadcastPrivateMessages(pg, message.channel_id, auth.uid)
.catch((err) => {
console.error('broadcastPrivateMessages failed', err)
})
return {success: true}
}

View File

@@ -0,0 +1,44 @@
import {APIError, APIHandler} from './helpers/endpoint'
import {createSupabaseDirectClient} from 'shared/supabase/init'
import {encryptMessage} from "shared/encryption";
import {broadcastPrivateMessages} from "api/helpers/private-messages";
export const editMessage: APIHandler<'edit-message'> = async ({messageId, content}, auth) => {
const pg = createSupabaseDirectClient()
// Verify user is the message author and message is not too old
const message = await pg.oneOrNone(
`SELECT *
FROM private_user_messages
WHERE id = $1
AND user_id = $2
-- AND created_time > NOW() - INTERVAL '1 day'
AND deleted = FALSE`,
[messageId, auth.uid]
)
if (!message) {
throw new APIError(404, 'Message not found or cannot be edited')
}
const plaintext = JSON.stringify(content)
const {ciphertext, iv, tag} = encryptMessage(plaintext)
await pg.none(
`UPDATE private_user_messages
SET ciphertext = $1,
iv = $2,
tag = $3,
is_edited = TRUE,
edited_at = NOW()
WHERE id = $4`,
[ciphertext, iv, tag, messageId]
)
void broadcastPrivateMessages(pg, message.channel_id, auth.uid)
.catch((err) => {
console.error('broadcastPrivateMessages failed', err)
})
return {success: true}
}

View File

@@ -1,7 +1,7 @@
import {APIHandler} from './helpers/endpoint'
import {createSupabaseDirectClient} from "shared/supabase/init";
export const getMessagesCount: APIHandler<'get-messages-count'> = async (_, auth) => {
export const getMessagesCount: APIHandler<'get-messages-count'> = async (_, _auth) => {
const pg = createSupabaseDirectClient()
const result = await pg.one(
`

View File

@@ -22,6 +22,10 @@ export type profileQueryType = {
pref_romantic_styles?: String[] | undefined,
diet?: String[] | undefined,
political_beliefs?: String[] | undefined,
mbti?: String[] | undefined,
relationship_status?: String[] | undefined,
languages?: String[] | undefined,
religion?: String[] | undefined,
wants_kids_strength?: number | undefined,
has_kids?: number | undefined,
is_smoker?: boolean | undefined,
@@ -57,6 +61,10 @@ export const loadProfiles = async (props: profileQueryType) => {
pref_romantic_styles,
diet,
political_beliefs,
mbti,
relationship_status,
languages,
religion,
wants_kids_strength,
has_kids,
is_smoker,
@@ -87,8 +95,9 @@ export const loadProfiles = async (props: profileQueryType) => {
const profiles = compatibleProfiles.filter(
(l) =>
(!name || l.user.name.toLowerCase().includes(name.toLowerCase())) &&
(!genders || genders.includes(l.gender)) &&
(!genders || genders.includes(l.gender ?? '')) &&
(!education_levels || education_levels.includes(l.education_level ?? '')) &&
(!mbti || mbti.includes(l.mbti ?? '')) &&
(!pref_gender || intersection(pref_gender, l.pref_gender).length) &&
(!pref_age_min || (l.age ?? MAX_INT) >= pref_age_min) &&
(!pref_age_max || (l.age ?? MIN_INT) <= pref_age_max) &&
@@ -102,6 +111,12 @@ export const loadProfiles = async (props: profileQueryType) => {
intersection(diet, l.diet).length) &&
(!political_beliefs ||
intersection(political_beliefs, l.political_beliefs).length) &&
(!relationship_status ||
intersection(relationship_status, l.relationship_status).length) &&
(!languages ||
intersection(languages, l.languages).length) &&
(!religion ||
intersection(religion, l.religion).length) &&
(!wants_kids_strength ||
wants_kids_strength == -1 ||
!l.wants_kids_strength ||
@@ -114,6 +129,7 @@ export const loadProfiles = async (props: profileQueryType) => {
(has_kids == 0 && !l.has_kids) ||
(l.has_kids && l.has_kids > 0)) &&
(is_smoker === undefined || l.is_smoker === is_smoker) &&
(!l.disabled) &&
(l.id.toString() != skipId) &&
(!geodbCityIds ||
(l.geodb_city_id && geodbCityIds.includes(l.geodb_city_id))) &&
@@ -145,6 +161,7 @@ export const loadProfiles = async (props: profileQueryType) => {
join('users on users.id = profiles.user_id'),
leftJoin(userActivityJoin),
where('looking_for_matches = true'),
where(`profiles.disabled != true`),
// where(`pinned_url is not null and pinned_url != ''`),
where(
`(data->>'isBannedFromPosting' != 'true' or data->>'isBannedFromPosting' is null)`
@@ -160,6 +177,8 @@ export const loadProfiles = async (props: profileQueryType) => {
education_levels?.length && where(`education_level = ANY($(education_levels))`, {education_levels}),
mbti?.length && where(`mbti = ANY($(mbti))`, {mbti}),
pref_gender?.length &&
where(`pref_gender is NULL or pref_gender = '{}' OR pref_gender && $(pref_gender)`, {pref_gender}),
@@ -199,6 +218,24 @@ export const loadProfiles = async (props: profileQueryType) => {
{political_beliefs}
),
relationship_status?.length &&
where(
`relationship_status IS NULL OR relationship_status = '{}' OR relationship_status && $(relationship_status)`,
{relationship_status}
),
languages?.length &&
where(
`languages && $(languages)`,
{languages}
),
religion?.length &&
where(
`religion IS NULL OR religion = '{}' OR religion && $(religion)`,
{religion}
),
!!wants_kids_strength &&
wants_kids_strength !== -1 &&
where(

View File

@@ -13,9 +13,11 @@ import {sendNewMessageEmail} from 'email/functions/helpers'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'
import webPush from 'web-push';
import {parseJsonContentToText} from "common/util/parse";
import {encryptMessage} from "shared/encryption";
import webPush from 'web-push'
import {parseJsonContentToText} from "common/util/parse"
import {encryptMessage} from "shared/encryption"
import * as admin from 'firebase-admin'
import {TokenMessage} from "firebase-admin/lib/messaging/messaging-api";
dayjs.extend(utc)
dayjs.extend(timezone)
@@ -29,17 +31,17 @@ export const leaveChatContent = (userName: string) => ({
},
],
})
export const joinChatContent = (userName: string) => {
return {
type: 'doc',
content: [
{
type: 'paragraph',
content: [{text: `${userName} joined the chat!`, type: 'text'}],
},
],
}
}
// export const joinChatContent = (userName: string) => {
// return {
// type: 'doc',
// content: [
// {
// type: 'paragraph',
// content: [{text: `${userName} joined the chat!`, type: 'text'}],
// },
// ],
// }
// }
export const insertPrivateMessage = async (
content: Json,
@@ -48,8 +50,8 @@ export const insertPrivateMessage = async (
visibility: ChatVisibility,
pg: SupabaseDirectClient
) => {
const plaintext = JSON.stringify(content);
const {ciphertext, iv, tag} = encryptMessage(plaintext);
const plaintext = JSON.stringify(content)
const {ciphertext, iv, tag} = encryptMessage(plaintext)
const lastMessage = await pg.one(
`insert into private_user_messages (ciphertext, iv, tag, channel_id, user_id, visibility)
values ($1, $2, $3, $4, $5, $6)
@@ -88,6 +90,27 @@ export const addUsersToPrivateMessageChannel = async (
)
}
export async function broadcastPrivateMessages(
pg: SupabaseDirectClient,
channelId: number,
userId: string,
) {
const otherUserIds = await pg.map<string>(
`select user_id
from private_user_message_channel_members
where channel_id = $1
and user_id != $2
and status != 'left'
`,
[channelId, userId],
(r) => r.user_id
)
otherUserIds.concat(userId).forEach((otherUserId) => {
broadcast(`private-user-messages/${otherUserId}`, {})
})
return otherUserIds;
}
export const createPrivateUserMessageMain = async (
creator: User,
channelId: number,
@@ -115,26 +138,13 @@ export const createPrivateUserMessageMain = async (
channel_id: channelId,
user_id: creator.id,
}
const otherUserIds = await pg.map<string>(
`select user_id
from private_user_message_channel_members
where channel_id = $1
and user_id != $2
and status != 'left'
`,
[channelId, creator.id],
(r) => r.user_id
)
otherUserIds.concat(creator.id).forEach((otherUserId) => {
broadcast(`private-user-messages/${otherUserId}`, {})
})
const otherUserIds = await broadcastPrivateMessages(pg, channelId, creator.id);
// Fire and forget safely
void notifyOtherUserInChannelIfInactive(channelId, creator, content, pg)
.catch((err) => {
console.error('notifyOtherUserInChannelIfInactive failed', err)
});
})
track(creator.id, 'send private message', {
channelId,
@@ -162,49 +172,24 @@ const notifyOtherUserInChannelIfInactive = async (
// We're only sending notifs for 1:1 channels
if (!otherUserIds || otherUserIds.length > 1) return
const otherUserId = first(otherUserIds)
if (!otherUserId) return
const receiverId = first(otherUserIds)?.user_id
if (!receiverId) return
// TODO: notification only for active user
const otherUser = await getUser(otherUserId.user_id)
console.debug('otherUser:', otherUser)
if (!otherUser) return
const receiver = await getUser(receiverId)
console.debug('receiver:', receiver)
if (!receiver) return
// Push notif
webPush.setVapidDetails(
'mailto:hello@compassmeet.com',
process.env.VAPID_PUBLIC_KEY!,
process.env.VAPID_PRIVATE_KEY!
);
// Push notifs
const textContent = parseJsonContentToText(content)
// Retrieve subscription from the database
const subscriptions = await getSubscriptionsFromDB(otherUser.id, pg);
for (const subscription of subscriptions) {
try {
const payload = JSON.stringify({
title: `${creator.name}`,
body: textContent,
url: `/messages/${channelId}`,
})
console.log('Sending notification to:', subscription.endpoint, payload);
await webPush.sendNotification(subscription, payload);
} catch (err: any) {
console.log('Failed to send notification', err);
if (err.statusCode === 410 || err.statusCode === 404) {
console.warn('Removing expired subscription', subscription.endpoint);
await pg.none(
`DELETE
FROM push_subscriptions
WHERE endpoint = $1
AND user_id = $2`,
[subscription.endpoint, otherUser.id]
);
} else {
console.error('Push failed', err);
}
}
const payload = {
title: `${creator.name}`,
body: textContent,
url: `/messages/${channelId}`,
}
await sendWebNotifications(pg, receiverId, JSON.stringify(payload))
await sendMobileNotifications(pg, receiverId, payload)
const startOfDay = dayjs()
.tz('America/Los_Angeles')
@@ -220,9 +205,9 @@ const notifyOtherUserInChannelIfInactive = async (
[channelId, creator.id, startOfDay]
)
log('previous messages this day', previousMessagesThisDayBetweenTheseUsers)
if (previousMessagesThisDayBetweenTheseUsers.count > 0) return
if (previousMessagesThisDayBetweenTheseUsers.count > 1) return
await createNewMessageNotification(creator, otherUser, channelId)
await createNewMessageNotification(creator, receiver, channelId)
}
const createNewMessageNotification = async (
@@ -237,9 +222,38 @@ const createNewMessageNotification = async (
}
export async function getSubscriptionsFromDB(
async function sendWebNotifications(
pg: SupabaseDirectClient,
userId: string,
payload: string,
) {
webPush.setVapidDetails(
'mailto:hello@compassmeet.com',
process.env.VAPID_PUBLIC_KEY!,
process.env.VAPID_PRIVATE_KEY!
)
// Retrieve subscription from the database
const subscriptions = await getSubscriptionsFromDB(pg, userId)
for (const subscription of subscriptions) {
try {
console.log('Sending notification to:', subscription.endpoint, payload)
await webPush.sendNotification(subscription, payload)
} catch (err: any) {
console.log('Failed to send notification', err)
if (err.statusCode === 410 || err.statusCode === 404) {
console.warn('Removing expired subscription', subscription.endpoint)
await removeSubscription(pg, subscription.endpoint, userId)
} else {
console.error('Push failed', err)
}
}
}
}
export async function getSubscriptionsFromDB(
pg: SupabaseDirectClient,
userId: string,
pg: SupabaseDirectClient
) {
try {
const subscriptions = await pg.manyOrNone(`
@@ -247,14 +261,127 @@ export async function getSubscriptionsFromDB(
from push_subscriptions
where user_id = $1
`, [userId]
);
)
return subscriptions.map(sub => ({
endpoint: sub.endpoint,
keys: sub.keys,
}));
}))
} catch (err) {
console.error('Error fetching subscriptions', err);
return [];
console.error('Error fetching subscriptions', err)
return []
}
}
async function removeSubscription(
pg: SupabaseDirectClient,
endpoint: any,
userId: string,
) {
await pg.none(
`DELETE
FROM push_subscriptions
WHERE endpoint = $1
AND user_id = $2`,
[endpoint, userId]
)
}
async function removeMobileSubscription(
pg: SupabaseDirectClient,
token: any,
userId: string,
) {
await pg.none(
`DELETE
FROM push_subscriptions_mobile
WHERE token = $1
AND user_id = $2`,
[token, userId]
)
}
async function sendMobileNotifications(
pg: SupabaseDirectClient,
userId: string,
payload: PushPayload,
) {
const subscriptions = await getMobileSubscriptionsFromDB(pg, userId)
for (const subscription of subscriptions) {
await sendPushToToken(pg, userId, subscription.token, payload)
}
}
interface PushPayload {
title: string
body: string
url: string
data?: Record<string, string>
}
export async function sendPushToToken(
pg: SupabaseDirectClient,
userId: string,
token: string,
payload: PushPayload,
) {
const message: TokenMessage = {
token,
android: {
notification: {
title: payload.title,
body: payload.body,
},
},
data: {
endpoint: payload.url,
},
}
try {
// Fine to create at each call, as it's a cached singleton
const fcm = admin.messaging()
console.log('Sending notification to:', token, message)
const response = await fcm.send(message)
console.log('Push sent successfully:', response)
return response
} catch (err: unknown) {
// Check if it's a Firebase Messaging error
if (err instanceof Error && 'code' in err) {
const firebaseError = err as { code: string; message: string }
console.warn('Firebase error:', firebaseError.code, firebaseError.message)
// Handle specific error cases here if needed
// For example, if token is no longer valid:
if (firebaseError.code === 'messaging/registration-token-not-registered' ||
firebaseError.code === 'messaging/invalid-argument') {
console.warn('Removing invalid FCM token')
await removeMobileSubscription(pg, token, userId)
}
} else {
console.error('Unknown error:', err)
}
}
return
}
export async function getMobileSubscriptionsFromDB(
pg: SupabaseDirectClient,
userId: string,
) {
try {
const subscriptions = await pg.manyOrNone(`
select token
from push_subscriptions_mobile
where user_id = $1
`, [userId]
)
return subscriptions
} catch (err) {
console.error('Error fetching subscriptions', err)
return []
}
}

View File

@@ -0,0 +1,64 @@
@media (prefers-color-scheme: dark) {
body {
background-color: #1e1e1e !important;
color: #ffffff !important;
}
.swagger-ui p,
h1,
h2,
h3,
h4,
h5,
h6,
label,
.btn,
.parameter__name,
.parameter__type,
.parameter__in,
.response-control-media-type__title,
table thead tr td,
table thead tr th,
.tab li,
.response-col_links,
.opblock-summary-description {
color: #ffffff !important;
}
.swagger-ui .topbar, .opblock-body select, textarea {
background-color: #2b2b2b !important;
color: #ffffff !important;
}
.swagger-ui .opblock {
background-color: #2c2c2c !important;
border-color: #fff !important;
}
.swagger-ui .opblock .opblock-summary-method {
background-color: #1f1f1f !important;
color: #fff !important;
}
.swagger-ui .opblock .opblock-section-header {
background: #1f1f1f !important;
color: #fff !important;
}
.swagger-ui .responses-wrapper {
background-color: #1f1f1f !important;
}
.swagger-ui .response-col_status {
color: #fff !important;
}
.swagger-ui .scheme-container {
background-color: #1f1f1f !important;
}
.swagger-ui .modal-ux, input {
background-color: #1f1f1f !important;
color: #fff !important;
}
.swagger-ui svg path {
fill: white !important;
}
.swagger-ui .close-modal svg {
color: #1e90ff !important;
}
a {
color: #1e90ff !important;
}
}

View File

@@ -0,0 +1,60 @@
import {APIError, APIHandler} from './helpers/endpoint'
import {createSupabaseDirectClient} from 'shared/supabase/init'
import {broadcastPrivateMessages} from "api/helpers/private-messages";
export const reactToMessage: APIHandler<'react-to-message'> = async ({messageId, reaction, toDelete}, auth) => {
const pg = createSupabaseDirectClient()
// Verify user is a member of the channel
const message = await pg.oneOrNone(
`SELECT *
FROM private_user_message_channel_members m
JOIN private_user_messages msg ON msg.channel_id = m.channel_id
WHERE m.user_id = $1
AND msg.id = $2`,
[auth.uid, messageId]
)
if (!message) {
throw new APIError(403, 'Not authorized to react to this message')
}
if (toDelete) {
// Remove the reaction
await pg.none(
`UPDATE private_user_messages
SET reactions = reactions - $1
WHERE id = $2
AND reactions -> $1 ? $3`,
[reaction, messageId, auth.uid]
)
} else {
// Toggle reaction
await pg.none(
`UPDATE private_user_messages
SET reactions =
CASE
WHEN reactions -> $1 IS NOT NULL
THEN reactions - $1
ELSE jsonb_set(
COALESCE(reactions, '{}'::jsonb),
ARRAY [$1],
(
COALESCE(reactions -> $1, '[]'::jsonb) || to_jsonb($2::text)
),
TRUE
)
END
WHERE id = $3`,
[reaction, auth.uid, messageId]
)
}
void broadcastPrivateMessages(pg, message.channel_id, auth.uid)
.catch((err) => {
console.error('broadcastPrivateMessages failed', err)
})
return {success: true}
}

View File

@@ -0,0 +1,28 @@
import {APIError, APIHandler} from './helpers/endpoint'
import {createSupabaseDirectClient} from 'shared/supabase/init'
export const saveSubscriptionMobile: APIHandler<'save-subscription-mobile'> = async (body, auth) => {
const {token} = body
if (!token) {
throw new APIError(400, `Invalid subscription object`)
}
const userId = auth?.uid
try {
const pg = createSupabaseDirectClient()
await pg.none(`
insert into push_subscriptions_mobile(token, platform, user_id)
values ($1, $2, $3)
on conflict(token) do update set platform = excluded.platform,
user_id = excluded.user_id
`,
[token, 'android', userId]
);
return {success: true};
} catch (err) {
console.error('Error saving subscription', err);
throw new APIError(500, `Failed to save subscription`)
}
}

View File

@@ -1,28 +1,20 @@
import { constructPrefixTsQuery } from 'shared/helpers/search'
import {
from,
join,
limit,
orderBy,
renderSql,
select,
where,
} from 'shared/supabase/sql-builder'
import { type APIHandler } from './helpers/endpoint'
import { convertUser } from 'common/supabase/users'
import { createSupabaseDirectClient } from 'shared/supabase/init'
import { toUserAPIResponse } from 'common/api/user-types'
import { uniqBy } from 'lodash'
import {constructPrefixTsQuery} from 'shared/helpers/search'
import {from, limit, orderBy, renderSql, select, where,} from 'shared/supabase/sql-builder'
import {type APIHandler} from './helpers/endpoint'
import {convertUser} from 'common/supabase/users'
import {createSupabaseDirectClient} from 'shared/supabase/init'
import {toUserAPIResponse} from 'common/api/user-types'
import {uniqBy} from 'lodash'
export const searchUsers: APIHandler<'search-users'> = async (props, auth) => {
const { term, page, limit } = props
export const searchUsers: APIHandler<'search-users'> = async (props, _auth) => {
const {term, page, limit} = props
const pg = createSupabaseDirectClient()
const offset = page * limit
// const userId = auth?.uid
// const searchFollowersSQL = getSearchUserSQL({ term, offset, limit, userId })
const searchAllSQL = getSearchUserSQL({ term, offset, limit })
const searchAllSQL = getSearchUserSQL({term, offset, limit})
const [all] = await Promise.all([
// pg.map(searchFollowersSQL, null, convertUser),
pg.map(searchAllSQL, null, convertUser),
@@ -39,7 +31,7 @@ function getSearchUserSQL(props: {
limit: number
userId?: string // search only this user's followers
}) {
const { term } = props
const {term} = props
return renderSql(
// userId
@@ -50,21 +42,21 @@ function getSearchUserSQL(props: {
// where('user_follows.user_id = $1', [userId]),
// ]
// :
[select('*'), from('users')],
[select('*'), from('users')],
term
? [
where(
`name_username_vector @@ websearch_to_tsquery('english', $1)
where(
`name_username_vector @@ websearch_to_tsquery('english', $1)
or name_username_vector @@ to_tsquery('english', $2)`,
[term, constructPrefixTsQuery(term)]
),
[term, constructPrefixTsQuery(term)]
),
orderBy(
`ts_rank(name_username_vector, websearch_to_tsquery($1)) desc,
orderBy(
`ts_rank(name_username_vector, websearch_to_tsquery($1)) desc,
data->>'lastBetTime' desc nulls last`,
[term]
),
]
[term]
),
]
: orderBy(`data->'creatorTraders'->'allTime' desc nulls last`),
limit(props.limit, props.offset)
)

View File

@@ -53,7 +53,7 @@ export const sendSearchNotifications = async () => {
for (const row of searches) {
if (typeof row.search_filters !== 'object') continue;
const { orderBy, ...filters } = (row.search_filters ?? {}) as Record<string, any>
const { orderBy: _, ...filters } = (row.search_filters ?? {}) as Record<string, any>
const props = {
...filters,
skipId: row.creator_id,

View File

@@ -3,7 +3,7 @@ import * as admin from 'firebase-admin'
import {initAdmin} from 'shared/init-admin'
import {loadSecretsToEnv} from 'common/secrets'
import {log} from 'shared/utils'
import {IS_LOCAL} from "common/envs/constants";
import {IS_LOCAL} from "common/hosting/constants";
import {METRIC_WRITER} from 'shared/monitoring/metric-writer'
import {listen as webSocketListen} from 'shared/websockets/server'
@@ -40,4 +40,4 @@ const startupProcess = async () => {
webSocketListen(httpServer, '/ws')
}
startupProcess().then(r => log('Server started successfully'))
startupProcess().then(_r => log('Server started successfully'))

8
backend/api/src/test.ts Normal file
View File

@@ -0,0 +1,8 @@
import {sendTestEmail} from "email/functions/helpers";
export const localSendTestEmail = async () => {
sendTestEmail('hello@compassmeet.com')
.then(() => console.debug('Email sent successfully!'))
.catch((error) => console.error('Failed to send email:', error))
return { message: 'Email sent successfully!'}
}

View File

View File

@@ -0,0 +1,59 @@
import { getUser } from "api/get-user";
import { createSupabaseDirectClient } from "shared/supabase/init";
import { toUserAPIResponse } from "common/api/user-types";
import { convertUser } from "common/supabase/users";
import { APIError } from "common/src/api/utils";
jest.mock("shared/supabase/init");
jest.mock("common/supabase/users");
jest.mock("common/api/utils");
describe('getUser', () =>{
let mockPg: any;
beforeEach(() => {
mockPg = {
oneOrNone: jest.fn(),
};
(createSupabaseDirectClient as jest.Mock).mockReturnValue(mockPg);
jest.clearAllMocks();
});
it('should fetch user successfully by id', async () => {
const mockDbUser = {
created_time: '2025-11-11T16:42:05.188Z',
data: { link: {}, avatarUrl: "", isBannedFromPosting: false },
id: 'feUaIfcxVmJZHJOVVfawLTTPgZiP',
name: 'Franklin Buckridge',
name_username_vector: "'buckridg':2,4 'franklin':1,3",
username: 'Franky_Buck'
};
const mockConvertedUser = {
created_time: new Date(),
id: 'feUaIfcxVmJZHJOVVfawLTTPgZiP',
name: 'Franklin Buckridge',
name_username_vector: "'buckridg':2,4 'franklin':1,3",
username: 'Franky_Buck'
};
const mockApiResponse = {
created_time: '2025-11-11T16:42:05.188Z',
data: { link: {}, avatarUrl: "", isBannedFromPosting: false },
id: 'feUaIfcxVmJZHJOVVfawLTTPgZiP',
name: 'Franklin Buckridge',
username: 'Franky_Buck'
};
// mockPg.oneOrNone.mockImplementation((query: any, params: any, callback: any) => {
// return Promise.resolve(callback(mockDbUser))
// })
// (convertUser as jest.Mock).mockReturnValue(mockConvertedUser);
// ( toUserAPIResponse as jest.Mock).mockReturnValue(mockApiResponse);
// const result = await getUser({id: 'feUaIfcxVmJZHJOVVfawLTTPgZiP'})
// console.log(result);
})
})

View File

@@ -0,0 +1,17 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
// Use / as the root for tests so path-mapped imports from
// ../shared and ../../common are within the configured rootDir.
// This avoids TS6059 during ts-jest compilation.
"rootDir": "../..",
"baseUrl": ".",
"paths": {
"api/*": ["src/*"],
"shared/*": ["../shared/src/*"],
"common/*": ["../../common/src/*"],
"email/*": ["../email/emails/*"]
}
},
"include": ["tests/**/*.ts", "src/**/*.ts"]
}

View File

@@ -1,3 +1,4 @@
import React from 'react';
import {PrivateUser, User} from 'common/user'
import {getNotificationDestinationsForUser, UNSUBSCRIBE_URL} from 'common/user-notification-preferences'
import {sendEmail} from './send-email'
@@ -5,12 +6,13 @@ import {NewMessageEmail} from '../new-message'
import {NewEndorsementEmail} from '../new-endorsement'
import {Test} from '../test'
import {getProfile} from 'shared/profiles/supabase'
import { render } from "@react-email/render"
import {render} from "@react-email/render"
import {MatchesType} from "common/profiles/bookmarked_searches";
import NewSearchAlertsEmail from "email/new-search_alerts";
import WelcomeEmail from "email/welcome";
import * as admin from "firebase-admin";
const from = 'Compass <compass@compassmeet.com>'
export const fromEmail = 'Compass <compass@compassmeet.com>'
// export const sendNewMatchEmail = async (
// privateUser: PrivateUser,
@@ -60,7 +62,7 @@ export const sendNewMessageEmail = async (
}
return await sendEmail({
from,
from: fromEmail,
subject: `${fromUser.name} sent you a message!`,
to: privateUser.email,
html: await render(
@@ -81,8 +83,9 @@ export const sendWelcomeEmail = async (
privateUser: PrivateUser,
) => {
if (!privateUser.email) return
const verificationLink = await admin.auth().generateEmailVerificationLink(privateUser.email);
return await sendEmail({
from,
from: fromEmail,
subject: `Welcome to Compass!`,
to: privateUser.email,
html: await render(
@@ -90,6 +93,7 @@ export const sendWelcomeEmail = async (
toUser={toUser}
unsubscribeUrl={UNSUBSCRIBE_URL}
email={privateUser.email}
verificationLink={verificationLink}
/>
),
})
@@ -108,7 +112,7 @@ export const sendSearchAlertsEmail = async (
if (!email || !sendToEmail) return
return await sendEmail({
from,
from: fromEmail,
subject: `People aligned with your values just joined`,
to: email,
html: await render(
@@ -135,7 +139,7 @@ export const sendNewEndorsementEmail = async (
if (!privateUser.email || !sendToEmail) return
return await sendEmail({
from,
from: fromEmail,
subject: `${fromUser.name} just endorsed you!`,
to: privateUser.email,
html: await render(
@@ -152,7 +156,7 @@ export const sendNewEndorsementEmail = async (
export const sendTestEmail = async (toEmail: string) => {
return await sendEmail({
from,
from: fromEmail,
subject: 'Test email from Compass',
to: toEmail,
html: await render(<Test name="Test User"/>),

View File

@@ -36,11 +36,15 @@ export const sinclairProfile: ProfileRow = {
pref_gender: ['female', 'trans-female'],
pref_age_min: 18,
pref_age_max: 21,
religion: [],
languages: ['english'],
pref_relation_styles: ['friendship'],
pref_romantic_styles: ['poly', 'open', 'mono'],
disabled: false,
wants_kids_strength: 3,
looking_for_matches: true,
visibility: 'public',
mbti: 'intj',
messaging_status: 'open',
comments_enabled: true,
has_kids: 0,
@@ -48,8 +52,10 @@ export const sinclairProfile: ProfileRow = {
drinks_per_month: 0,
diet: null,
political_beliefs: ['e/acc', 'libertarian'],
relationship_status: ['married'],
religious_belief_strength: null,
religious_beliefs: null,
political_details: '',
photo_urls: [
'https://firebasestorage.googleapis.com/v0/b/mantic-markets.appspot.com/o/user-images%2FSinclair%2Flove-images%2FnJz22lr3Bl.jpg?alt=media&token=f1e99ba3-39cc-4637-8702-16a3a8dd49db',
'https://firebasestorage.googleapis.com/v0/b/mantic-markets.appspot.com/o/user-images%2FSinclair%2Flove-images%2FygM0mGgP_j.HEIC?alt=media&token=573b23d9-693c-4d6e-919b-097309f370e1',
@@ -135,8 +141,11 @@ export const jamesProfile: ProfileRow = {
city: 'San Francisco',
gender: 'male',
pref_gender: ['female'],
disabled: false,
pref_age_min: 22,
pref_age_max: 32,
religion: [],
languages: ['english'],
pref_relation_styles: ['friendship'],
pref_romantic_styles: ['poly', 'open', 'mono'],
wants_kids_strength: 4,
@@ -149,8 +158,11 @@ export const jamesProfile: ProfileRow = {
drinks_per_month: 5,
diet: null,
political_beliefs: ['libertarian'],
relationship_status: ['single'],
religious_belief_strength: null,
religious_beliefs: '',
mbti: 'intj',
political_details: '',
photo_urls: [
'https://firebasestorage.googleapis.com/v0/b/mantic-markets.appspot.com/o/user-images%2FJamesGrugett%2Flove-images%2FKl0WtbZsZW.jpg?alt=media&token=c928604f-e5ff-4406-a229-152864a4aa48',
'https://firebasestorage.googleapis.com/v0/b/mantic-markets.appspot.com/o/user-images%2FJamesGrugett%2Flove-images%2Fsii17zOItz.jpg?alt=media&token=474034b9-0d23-4005-97ad-5864abfd85fe',

View File

@@ -1,3 +1,4 @@
import React from 'react';
import {Body, Button, Column, Container, Head, Html, Preview, Row, Section, Text,} from '@react-email/components'
import {type User} from 'common/user'
import {DOMAIN} from 'common/envs/constants'

View File

@@ -1,3 +1,4 @@
import React from 'react';
import {Body, Button, Container, Head, Html, Preview, Section, Text,} from '@react-email/components'
import {DOMAIN} from 'common/envs/constants'
import {type ProfileRow} from 'common/profiles/profile'

View File

@@ -1,3 +1,4 @@
import React from 'react';
import {Body, Button, Container, Head, Html, Preview, Section, Text,} from '@react-email/components'
import {type User} from 'common/user'
import {type ProfileRow} from 'common/profiles/profile'

View File

@@ -1,3 +1,4 @@
import React from 'react';
import {Body, Container, Head, Html, Link, Preview, Section, Text,} from '@react-email/components'
import {type User} from 'common/user'
import {mockUser,} from './functions/mock'

View File

@@ -1,3 +1,4 @@
import React from 'react';
import {Column, Img, Link, Row, Section, Text} from "@react-email/components";
import {DOMAIN} from "common/envs/constants";

View File

@@ -1,29 +1,36 @@
import React from 'react';
import {Body, Button, Container, Head, Html, Preview, Section, Text,} from '@react-email/components'
import {type User} from 'common/user'
import {mockUser,} from './functions/mock'
import {button, container, content, Footer, main, paragraph} from "email/utils";
function randomHex(length: number) {
const bytes = new Uint8Array(Math.ceil(length / 2));
crypto.getRandomValues(bytes);
return Array.from(bytes, b => b.toString(16).padStart(2, "0"))
.join("")
.slice(0, length);
}
// function randomHex(length: number) {
// const bytes = new Uint8Array(Math.ceil(length / 2));
// crypto.getRandomValues(bytes);
// return Array.from(bytes, b => b.toString(16).padStart(2, "0"))
// .join("")
// .slice(0, length);
// }
interface WelcomeEmailProps {
toUser: User
unsubscribeUrl: string
email?: string
verificationLink?: string
}
export const WelcomeEmail = ({
toUser,
unsubscribeUrl,
email,
verificationLink,
}: WelcomeEmailProps) => {
const name = toUser.name.split(' ')[0]
const confirmUrl = `https://compassmeet.com/confirm-email/${randomHex(16)}`
// Some users may already have a verified email (e.g., signed it with Googl), but we send them a link anyway so that
// their email provider marks Compass as spam-free once they click the link.
// We can remove the verif link for them if we ask the user to click on another link in the email (which would not be related to email verification)
// const verificationLink = `https://compassmeet.com/confirm-email/${randomHex(16)}`
return (
<Html>
@@ -48,14 +55,14 @@ export const WelcomeEmail = ({
<Button
style={button}
href={confirmUrl}
href={verificationLink}
>
Confirm My Email
</Button>
<Text style={{marginTop: "40px", fontSize: "10px", color: "#555"}}>
Or copy and paste this link into your browser: <br/>
<a href={confirmUrl}>{confirmUrl}</a>
<a href={verificationLink}>{verificationLink}</a>
</Text>
<Text style={{marginTop: "40px", fontSize: "12px", color: "#555"}}>

View File

@@ -0,0 +1,31 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
rootDir: '.',
testMatch: [
"<rootDir>/tests/**/*.test.ts",
"<rootDir>/tests/**/*.spec.ts"
],
moduleNameMapper: {
"^api/(.*)$": "<rootDir>/src/$1",
"^shared/(.*)$": "<rootDir>/../shared/src/$1",
"^common/(.*)$": "<rootDir>/../../common/src/$1",
"^email/(.*)$": "<rootDir>/../email/emails/$1"
},
moduleFileExtensions: ["ts", "js", "json"],
clearMocks: true,
globals: {
'ts-jest': {
tsconfig: "<rootDir>/tsconfig.test.json"
}
},
collectCoverageFrom: [
"src/**/*.{ts,tsx}",
"!src/**/*.d.ts"
],
};

View File

@@ -4,7 +4,8 @@
"private": true,
"scripts": {
"dev": "email dev --port 3001",
"build": "tsc -b"
"build": "tsc -b",
"test": "jest --config jest.config.js --passWithNoTests"
},
"dependencies": {
"@react-email/components": "0.0.33",

View File

View File

View File

@@ -0,0 +1,17 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
// Use / as the root for tests so path-mapped imports from
// ../shared and ../../common are within the configured rootDir.
// This avoids TS6059 during ts-jest compilation.
"rootDir": "../..",
"baseUrl": ".",
"paths": {
"api/*": ["src/*"],
"shared/*": ["../shared/src/*"],
"common/*": ["../../common/src/*"],
"email/*": ["../email/emails/*"]
}
},
"include": ["tests/**/*.ts", "src/**/*.ts"]
}

View File

@@ -0,0 +1,31 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
rootDir: '.',
testMatch: [
"<rootDir>/tests/**/*.test.ts",
"<rootDir>/tests/**/*.spec.ts"
],
moduleNameMapper: {
"^api/(.*)$": "<rootDir>/src/$1",
"^shared/(.*)$": "<rootDir>/../shared/src/$1",
"^common/(.*)$": "<rootDir>/../../common/src/$1",
"^email/(.*)$": "<rootDir>/../email/emails/$1"
},
moduleFileExtensions: ["ts", "js", "json"],
clearMocks: true,
globals: {
'ts-jest': {
tsconfig: "<rootDir>/tsconfig.test.json"
}
},
collectCoverageFrom: [
"src/**/*.{ts,tsx}",
"!src/**/*.d.ts"
],
};

View File

@@ -6,7 +6,8 @@
"build": "tsc -b && yarn --cwd=../../common tsc-alias && tsc-alias",
"compile": "tsc -b",
"verify": "yarn --cwd=../.. verify",
"verify:dir": "npx eslint . --max-warnings 0"
"verify:dir": "npx eslint . --max-warnings 0",
"test": "jest --config jest.config.js --passWithNoTests"
},
"sideEffects": false,
"dependencies": {

View File

@@ -2,7 +2,7 @@ import * as admin from 'firebase-admin'
import {getServiceAccountCredentials} from "shared/firebase-utils";
import {IS_LOCAL} from "common/envs/constants";
import {IS_LOCAL} from "common/hosting/constants";
// Locally initialize Firebase Admin.
export const initAdmin = () => {

View File

@@ -2,7 +2,7 @@ import { format } from 'node:util'
import { isError, pick, omit } from 'lodash'
import { dim, red, yellow } from 'colors/safe'
import { getMonitoringContext } from './context'
import {IS_GOOGLE_CLOUD} from "common/envs/constants";
import {IS_GOOGLE_CLOUD} from "common/hosting/constants";
// mapping JS log levels (e.g. functions on console object) to GCP log levels
const JS_TO_GCP_LEVELS = {

View File

@@ -4,7 +4,7 @@ import {log} from './log'
import {getInstanceInfo, InstanceInfo} from './instance-info'
import {chunk} from 'lodash'
import {CUSTOM_METRICS, metrics, MetricStore, MetricStoreEntry,} from './metrics'
import {IS_GOOGLE_CLOUD} from "common/envs/constants";
import {IS_GOOGLE_CLOUD} from "common/hosting/constants";
// how often metrics are written. GCP says don't write for a single time series
// more than once per 5 seconds.

View File

@@ -1,6 +1,6 @@
export const removePinnedUrlFromPhotoUrls = async (parsedBody: {
pinned_url?: string
photo_urls?: string[]
photo_urls?: string[] | null
}) => {
if (parsedBody.photo_urls && parsedBody.pinned_url) {
parsedBody.photo_urls = parsedBody.photo_urls.filter(

View File

@@ -9,7 +9,7 @@ import {
ServerMessage,
CLIENT_MESSAGE_SCHEMA,
} from 'common/api/websockets'
import {IS_LOCAL} from "common/envs/constants";
import {IS_LOCAL} from "common/hosting/constants";
import {getWebsocketUrl} from "common/api/utils";
// Extend the type definition locally

View File

View File

@@ -0,0 +1 @@
Note: may not be needed. `shared` rarely needs integration tests.

View File

View File

@@ -0,0 +1,17 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
// Use / as the root for tests so path-mapped imports from
// ../shared and ../../common are within the configured rootDir.
// This avoids TS6059 during ts-jest compilation.
"rootDir": "../..",
"baseUrl": ".",
"paths": {
"api/*": ["src/*"],
"shared/*": ["../shared/src/*"],
"common/*": ["../../common/src/*"],
"email/*": ["../email/emails/*"]
}
},
"include": ["tests/**/*.ts", "src/**/*.ts"]
}

View File

@@ -8,7 +8,7 @@ create table if not exists
-- Foreign Keys
alter table contact
add constraint contact_user_id_fkey foreign key (user_id) references users (id);
add constraint contact_user_id_fkey foreign key (user_id) references users (id) on delete set null;
-- Row Level Security
alter table contact enable row level security;

View File

@@ -0,0 +1,55 @@
-- Add columns to support message actions
ALTER TABLE private_user_messages
ADD COLUMN IF NOT EXISTS is_edited BOOLEAN DEFAULT FALSE,
ADD COLUMN IF NOT EXISTS reactions JSONB DEFAULT '{}'::jsonb,
ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE,
ADD COLUMN IF NOT EXISTS edited_at TIMESTAMPTZ;
-- Create a function to update edited_at timestamp
-- CREATE OR REPLACE FUNCTION update_edited_at()
-- RETURNS TRIGGER AS $$
-- BEGIN
-- IF NEW.content <> OLD.content THEN
-- NEW.is_edited := TRUE;
-- NEW.edited_at := NOW();
-- END IF;
-- RETURN NEW;
-- END;
-- $$ LANGUAGE plpgsql;
--
-- -- Create a trigger to update edited_at when content changes
-- DROP TRIGGER IF EXISTS update_private_message_edited_at ON private_user_messages;
-- CREATE TRIGGER update_private_message_edited_at
-- BEFORE UPDATE ON private_user_messages
-- FOR EACH ROW
-- WHEN (OLD.content IS DISTINCT FROM NEW.content)
-- EXECUTE FUNCTION update_edited_at();
-- Update RLS policies to allow message owners to update their messages
-- DROP POLICY IF EXISTS "private message update" ON private_user_messages;
-- CREATE POLICY "private message update" ON private_user_messages
-- FOR UPDATE USING (
-- user_id = firebase_uid()
-- AND created_time > NOW() - INTERVAL '1 day' -- Only allow editing for 24 hours
-- AND deleted = FALSE
-- );
-- Add policy for soft delete
-- DROP POLICY IF EXISTS "private message delete" ON private_user_messages;
-- CREATE POLICY "private message delete" ON private_user_messages
-- FOR UPDATE USING (
-- user_id = firebase_uid()
-- );
-- Add policy for reactions
-- DROP POLICY IF EXISTS "private message react" ON private_user_messages;
-- CREATE POLICY "private message react" ON private_user_messages
-- FOR UPDATE USING (
-- EXISTS (
-- SELECT 1
-- FROM private_user_message_channels ch
-- JOIN private_user_message_channel_members m ON ch.id = m.channel_id
-- WHERE m.user_id = firebase_uid()
-- AND ch.id = private_user_messages.channel_id
-- )
-- );

View File

@@ -0,0 +1,6 @@
-- Add languages column to profiles table
ALTER TABLE profiles
ADD COLUMN IF NOT EXISTS languages TEXT[] null;
-- Create GIN index for array operations
CREATE INDEX IF NOT EXISTS idx_profiles_languages ON profiles USING GIN (languages);

View File

@@ -0,0 +1,6 @@
-- Add MBTI column to profiles table
ALTER TABLE profiles
ADD COLUMN IF NOT EXISTS mbti TEXT;
-- Create GIN index for array operations
CREATE INDEX IF NOT EXISTS idx_profiles_mbti ON profiles USING btree (mbti);

View File

@@ -1,4 +1,3 @@
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'profile_visibility') THEN
@@ -35,7 +34,9 @@ CREATE TABLE IF NOT EXISTS profiles (
occupation_title TEXT,
photo_urls TEXT[],
pinned_url TEXT,
political_details TEXT,
political_beliefs TEXT[],
relationship_status TEXT[],
pref_age_max INTEGER NULL,
pref_age_min INTEGER NULL,
pref_gender TEXT[] NOT NULL,
@@ -45,12 +46,14 @@ CREATE TABLE IF NOT EXISTS profiles (
region_code TEXT,
religious_belief_strength INTEGER,
religious_beliefs TEXT,
religion TEXT[],
twitter TEXT,
university TEXT,
user_id TEXT NOT NULL,
visibility profile_visibility DEFAULT 'member'::profile_visibility NOT NULL,
wants_kids_strength INTEGER DEFAULT 0 NOT NULL,
website TEXT,
disabled BOOLEAN DEFAULT FALSE NOT NULL,
CONSTRAINT profiles_pkey PRIMARY KEY (id)
);

View File

@@ -0,0 +1,18 @@
create table push_subscriptions_mobile (
id serial primary key,
user_id text not null,
token text not null unique,
platform text not null, -- 'android' or 'ios'
created_at timestamptz default now(),
constraint push_subscriptions_mobile_user_id_fkey foreign KEY (user_id) references users (id) on delete CASCADE
);
-- Row Level Security
ALTER TABLE push_subscriptions_mobile ENABLE ROW LEVEL SECURITY;
-- Indexes
CREATE INDEX IF not exists user_id_idx ON push_subscriptions_mobile (user_id);
CREATE INDEX IF not exists platform_idx ON push_subscriptions_mobile (platform);
CREATE INDEX IF not exists platform_user_id_idx ON push_subscriptions_mobile (platform, user_id);

View File

@@ -8,15 +8,15 @@ create table if not exists
id text default uuid_generate_v4 () not null,
parent_id text,
parent_type text,
user_id text not null
user_id text
);
-- Foreign Keys
alter table reports
add constraint reports_content_owner_id_fkey foreign key (content_owner_id) references users (id);
add constraint reports_content_owner_id_fkey foreign key (content_owner_id) references users (id) on delete set null;
alter table reports
add constraint reports_user_id_fkey foreign key (user_id) references users (id);
add constraint reports_user_id_fkey foreign key (user_id) references users (id) on delete set null;
-- Row Level Security
alter table reports enable row level security;

View File

@@ -44,6 +44,7 @@ create or replace function get_votes_with_results(order_by text default 'recent'
created_time timestamptz,
creator_id TEXT,
is_anonymous boolean,
status text,
votes_for int,
votes_against int,
votes_abstain int,
@@ -58,6 +59,7 @@ with results as (
v.created_time,
v.creator_id,
v.is_anonymous,
v.status,
COALESCE(SUM(CASE WHEN r.choice = 1 THEN 1 ELSE 0 END), 0) AS votes_for,
COALESCE(SUM(CASE WHEN r.choice = -1 THEN 1 ELSE 0 END), 0) AS votes_against,
COALESCE(SUM(CASE WHEN r.choice = 0 THEN 1 ELSE 0 END), 0) AS votes_abstain,
@@ -73,6 +75,7 @@ SELECT
created_time,
creator_id,
is_anonymous,
status,
votes_for,
votes_against,
votes_abstain,

View File

@@ -4,7 +4,8 @@ CREATE TABLE IF NOT EXISTS votes (
creator_id TEXT NOT NULL,
title TEXT NOT NULL,
is_anonymous BOOLEAN NOT NULL,
description JSONB
description JSONB,
status TEXT
);
-- Foreign Keys

20
capacitor.config.ts Normal file
View File

@@ -0,0 +1,20 @@
import type { CapacitorConfig } from '@capacitor/cli';
const WEBVIEW_DEV_PHONE = process.env.NEXT_PUBLIC_WEBVIEW_DEV_PHONE === '1'
const LOCAL_ANDROID = WEBVIEW_DEV_PHONE || process.env.NEXT_PUBLIC_LOCAL_ANDROID === '1'
const LOCAL_URL = WEBVIEW_DEV_PHONE ? '192.168.1.3' : '10.0.2.2'
console.log("CapacitorConfig", {LOCAL_ANDROID, WEBVIEW_DEV_PHONE})
const config: CapacitorConfig = {
appId: 'com.compassconnections.app',
appName: 'Compass',
webDir: 'web/out',
server: LOCAL_ANDROID ? { url: `http://${LOCAL_URL}:3000`, cleartext: true } : {},
plugins: {
LiveUpdate: {
appId: "969bc540-8077-492f-8403-b554bee5de50"
}
}
};
export default config;

View File

@@ -1,12 +1,16 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
const { pathsToModuleNameMapper } = require('ts-jest')
const { compilerOptions } = require('./tsconfig')
const {pathsToModuleNameMapper} = require('ts-jest')
const {compilerOptions} = require('./tsconfig')
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {
prefix: '<rootDir>/',
}),
testMatch: ['**/*.test.ts'],
preset: 'ts-jest',
testEnvironment: 'node',
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {
prefix: '<rootDir>/',
}),
testMatch: ['**/*.test.ts'],
collectCoverageFrom: [
"src/**/*.{ts,tsx}",
"!src/**/*.d.ts"
],
}

View File

@@ -7,7 +7,7 @@
"compile": "tsc -b",
"verify": "yarn --cwd=.. verify",
"verify:dir": "npx eslint . --max-warnings 0",
"test": "jest"
"test": "jest --config jest.config.js --passWithNoTests"
},
"sideEffects": false,
"dependencies": {

View File

@@ -238,9 +238,7 @@ export const API = (_apiTypeCheck = {
method: 'POST',
authed: true,
rateLimited: true,
props: z.object({
username: z.string(), // just so you're sure
}),
props: z.object({}),
summary: 'Delete the authenticated user account',
tag: 'Users',
},
@@ -297,6 +295,47 @@ export const API = (_apiTypeCheck = {
summary: 'Remove the pinned photo from a profile',
tag: 'Profiles',
},
'create-compatibility-question': {
method: 'POST',
authed: true,
rateLimited: true,
returns: {} as any,
props: z.object({
question: z.string().min(1).max(MAX_COMPATIBILITY_QUESTION_LENGTH),
options: z.record(z.string(), z.number()),
}),
summary: 'Create a new compatibility question with options',
tag: 'Compatibility',
},
'set-compatibility-answer': {
method: 'POST',
authed: true,
rateLimited: true,
returns: {} as Row<'compatibility_answers'>,
props: z
.object({
questionId: z.number(),
multipleChoice: z.number(),
prefChoices: z.array(z.number()),
importance: z.number(),
explanation: z.string().nullable().optional(),
})
.strict(),
summary: 'Submit or update a compatibility answer',
tag: 'Compatibility',
},
'get-profile-answers': {
method: 'GET',
authed: true,
rateLimited: true,
props: z.object({userId: z.string()}).strict(),
returns: {} as {
status: 'success'
answers: Row<'compatibility_answers'>[]
},
summary: 'Get compatibility answers for a profile',
tag: 'Compatibility',
},
'get-compatibility-questions': {
method: 'GET',
authed: true,
@@ -312,6 +351,16 @@ export const API = (_apiTypeCheck = {
summary: 'Retrieve compatibility questions and stats',
tag: 'Compatibility',
},
'delete-compatibility-answer': {
method: 'POST',
authed: true,
rateLimited: true,
props: z.object({
id: z.number(),
}),
summary: 'Delete a compatibility answer',
tag: 'Compatibility',
},
'like-profile': {
method: 'POST',
authed: true,
@@ -402,10 +451,14 @@ export const API = (_apiTypeCheck = {
pref_age_max: z.coerce.number().optional(),
drinks_min: z.coerce.number().optional(),
drinks_max: z.coerce.number().optional(),
religion: arraybeSchema.optional(),
pref_relation_styles: arraybeSchema.optional(),
pref_romantic_styles: arraybeSchema.optional(),
diet: arraybeSchema.optional(),
political_beliefs: arraybeSchema.optional(),
mbti: arraybeSchema.optional(),
relationship_status: arraybeSchema.optional(),
languages: arraybeSchema.optional(),
wants_kids_strength: z.coerce.number().optional(),
has_kids: z.coerce.number().optional(),
is_smoker: zBoolean.optional().optional(),
@@ -575,47 +628,55 @@ export const API = (_apiTypeCheck = {
summary: 'Leave a private message channel',
tag: 'Messages',
},
'create-compatibility-question': {
'edit-message': {
method: 'POST',
authed: true,
rateLimited: true,
returns: {} as any,
props: z.object({
question: z.string().min(1).max(MAX_COMPATIBILITY_QUESTION_LENGTH),
options: z.record(z.string(), z.number()),
messageId: z.number(),
content: contentSchema,
}),
summary: 'Create a new compatibility question with options',
tag: 'Compatibility',
summary: 'Edit a private message',
tag: 'Messages',
},
'set-compatibility-answer': {
'delete-message': {
method: 'POST',
authed: true,
rateLimited: true,
returns: {} as Row<'compatibility_answers'>,
props: z
.object({
questionId: z.number(),
multipleChoice: z.number(),
prefChoices: z.array(z.number()),
importance: z.number(),
explanation: z.string().nullable().optional(),
})
.strict(),
summary: 'Submit or update a compatibility answer',
tag: 'Compatibility',
returns: {} as any,
props: z.object({
messageId: z.number(),
}),
summary: 'Delete a private message',
tag: 'Messages',
},
'get-profile-answers': {
method: 'GET',
'react-to-message': {
method: 'POST',
authed: true,
rateLimited: true,
props: z.object({userId: z.string()}).strict(),
returns: {} as {
status: 'success'
answers: Row<'compatibility_answers'>[]
},
summary: 'Get compatibility answers for a profile',
tag: 'Compatibility',
returns: {} as any,
props: z.object({
messageId: z.number(),
reaction: z.string(),
toDelete: z.boolean().optional(),
}),
summary: 'Add or remove a reaction to a message',
tag: 'Messages',
},
// 'get-message-reactions': {
// method: 'GET',
// authed: true,
// rateLimited: false,
// returns: {} as {
// reactions: Record<string, number>
// },
// props: z.object({
// messageId: z.string(),
// }),
// summary: 'Get reactions for a message',
// tag: 'Messages',
// },
'create-vote': {
method: 'POST',
authed: true,
@@ -698,6 +759,17 @@ export const API = (_apiTypeCheck = {
summary: 'Save a push/browser subscription for the user',
tag: 'Notifications',
},
'save-subscription-mobile': {
method: 'POST',
authed: true,
rateLimited: true,
returns: {} as any,
props: z.object({
token: z.string(),
}),
summary: 'Save a mobile push subscription for the user',
tag: 'Notifications',
},
'create-bookmarked-search': {
method: 'POST',
authed: true,
@@ -723,6 +795,17 @@ export const API = (_apiTypeCheck = {
summary: 'Delete a bookmarked search by ID',
tag: 'Searches',
},
// 'auth-google': {
// method: 'GET',
// authed: false,
// rateLimited: true,
// returns: {} as any,
// props: z.object({
// code: z.string(),
// }),
// summary: 'Google Auth',
// tag: 'Tokens',
// },
} as const)
export type APIPath = keyof typeof API

View File

@@ -1,4 +1,5 @@
import {BACKEND_DOMAIN, IS_LOCAL} from 'common/envs/constants'
import {BACKEND_DOMAIN} from 'common/envs/constants'
import {IS_LOCAL} from "common/hosting/constants";
type ErrorCode =
| 400 // your input is bad (like zod is mad)

Some files were not shown because too many files have changed in this diff Show More