Rutemu API

Frontend integration guide

How the Rutemu Flutter app talks to this API: every screen of the mockup, the call it makes, the JSON it gets back, the live Socket.IO events, and what to show for each error. Try any endpoint in Swagger UI.

REST

/api — JSON, camelCase, UTC ISO-8601 times.

Auth

Authorization: Bearer <token> from login / register.

Realtime

Socket.IO v4 on the same host, auth: { token }.

Language

Accept-Language: id or en → error messages in that language.

Quick start

  1. Run the API (npm run start:dev) and seed the demo story: npm run seed.
  2. From the Android emulator the API is http://10.0.2.2:3000/api; from a phone on the same Wi-Fi use your computer's IP, e.g. http://192.168.1.20:3000/api.
  3. Log in as angganu / gather-2026! — the same story as the mockup:
DemoWhat happens
Family day @ Ancol K8D2ANLive now, Angga hosts, 3 people with positions and trails → Home “LIVE NOW”, live map.
Jakarta → Bandung Ride 7Q4X2MAngga's journey in 2 days, 5 stops → “NEXT UP”, host lobby.
Join 4KD9WPSentul Morning Loop (host eva) — fits your schedule → Join as guest.
Join 8MN2TCAncol Beach Cleanup — overlaps Family day → “You can't join this one” (conflict).
Join C7F2DSCar Free Day Sudirman — you're already a member (alreadyMember: true).
Join 3RT8XQJakarta → Puncak Ride — already ended → 410 room_ended.
Join X9Y8Z7No such room → 404 not_found.
History6 finished events (journeys and monitoring, as host and as guest) with timelines and trails.

Other demo users (same password): eva, revan, arief. Running npm run seed again resets the story to “now”.

Password reset in development. With EXPOSE_DEV_CODES=true (never in production) POST /auth/forgot-password returns the 6-digit code as devCode, and the code is also printed in the server console when SMTP isn't set.

Conventions

Errors

Every error has the same shape. Some add fields (listed below).

{ "error": "schedule_conflict", "message": "You’re already in Family day @ Ancol at that time (30 Oct, 10:00 – 30 Oct, 15:00).", "conflict": { …RoomSummary }, "overlapFrom": "…", "overlapTo": "…" }
HTTPerrorWhenExtra fieldsSuggested UI (mockup key)
400validation_errorA field is missing or wrongfieldsError under each field; see codes below
400invalid_codeWrong reset codeattemptsLeftauth.reset.codeWrong
400code_expiredReset code older than 15 minAsk for a new code
401unauthorizedMissing, expired or revoked tokenLog out → Login
401invalid_credentialsWrong login, or wrong current passwordauth.errors.invalidCredentials / auth.change.wrongCurrent
403forbiddenNot your room / host-only actionToast
403removed_from_roomThe host removed youToast, back to Home
404not_foundUnknown room / code / endpointjoin.errors.notFound
409schedule_conflictOverlaps another event you're inconflict, overlapFrom, overlapTo, (user on edits)Overlap sheet / Join conflict screen
409username_taken · email_takenRegister / edit profileauth.register.usernameTaken
409invalid_stateAction not possible in this room statusstatusRefresh the room
409host_cannot_leaveHost tried to leaveOffer “End event”
409other_room_liveStarting while still live elsewhereconflict“Another event is live” dialog (room.otherLiveHost)
409voice_fullSocket voice:join when the voice room already has VOICE_MAX_PEERS phonesmaxPeers“Voice is full” under the mic (live.voiceFull); the app tries again every 30 s
410room_endedJoining a finished eventjoin.errors.ended
413payload_too_largeBody over 1 MB
429too_many_attemptsReset code resent within 60 s, or 5 wrong codesretryAfterSecondsauth.reset.resendIn
429too_many_requestsRate limitToast
500server_errorBug or database downGeneric toast

Field problem codes (fields)

Keys are field paths (stops.2.restMinutes), values are codes:

CodeMeaningCodeMeaning
requiredMissing / emptyinvalid_username3–20 chars a–z 0–9 . _
invalid_emailNot an emailweak_password8+ chars with a number and a symbol
too_long · too_shortLength / time window too longinvalid_dateNot an ISO-8601 date
before_startEnd is not after starttoo_early · too_lateStart > 24 h ago / > 1 year ahead
must_be_start · must_be_finish · must_be_transit_or_restStop ordertoo_few · too_manyArray size (stops: 2–9)
invalid_choiceNot one of the allowed valuesinvalid_formatWrong pattern (code, colour)
invalid_latitude · invalid_longitudeOut of rangetoo_small · too_largeNumber out of range
not_allowedField not allowed hereinvalid_json(key body) body isn't valid JSON

Rules the server enforces

Screens: login, register, forgot / reset, change password

POST/api/auth/loginLogin screen
{ "identifier": "angganu", "password": "gather-2026!" }   // identifier = email or username
200 { "token": "eyJhbGciOi…", "expiresAt": "2026-11-29T04:04:17.157Z",
      "user": { "id": "…", "username": "angganu", "displayName": "Angga", "avatarColor": "#6D4AFF", "code": "K7Q2M",
                "email": "angga@example.com", "language": "id", "createdAt": "…" } }

401 invalid_credentials → “That email, username or password isn't right”. Store the token securely (e.g. flutter_secure_storage).

POST/api/auth/registerRegister screen
{ "displayName": "Angga Nugraha", "username": "angganu", "email": "angga@example.com", "password": "gather-2026!", "language": "id" }

201 — same body as login (you're logged in). language is optional (defaults to Accept-Language). 409 username_taken / email_taken; 400 validation_error with fields.

GET/api/auth/username-available?username=eva“@eva is available” while typing
{ "available": true }   |   { "available": false, "reason": "taken" | "invalid" }

Debounce ~400 ms. With a token (Edit profile) your own username counts as available.

POST/api/auth/forgot-passwordForgot password → send code
{ "email": "angga@example.com" }   →   200 { "ok": true }   (+ "devCode": "482917" in development)

Always 200, even for unknown emails. The code is valid 15 minutes. Resending within 60 s → 429 too_many_attempts with retryAfterSeconds (drive the “Resend in 0:42” timer from it).

POST/api/auth/reset-passwordReset password screen
{ "email": "angga@example.com", "code": "482917", "newPassword": "new-pass-2026!" }   →   200 { "ok": true }

400 invalid_code (with attemptsLeft) / code_expired; after 5 wrong codes 429 too_many_attempts — request a new code. A reset logs out every device; go to Login.

POST/api/auth/change-passwordProfile → Change password
{ "currentPassword": "gather-2026!", "newPassword": "new-pass-2026!" }   →   200 { "token": "…", "expiresAt": "…" }

Replace the stored token with the new one: every older token (other phones too) stops working. Wrong current password → 401 invalid_credentials.

POST/api/auth/logoutProfile → Log out

Revokes this device's token → { "ok": true }. Then delete it locally.

POST/api/me/referralProfile → Your code → Referral code
{ "code": "K7Q2M" }   →   200 { "user": Me }   // user.refCode = "K7Q2M"

A friend's code, typed or scanned from their referral QR (…/u/<CODE>, built from user.referralUrl). Case, spaces and dashes are ignored. Once only: hide the field when user.refCode is set. 400 referral_own_code; 404 not_found (no one has that code); 409 referral_already_set.

Screen: Home dashboard

Load these in parallel when Home opens and when the app returns to the foreground:

Part of the screenCall
“Hi, Angga”GET /me → user.displayName (first word)
LIVE NOW card, NEXT UP card, “Coming up”GET /me/rooms → items: live first, then by startsAt. First live = LIVE NOW; first scheduled = NEXT UP.
Your activity (Events · Distance · Tracking)GET /me/stats → events, hosted, joined, distanceMeters, trackedSeconds
Calendar month + dots + day listGET /me/calendar?from=…&to=… with the month's local boundaries converted to UTC. Dot colour = type; an ended item with startedAt opens History.
GET /api/me/stats  →  { "events": 9, "hosted": 5, "joined": 4, "distanceMeters": 290964, "trackedSeconds": 83531 }

“3h 34m left” = endsAt − now; “running 1h 13m” = now − startedAt; endsAt = null → unlimited. Avatars: memberPreview (max 4) and “+N” = memberCount − 4. Listen to the socket's room:started / room:ended / room:deleted to refresh Home without polling.

Screens: create event (journey / monitoring)

Step 1 — kind, name, schedule

Each time date/time changes, check the overlap and show “No overlap with your other events” or the warning:

GET/api/me/availability?startsAt=…&endsAt=…live overlap check
{ "available": false,
  "conflict": { "id": "…", "title": "Family day @ Ancol", "startsAt": "…", "endsAt": "…", … RoomSummary },
  "overlapFrom": "2026-10-30T05:50:00.000Z", "overlapTo": "2026-10-30T07:50:00.000Z" }

Omit endsAt for an unlimited monitoring event. Add excludeRoomId when editing a room.

Step 2a — journey route → Create room

POST/api/rooms/journey201 { room }
{
  "title": "Jakarta → Bandung Ride",
  "startsAt": "2026-11-07T23:00:00.000Z",
  "endsAt": "2026-11-08T07:00:00.000Z",
  "guestsCanTalk": true,
  "stops": [
    { "kind": "start",   "name": "Monas, Jakarta Pusat", "address": "Gambir, Jakarta Pusat", "lat": -6.1754, "lng": 106.8272 },
    { "kind": "transit", "name": "GT Bekasi Timur",      "lat": -6.2489, "lng": 107.0174 },
    { "kind": "rest",    "name": "Rest Area KM 57",      "lat": -6.3486, "lng": 107.2155, "restMinutes": 20 },
    { "kind": "rest",    "name": "Rest Area KM 97",      "lat": -6.5639, "lng": 107.4419, "restMinutes": 20 },
    { "kind": "finish",  "name": "Gedung Sate, Bandung", "lat": -6.9025, "lng": 107.6188 }
  ],
  "routeDistanceMeters": 152000,     // optional, from Google Routes
  "routeDurationSeconds": 13320,     // optional ("~3h 42m")
  "routePolyline": "…"               // optional encoded polyline, returned to every member
}

Errors: 400 with fields like stops.0.kind: must_be_start, stops.2.restMinutes: required, endsAt: before_start; 409 schedule_conflict. On success go to the host lobby with room.id.

Step 2b — monitoring duration → Create room

POST/api/rooms/monitoring201 { room }
{
  "title": "Family day @ Ancol",
  "startsAt": "2026-11-01T03:00:00.000Z",
  "endsAt": "2026-11-01T08:00:00.000Z",          // null or omitted = Unlimited
  "meetingPoint": { "name": "Gate", "address": "Pintu Gerbang Utama Ancol", "lat": -6.1251, "lng": 106.8411 }  // optional
}

Presets (2 h, 4 h, 8 h, custom h/m) are just endsAt = startsAt + duration. POST /api/rooms with "type": "journey" | "monitoring" does the same (rutemu contract).

Screens: room lobby (host and guest)

GET /rooms/:id→socket room:subscribe→room:updated pushes→status live → live map
GET/api/rooms/:idroom detail, for anyone who is or was in it

Returns { room } (see Room). Use it for the header (type chip, “You're the host”, title, date · time · km · stops), the invite card and the member list. Subscribe on the socket right after so the screen stays live.

  • QR code = room.joinUrl (https://app.rutemu.com/j/7Q4X2M); group code = room.code shown as “7Q4 X2M”.
  • Ready / Location off / Mic off per member: online, locationEnabled, micOn, micAllowed. Report your own with socket presence:update.
  • “In the room · 4” = memberCount; list members where leftAt == null.
PATCH/api/rooms/:idhostGuests can talk toggle, rename, reschedule
{ "guestsCanTalk": false }          // any time before the end; sets micAllowed of every guest
{ "title": "Sunday Ride" }
{ "startsAt": "…", "endsAt": "…", "stops": [ … ], "meetingPoint": { … } | null }   // scheduled only

Rescheduling checks every member's calendar; a clash → 409 schedule_conflict with user (whose calendar).

PATCH/api/rooms/:id/members/:userIdhostTurn their mic off / let them talk
{ "micAllowed": false }   →   { room }
DELETE/api/rooms/:id/members/:userIdhostRemove from room

→ { room }. The person gets member:removed and can't rejoin this room.

POST/api/rooms/:id/starthostStart tracking

→ { room } with status: "live". Everyone subscribed gets room:updated (switch to the live map with the SharedAxis Z transition); members on other screens get room:started. 409 other_room_live (with conflict) → “Another event is live · End it and start”: call POST /rooms/{conflict.id}/end (host) or /leave (guest), then start again.

DELETE/api/rooms/:idhostRoom options → Cancel event (scheduled only)

→ { ok: true }; members get room:deleted.

POST/api/rooms/:id/leaveGuest → Leave room

→ { ok: true }. Host → 409 host_cannot_leave.

Screens: join (scan QR, link, type code)

  1. Get the code. QR and links contain …/j/<CODE> — take the last path segment. Typed codes can be sent as typed. A community QR contains …/c/<4 characters> — see Communities.
  2. Preview → decide which screen to show:
GET/api/rooms/code/:codeJoin preview / conflict
{ "room": { … Room, members are active ones, positions hidden },
  "alreadyMember": false,
  "conflict": null,                     // or your overlapping RoomSummary
  "overlapFrom": null, "overlapTo": null }
ResultScreen
conflict == null, alreadyMember == falseJoin preview → “Fits your schedule” → Join as guest
conflict != nullJoin conflict (“You can't join this one”, overlap bar from overlapFrom–overlapTo)
alreadyMember == true“You're already in this room” → open the lobby
404 not_found / 410 room_endedError under the code field
403 community_only (body has community: CommunityRef)“Members only — join {name} first”
POST/api/rooms/code/:code/joinJoin as guest
{ "method": "qr" | "link" | "code" | "community" }   →   { room }   (then open the guest lobby)

Joining again is harmless. 409 schedule_conflict, 410 room_ended, 403 removed_from_room, 403 community_only. Send community when joining from the community page.

Screen: live map

room:subscribe→location:update every 2–5 s⇄location · room:updated · timeline→room:updated status ended
POST/api/rooms/:id/locationsHTTP fallback / background batch
{ "points": [ { "lat": -6.1754, "lng": 106.8272, "heading": 90, "speed": 12.5, "accuracy": 8, "at": "2026-10-30T04:15:09.810Z" } ] }
→ { "accepted": 1, "position": { "userId": "…", "lat": -6.1754, "lng": 106.8272, …, "distanceMeters": 41250 } }
GET/api/rooms/:id/tracks?since=ISOtrails
{ "tracks": { "<userId>": [[-6.2001, 106.8167, 1793333059810], …] } }   // [lat, lng, epochMillis]

Voice (WebRTC, STUN, TURN)

The audio goes from phone to phone; the API only introduces the phones of a live room and hands out STUN/TURN servers (TURN relays the audio when a network blocks direct connections).

  1. Join: make up a UUID peerId for this voice session and send voice:join { roomId, peerId }. After a socket reconnect send the same peerId: within 20 s you get your place back (resumed: true) and nobody is told. A new peerId replaces your other devices (they get voice:closed with reason elsewhere).
  2. Connect to everyone in peers and to every voice:peer-joined: of each pair, the phone with the smaller peerId creates the peer connection (iceServers and iceTransportPolicy from the ack), adds one audio transceiver (sendrecv) and sends the offer; the other one answers. Each connection has its own sid, and every message about it carries it.
  3. Signal with voice:signal { roomId, to: peerId, sid, description | candidate | restart }; it arrives as voice:signal with from and fromUserId, in the order it was sent. restart: true asks the offering side to connect again (lost connection, offer never arrived).
  4. Mic: attach the microphone track to every connection with replaceTrack when you unmute and replaceTrack(null) when you mute — no new offer needed.
  5. Leave with voice:leave { roomId }. Leaving or being removed from the room, and the end of the event, send voice:closed (left, removed, ended).
SOCKETvoice:joinack
{ "ok": true, "peerId": "9b0c…", "resumed": false, "canTalk": true, "maxPeers": 12,
  "peers": [ { "peerId": "4f1a…", "userId": "<user id>" } ],
  "iceServers": [ { "urls": ["stun:stun.l.google.com:19302"] },
                  { "urls": ["turn:turn.example.com:3478?transport=udp", "turns:turn.example.com:5349?transport=tcp"],
                    "username": "1793420000:<your user id>", "credential": "…" } ],
  "iceTransportPolicy": "all", "expiresAt": "2026-11-05T04:13:20.000Z" }

The TURN credentials expire at expiresAt; get new ones with voice:ice { roomId } before building a connection after that. Errors: invalid_state (not live), forbidden / removed_from_room, voice_full (with maxPeers).

Screens: History list and detail

GET/api/me/history?type=&role=&q=&limit=&offset=list, newest first
{ "total": 6,
  "items": [ { "roomId": "…", "code": "3RT8XQ", "title": "Jakarta → Puncak Ride", "type": "journey", "myRole": "host",
               "status": "ended", "startedAt": "…", "leftAt": "…", "peopleCount": 8,
               "distanceMeters": 86200, "trackedSeconds": 20760 } ] }

Filters map to the chips: type = All / Journey / Monitoring, role = Any role / As host / As guest, q = search by name or code. The summary line (“24 events · 1,284 km · 96.5 h live”) comes from GET /me/stats. Group by month of startedAt in the app. “New” badge: compare with the last time the user opened History (app-side).

GET/api/me/history/:roomIddetail

Everything of the list item plus host, endedAt, endReason, stops, meetingPoint, routePolyline, people (host first, with each person's distance), timeline, tracks (≤ 300 points per person, [lat, lng]) for the hero map, and points: your EventPoints for this event (null while it's live or when you weren't eligible).

timeline[].kindShow
joined“You joined the room · Scanned the QR code” (joinMethod) / “eva joined”
started“Event started” / “Monitoring started · GBK gate · host @eva” (meetingPoint, host)
stop_reachedstop.kind: rest → “Rest stop · 25 min”, transit → “Transit · regroup”, finish → “Reached the finish”
left“You left the room” (reason left) / removed by host
endedreason host → “You ended the event” / “Ended by the host”; schedule → “Scheduled time ended”

The host sees everyone's entries; a guest sees their own plus started / ended. Share summary text is built in the app.

Screen: Profile

RowCall
Header (photo, name, username, email)GET /me
Name, username & photo (avatar colour)PATCH /me { displayName?, username?, avatarColor? } (+ GET /auth/username-available while typing)
Language (ID | EN switch)PATCH /me { "language": "id" | "us" } — also send the matching Accept-Language from then on. Emails (reset codes) use this language.
Change passwordPOST /auth/change-password (store the new token)
Permissions (location, microphone)Device settings — no API. Report the effect per room with presence:update.
My points (shows points.current)GET /me → points; tap → Points
Log outPOST /auth/logout

Screen: Points

GET/api/me/points?direction=&limit=&offset=balance, history, rules
{ "balance": { "total": 34.75, "used": 0, "current": 34.75 },
  "total": 2,
  "items": [
    { "id": "…", "direction": "in", "type": "event", "amount": 9.75, "balanceAfter": 34.75, "note": null, "createdAt": "…",
      "event": { "id": "…", "code": "3RT8XQ", "title": "Jakarta → Puncak Ride", "type": "journey" },
      "eventPoints": { "distanceMeters": 57000, "durationMinutes": 240, "restMinutes": 0, "averageSpeedKmh": 14.25,
                       "participationPoints": 1, "distanceScore": 5.7, "distancePoints": 3.42,
                       "durationScore": 13.33, "durationPoints": 5.33, "totalPoints": 9.75, "flags": [] , … },
      "referredUser": null },
    { "direction": "in", "type": "referral", "amount": 25, "balanceAfter": 25, "referredUser": PublicUser, … } ],
  "rules": { "referralPoints": 25, "participationPoints": 1, "minStayMinutes": 18, "participationsPerDay": 3,
             "distanceMinKm": 10, "distanceMaxKm": 1000, "distanceKmPerScore": 10, "distanceWeightPercent": 60,
             "durationMinMinutes": 18, "durationMaxMinutes": 1800, "durationMinutesPerScore": 18,
             "durationWeightPercent": 40, "minAverageKmh": 1, "maxAverageKmh": 120, "minPeople": 2 } }

Newest first. direction = in (earned) / out (spent) for the All / Earned / Used tabs. Show +amount for in and −amount for out; balanceAfter is your current points right after that row. Explain the rules with the numbers from rules rather than copies in the app.

typeShow
event (in)event.title; tap → breakdown from eventPoints
referral (in)“referredUser.displayName used your code”
buy, other (in)Bought points / note (reserved for later)
claim_money, hide_ads, feature, other (out)What the points were used for (reserved for later)

How an event scores (for everyone who was in it while live, from the start or when they joined to the end or when they left):

participation  1                      (at least 18 min live; at most 3 events a day, APP_TIMEZONE)
distance score km ÷ 10, 10 → 1,000 km = 1 → 100     distance points = score × 60 %
duration score ((minutes − rest) ÷ 60 ÷ 30) × 100, 18 min → 30 h of travel = 1 → 100   duration points = score × 40 %
               rest = rest_minutes of the rest stops you reached (stop_reached in the timeline, each stop once)
total          participation + distance points + duration points       (max 101 per event)

57 km, 10:00–14:00:                1 + 5.70 × 60 % + 13.33 × 40 % = 1 + 3.42 + 5.33 = 9.75
… with a 20-minute rest stop:      1 + 5.70 × 60 % + 12.22 × 40 % = 1 + 3.42 + 4.89 = 9.31
flags[]Meaning
short_stayLess than 18 min in the live event → no participation point
daily_limitAlready 3 participation points that day → no participation point
soloFewer than 2 people in the room while it was live (people the host removed don't count) → no distance and no duration points
short_distanceUnder 10 km → no distance and no duration points (e.g. 2 h without moving)
too_fastAverage over 120 km/h (e.g. 100 km in 30 min) → no distance and no duration points
too_slowAverage under 1 km/h (GPS drift, location off for hours) → no distance and no duration points

Event points are given right when the event ends; a sweep every minute retries anything that failed. People the host removed get nothing.

Screens: Communities

Screen / actionCall
Community tab (cards)GET /communities → members (myStatus: member), then waiting requests (myStatus: pending). Badge: sum of pendingCount where canManage.
Create communityGET /community-categories, then POST /communities, then PUT /communities/:id/image (multipart file)
Join (scan / type 4 characters)GET /communities/code/:code (preview) → POST /communities/code/:code/join
Search (name / code / near me)GET /communities/search?q=… and/or &lat=…&lng=… (home base within 10 km) → preview from the result → POST /communities/:id/join
Community pageGET /communities/:id, GET /communities/:id/members, GET /communities/:id/events
“Waiting approval”GET /communities/:id answers the summary with myStatus: pending and requestedAt; DELETE /communities/:id/request withdraws it
Join requests (leader / vice)GET /communities/:id/requests, POST …/requests/:requestId/approve | reject
PositionsPOST /communities/:id/positions, PATCH|DELETE …/positions/:positionId, PUT …/positions/order; assign with PATCH /communities/:id/members/:userId { positionId }
Hand over leadershipPOST /communities/:id/transfer { userId } — the old leader takes the new leader's previous position
New community eventPOST /rooms/journey or /rooms/monitoring with "communityId"
GET/api/community-categoriesCategory list (from the database)
{ "items": [ { "id": 1, "slug": "motorcycle_club", "icon": "motorcycle",
               "name": { "id": "Klub Motor", "us": "Motorcycle Club" } }, … ] }

Edit the community_categories table to change the list (set active = false to hide one). Users can't add categories. Icon keys: motorcycle, car, touring, running, cycling, hiking, backpack, other.

POST/api/communitiesCreate (you become the leader)
{ "name": "Rutemu Riders", "categoryId": 1, "description": "…", "visibility": "public" | "private",
  "address": "Jl. Sudirman 1", "homeBase": { "name": "Basecamp", "address": "…", "lat": -6.2, "lng": 106.8 } }
→ 201 { "community": CommunityDetail }   // code "SR48", joinUrl ".../c/SR48", positions Leader + Vice Leader
POST/api/communities/code/:code/joinJoin (public) or ask to join (private)
{ "method": "qr" | "link" | "code" }
→ { "status": "joined" | "requested", "community": CommunityDetail }

Private: managers get community:requests; the person gets community:approved / community:rejected later. Code lookups are limited to 30 per minute.

GET/api/communities/searchFind communities by name, description, code, or near you
?q=riders                          // part of the name or description, or the exact 4-character code (min 2 characters)
?lat=-7.7956&lng=110.3695          // home base within 10 km of you, nearest first
?q=trail&lat=-7.7956&lng=110.3695   // both
→ { "items": [ CommunitySummary + { "distanceMeters": 2350 | null } ] }

Public and private communities, at most 30. Yours are included (see myStatus). Communities without a home base only show up in text searches. Text order: the code match, then names starting with q, other name matches, description matches. 400 validation_error when neither q nor lat + lng is given. Limited to 60 per minute.

POST/api/communities/:id/joinJoin / ask to join a search result
→ { "status": "joined" | "requested", "community": CommunityDetail }

Same as joining with the code (search results don't carry the code); the join method is search.

GET/api/communities/:id/membersMembers with their activity
{ "items": [ { "user": PublicUser, "position": CommunityPosition | null, "isLeader": true, "canManage": true,
               "joinedAt": "…", "joinMethod": "creator" | "qr" | "link" | "code" | "search",
               "stats": { "community": MemberStats, "overall": MemberStats } } ] }
MemberStats = { "events": 12, "distanceMeters": 845000, "trackedSeconds": 151200, "lastEventAt": "…" | null }

Leader first, then by position rank, then by name. community counts events of this community, overall every event the member joined (events that went live while they were in them). Sort on the phone (position, name, distance, time, newest / oldest member).

GET/api/communities/:id/eventsUpcoming and past events of the community
{ "upcoming": [RoomSummary], "past": [RoomSummary] }   // past: only events you took part in; RoomSummary.community is set

CommunitySummary · CommunityDetail

CommunityRef     { id, name, category: { id, slug, icon, name: { id, us } }, visibility, imageUrl, imageThumbUrl }
CommunitySummary = CommunityRef + { description, address, homeBase: Place | null, memberCount, memberPreview: [PublicUser],
                   leader: PublicUser | null, myStatus: "member" | "pending" | null, myPosition, canManage,
                   pendingCount (managers), nextEvent: { id, title, type, status, startsAt, endsAt } | null, createdAt }
CommunityDetail  = CommunitySummary + { code, joinUrl, positions: [CommunityPosition], isLeader, myJoinedAt, requestedAt }
                   // code, joinUrl and positions only for members
CommunityPosition { id, name, isLeader, canManage, rank, memberCount }
RoomSummary.community: CommunityRef | null   // members-only event

Realtime (Socket.IO v4)

Same host and port as the REST API, path /socket.io, websocket transport. Pass the token in auth; a bad token fails with connect_error message unauthorized. Reconnect after the app returns to the foreground and subscribe again to the open room (subscriptions don't survive a reconnect).

App → server

Every event can take an acknowledgement callback. Acks are { "ok": true, … } or { "ok": false, "error": "<code>", "fields"?: {…} } plus the error's other fields (e.g. maxPeers).

EventPayloadAck
room:subscribe{ roomId }{ ok, room } — active members only (forbidden, removed_from_room, not_found)
room:unsubscribe{ roomId }{ ok }
location:update{ roomId, lat, lng, heading?, speed?, accuracy?, at? }{ ok, accepted, reason? } — reason not_live, not_member, inaccurate, stale, jump
presence:update{ roomId, locationEnabled?, micOn? }{ ok }
voice:join{ roomId, peerId } (UUID){ ok, peerId, resumed, peers, canTalk, maxPeers, iceServers, iceTransportPolicy, expiresAt } — live rooms, active members
voice:signal{ roomId, to, sid, description? { type, sdp } | candidate? { candidate, sdpMid, sdpMLineIndex } | restart? }{ ok, delivered } — delivered: false while that phone reconnects; not_found when it left
voice:ice{ roomId }{ ok, iceServers, iceTransportPolicy, expiresAt } — fresh TURN credentials
voice:leave{ roomId }{ ok }

Server → app

EventPayloadSent toWhen
room:updatedRoom (with your myRole)Everyone subscribedJoin, leave, removal, start, end (also automatic), mic / guestsCanTalk change, edit, someone comes online / goes offline, presence change
locationPosition + roomIdEveryone subscribedAn accepted position
timelineTimelineEntry + roomIdSubscribed (stop_reached: host + that person)joined, left, started, stop_reached, ended
room:started{ roomId }All active members (any screen)Host started
room:ended{ roomId, reason }All active members (any screen)Ended by host or schedule
room:deleted{ roomId }Subscribed + all membersHost cancelled a scheduled room
member:removed{ roomId, userId }The removed personHost removed them
community:requests{ communityId, pendingCount }The community's managersA join request arrived, was approved, rejected or withdrawn
community:approved / community:rejected{ communityId, name }The person who askedA manager answered the request
community:removed{ communityId, name }The removed memberA manager removed them
community:deleted{ communityId, name }All members but the leaderThe leader deleted the community
community:leader{ communityId, name }The new leaderLeadership was handed to them
voice:peer-joined{ roomId, peerId, userId }Phones in the voice roomSomeone joined voice
voice:peer-left{ roomId, peerId, userId }Phones in the voice roomSomeone hung up, left, was removed, or didn't reconnect within 20 s
voice:signal{ roomId, from, fromUserId, sid, description | candidate | restart }One phoneOffer, answer, ICE candidate or restart request from another phone
voice:closed{ roomId, reason }The phone(s) concernedended, left, removed, elsewhere (you joined voice on another device)
// pubspec: socket_io_client: ^3.0.0
import 'package:socket_io_client/socket_io_client.dart' as io;

final socket = io.io(
  'http://10.0.2.2:3000',
  io.OptionBuilder()
      .setTransports(['websocket'])
      .setAuth({'token': token})
      .disableAutoConnect()
      .build(),
);
socket.onConnect((_) {
  socket.emitWithAck('room:subscribe', {'roomId': roomId}, ack: (ack) {
    if (ack['ok'] == true) applyRoom(Room.fromJson(ack['room']));
  });
});
socket.onConnectError((err) { if ('$err'.contains('unauthorized')) logout(); });
socket.on('room:updated', (data) => applyRoom(Room.fromJson(data)));
socket.on('location', (data) => moveMarker(Position.fromJson(data)));
socket.on('timeline', (data) => showNotice(TimelineEntry.fromJson(data)));
socket.on('member:removed', (_) => leaveLiveMap(removed: true));
socket.connect();

// every 2–5 s while live
socket.emit('location:update', {
  'roomId': roomId, 'lat': p.latitude, 'lng': p.longitude,
  'heading': p.heading, 'speed': p.speed, 'accuracy': p.accuracy,
  'at': p.timestamp.toUtc().toIso8601String(),
});

JSON models

PublicUser · Me

PublicUser { "id": "uuid", "username": "eva", "displayName": "Eva Wahyuni", "avatarColor": "#0B7F86" }
Me         PublicUser + { "code": "K7Q2M", "referralUrl": "https://app.rutemu.com/u/K7Q2M", "refCode": null | "AB12C", "email": "angga@example.com", "language": "id" | "us", "createdAt": "ISO",
                          "points": { "total": 19.75, "used": 0, "current": 19.75 } }

Initials (“RP”) are computed in the app from displayName.

RoomSummary · Room

{
  "id": "7505854a-19a1-40b6-bbf8-457d41e4eb4e",
  "code": "K8D2AN",
  "title": "Family day @ Ancol",
  "type": "monitoring",                     // journey | monitoring
  "status": "live",                         // scheduled | live | ended
  "startsAt": "2026-10-30T03:00:00.000Z",
  "endsAt": "2026-10-30T08:00:00.000Z",     // null = unlimited
  "startedAt": "2026-10-30T03:02:00.000Z",
  "endedAt": null,
  "endReason": null,                        // host | schedule
  "host": { PublicUser },
  "myRole": "host",                         // host | guest | null (not a member)
  "memberCount": 6,
  "memberPreview": [ PublicUser ×4 ],
  "routeDistanceMeters": null,              // journey only
  "routeDurationSeconds": null,             // journey only
  "stopCount": 0,                           // journey: all stops incl. start/finish
  "meetingPoint": { "name": "Gate", "address": "…", "lat": -6.1251, "lng": 106.8411 },   // monitoring, may be null
  "joinUrl": "https://app.rutemu.com/j/K8D2AN",
  // ── Room (detail) adds:
  "guestsCanTalk": true,
  "routePolyline": null,
  "stops": [ Stop ],
  "members": [ Member ]
}

Stop · Member · Position

Stop     { "id": "uuid", "position": 2, "kind": "rest", "name": "Rest Area KM 57", "address": null,
           "lat": -6.3486, "lng": 107.2155, "restMinutes": 20 }

Member   { "user": PublicUser, "role": "guest", "joinedAt": "ISO", "joinMethod": "qr",
           "leftAt": null, "leftReason": null,            // left | removed
           "micAllowed": true, "micOn": false,            // micOn/locationEnabled: null = unknown
           "online": true, "locationEnabled": true,
           "lastPosition": Position | null,               // null unless you're an active member
           "distanceMeters": 2400 }

Position { "userId": "uuid", "lat": -6.1279, "lng": 106.8417, "heading": 180, "speed": 1.3,
           "accuracy": 6, "at": "ISO", "distanceMeters": 1710 }

TimelineEntry · Stats · HistoryItem · HistoryDetail

TimelineEntry { "kind": "stop_reached", "at": "ISO", "user": PublicUser | null,
                "joinMethod": null, "stop": Stop | null, "reason": null }

Stats         { "events": 24, "hosted": 9, "joined": 15, "distanceMeters": 1284000, "trackedSeconds": 347400 }

HistoryItem   { "roomId", "code", "title", "type", "myRole", "status", "startedAt", "leftAt",
                "peopleCount", "distanceMeters", "trackedSeconds" }

HistoryDetail HistoryItem + { "host", "endedAt", "endReason", "routeDistanceMeters", "routePolyline",
                "stops": [Stop], "meetingPoint", "people": [{ "user", "role", "distanceMeters" }],
                "timeline": [TimelineEntry], "tracks": { "<userId>": [[lat, lng], …] },
                "points": EventPoints | null }

PointBalance · EventPoints · PointEntry

PointBalance { "total": 19.75, "used": 0, "current": 19.75 }

EventPoints  { "from": "ISO", "to": "ISO", "distanceMeters": 57000, "durationMinutes": 240, "restMinutes": 20,
               "averageSpeedKmh": 14.25 | null,
               "participationPoints": 1, "distanceScore": 5.7, "distancePoints": 3.42,
               "durationScore": 13.33, "durationPoints": 5.33, "totalPoints": 9.75,
               "flags": [] | ["short_stay" | "daily_limit" | "solo" | "short_distance" | "too_fast" | "too_slow"] }

PointEntry   { "id", "direction": "in" | "out", "type", "amount": 9.75, "balanceAfter": 19.75, "note": null, "createdAt": "ISO",
               "event": { "id", "code", "title", "type" } | null, "eventPoints": EventPoints | null,
               "referredUser": PublicUser | null }

All endpoints

MethodPathAuthPurpose
GET/api/health—Up? DB? TURN relay configured?
POST/api/auth/register—Create account
POST/api/auth/login—Log in
GET/api/auth/username-availableoptionalUsername check
POST/api/auth/forgot-password—Email a reset code
POST/api/auth/reset-password—New password with the code
POST/api/auth/change-password✓Change password (new token)
POST/api/auth/logout✓Revoke this token
GET/api/me✓Profile
PATCH/api/me✓Edit profile / language
POST/api/me/referral✓Apply a friend's referral code (once)
PUT/api/me/avatar✓Profile photo (multipart file) → avatarUrl 512 px, avatarThumbUrl 160 px
DELETE/api/me/avatar✓Remove photo (back to initials)
GET/api/me/stats✓Activity numbers
GET/api/me/rooms✓Scheduled + live rooms
GET/api/me/calendar✓Rooms in a date range
GET/api/me/availability✓Overlap check
GET/api/me/history✓History list
GET/api/me/history/:roomId✓History detail
GET/api/me/points✓Points balance and history
POST/api/rooms/journey✓Create journey
POST/api/rooms/monitoring✓Create monitoring
POST/api/rooms✓Create by type (contract)
GET/api/rooms/code/:code✓Join preview
POST/api/rooms/code/:code/join✓Join as guest
GET/api/rooms/:id✓Room detail
PATCH/api/rooms/:idhostEdit room
DELETE/api/rooms/:idhostCancel scheduled room
POST/api/rooms/:id/starthostStart tracking
POST/api/rooms/:id/endhostEnd for everyone
POST/api/rooms/:id/leaveguestLeave
PATCH/api/rooms/:id/members/:userIdhostMic on/off for a guest
DELETE/api/rooms/:id/members/:userIdhostRemove a guest
POST/api/rooms/:id/mute-allhostMute all guests
POST/api/rooms/:id/locationsmemberPositions over HTTP
GET/api/rooms/:id/tracksmemberTrails
GET/api/community-categories✓Category list
GET/api/communities✓Your communities + waiting requests
POST/api/communities✓Create community
GET/api/communities/code/:code✓Community join preview
POST/api/communities/code/:code/join✓Join / ask to join
GET/api/communities/search✓Search by name / code / near me
POST/api/communities/:id/join✓Join / ask to join a search result
GET/api/communities/:idmember / pendingCommunity detail
PATCH/api/communities/:idmanagerEdit community
DELETE/api/communities/:idleaderDelete community
PUT/api/communities/:id/imagemanagerPicture (multipart file)
DELETE/api/communities/:id/imagemanagerRemove picture
POST/api/communities/:id/code/regeneratemanagerNew code + QR
POST/api/communities/:id/leavememberLeave (not the leader)
POST/api/communities/:id/transferleaderHand over leadership
GET/api/communities/:id/membersmemberMembers + activity
PATCH/api/communities/:id/members/:userIdmanagerSet position
DELETE/api/communities/:id/members/:userIdmanagerRemove member
POST/api/communities/:id/positionsmanagerAdd position
PUT/api/communities/:id/positions/ordermanagerReorder positions
PATCH/api/communities/:id/positions/:positionIdmanagerRename / can manage
DELETE/api/communities/:id/positions/:positionIdmanagerDelete position
GET/api/communities/:id/requestsmanagerWaiting requests
POST/api/communities/:id/requests/:requestId/approvemanagerApprove
POST/api/communities/:id/requests/:requestId/rejectmanagerDecline
DELETE/api/communities/:id/requestpendingWithdraw your request
GET/api/communities/:id/eventsmemberCommunity events

Flutter snippets

HTTP client with token, language and error parsing (dio)

// pubspec: dio: ^5.7.0
class ApiError implements Exception {
  ApiError(this.status, this.code, this.message, this.data);
  final int status; final String code; final String message; final Map<String, dynamic> data;
  Map<String, String> get fields => Map<String, String>.from(data['fields'] ?? const {});
}

Dio buildDio({required String baseUrl, required String? Function() token, required String Function() lang}) {
  final dio = Dio(BaseOptions(baseUrl: '$baseUrl/api', connectTimeout: const Duration(seconds: 10)));
  dio.interceptors.add(InterceptorsWrapper(
    onRequest: (o, h) {
      final t = token();
      if (t != null) o.headers['Authorization'] = 'Bearer $t';
      o.headers['Accept-Language'] = lang() == 'id' ? 'id' : 'en';   // AppLanguage.id / .us
      h.next(o);
    },
    onError: (e, h) {
      final body = e.response?.data;
      if (body is Map<String, dynamic> && body['error'] is String) {
        h.reject(DioException(requestOptions: e.requestOptions, response: e.response,
          error: ApiError(e.response!.statusCode!, body['error'], body['message'] ?? '', body)));
        return;
      }
      h.next(e);
    },
  ));
  return dio;
}

// Show errors with the app's own translations, fall back to the server message:
String errorText(BuildContext context, ApiError e) => switch (e.code) {
  'invalid_credentials' => context.tr('auth.errors.invalidCredentials'),
  'username_taken'      => context.tr('auth.register.usernameTaken', {'username': username}),
  'room_ended'          => context.tr('join.errors.ended'),
  'not_found'           => context.tr('join.errors.notFound'),
  _                     => e.message,
};

Parsing a code from a scanned QR / link

String? roomCodeFrom(String raw) {
  final uri = Uri.tryParse(raw.trim());
  final last = (uri != null && uri.pathSegments.isNotEmpty) ? uri.pathSegments.last : raw;
  final code = last.replaceAll(RegExp(r'[\s-]'), '').toUpperCase();
  return RegExp(r'^[2-9A-HJ-NP-Z]{6}$').hasMatch(code) ? code : null;
}

Month range for the calendar

final first = DateTime(month.year, month.month, 1);           // local midnight
final next  = DateTime(month.year, month.month + 1, 1);
dio.get('/me/calendar', queryParameters: {
  'from': first.toUtc().toIso8601String(), 'to': next.toUtc().toIso8601String() });

Database

MySQL 8 (or MariaDB 10.6+), utf8mb4, all times UTC. Created by the TypeORM migration in src/database/migrations.

TableHolds
usersAccounts: 5-character code, ref_code (referrer's code, set once), username, email, display name, bcrypt password hash, avatar colour, language, point_total / point_used / point_current (= total − used, generated)
user_sessionsOne row per logged-in device (the JWT carries its id), so tokens can be revoked
password_resetsHashed 6-digit codes, attempts, expiry
eventsRooms: code, title, type, status, host, window, start/end, route, monitoring meeting point, community_id (members-only), points_awarded_at
event_stopsJourney stops in order (start / transit / rest / finish)
event_membersHost and guests: join method, left/removed, mic, presence, last position, distance
event_track_pointsTrails (thinned: ≥ 10 m or ≥ 30 s apart)
event_timelinejoined / started / stop_reached / left / ended entries
community_categoriesThe categories users pick from (managed in the database)
communitiesName, 4-character code, category, public / private, picture, address, home base pin
community_positionsEach community's own positions: one leader, can_manage, rank
community_membersWho is in which community, with their position and join method
community_join_requestsRequests to join private communities (pending / approved / rejected / cancelled)
event_point_scoresHow each person scored in an ended event: time, rest at rest stops, distance, average speed, participation / distance / duration score and points, flags
point_transactionsPoints history: in (event, referral, buy, other) / out (claim_money, hide_ads, feature, other), amount, balance after
point_transaction_refsWhat each transaction is about (ref_type event / event_score / referred_user + ref_id)

Compared with the rutemu API contract

Every endpoint and event of rutemu-api-contract.md works the same here, with one difference: POST /rooms/:id/end on a scheduled room cancels it and answers { "room": null } (the room is gone). Additions: