Compare commits

...
59 Commits
Author SHA1 Message Date
Burrowdev 8e117ff26f feat: all four pattern colours, the in-game item giver again, and 18 and over
- a special animal's pattern has four colours, as its presets do: the
  pattern tab's 1 to 4 each have a colour table
- the Item Giver opens in the game again; the Item Maker's previews keep
  their own colours instead of the giver's colour box
- the drawn trading sign is gone
- sign-up, the terms and the privacy policy say 18 and over (terms
  version 2026-10-24)
- builds 92
2026-10-24 05:55:42 +03:00
Burrowdev 29c0eff454 fix: an animal adopted of the other kind than the room's no longer shows twice in the switcher
the switch took the animals out of the list by index, as if the one in use
were always first; one of the other kind, just adopted, goes first instead.
the list is now rebuilt by which animal is which. builds 87
2026-10-24 03:53:55 +03:00
Burrowdev f72e346c03 fix: the game starts again: MinigameManager is the game's own once more
recompiled, its static setup threw (#1065) as the game started, and the
game never got past its loading screen; builds 86
2026-10-24 02:12:18 +03:00
Burrowdev 4355994253 fix: eggs, pets, minigames, themes, HQ facts and more
- egg stands sell an egg again; a bought egg hatches and is named at once
- pets whose bits name no pet the game has no longer stop loading
- the adopt-a-pet gift path opens with nothing adopted yet
- Spider Zapper and Wind Rider start with their players: spiders can be
  shot, and Wind Rider is played; Spider Zapper's waves are answered
- Phantom's Treasure can be left from its title screen and level choice
- the Touch Pool's fact window always closes
- the last key in Return of the Phantoms lies where it can be reached
- the Alpha HQ's bios and relics open and close
- a land animal in water (and a sea one on land) is drawn when it stands
- a seasonal theme's room has today's shops in it (lib/themerooms.js)
- the Forgotten Archive sells its own stock, not unfinished pieces
- custom items whose def is gone stay out of trade lists
- the captcha is always shown, and tried again when it fails
- builds 85
2026-10-24 01:57:49 +03:00
Burrowdev c7efda7030 fix: eco items, wall, photo booth, chat emoji, den fixes
- the eco den items work: the Eco Shop sells the real eco items, solar
  panels and wind turbines placed in the den in use earn eco credits, lamps
  switch on while there is power for them, and the eco score earns the
  three eco plaques; a first look gives an account its first credits
- the item giver row opens the web item giver
- a painting that cannot be shown is the Burrow logo, not a wait for good
- Jammer Central's buttons work; What's New shows the newest Jamaa Journal
- the Jammer Wall opens even while the HUD is checking the player's own; a
  photo of an animal wearing nothing is kept; a wall photo of an animal the
  game does not know no longer stops the wall
- the photo booth's paid picture is answered
- emoji no longer push the line off centre; "\" keeps an emote or a
  ":name:" as typed; a repeated line with emoji is sent as it was said
- the emoji button hides with the HUD, not a moment after
- the join date on a player's card stays in its corner
- den items whose def is gone no longer garble the den and the inventory;
  custom pictures in a den no longer stop walking
- the den editor's switch and recycle buttons are always there
- the den inventory scrolls to an eleventh item
2026-10-23 23:00:00 +03:00
Burrowdev 7de41ceed5 feat: redemption codes, world count, den visitor count and more fixes
- codes made in the admin panel (Messages) give an item, gems or
  diamonds through the game's Redeem Code window, which was never
  answered; its "need help?" says what codes are here
- the number of worlds is set in the admin panel (Debug), live
- a den's owner is told how many are in it: the HUD's count and doorbell
- the map counts the player's buddies in each land of their world
- gifts whose item no longer exists, or with a nonsense amount, are no
  gift at all, rather than a window that will not close
- custom item pictures are 256 pixels and 100 KB at most
- the account page's buddies and den visitors fold away
- shops no longer count down "X days left"
2026-10-23 22:25:35 +03:00
Burrowdev 15f321fb00 fix: official game table and lists, feedback, museum and books
recordings of the official game (tools/recorder.js) had its game table and
several generic lists in them:

- lib/games.json follows the official table: the print kits, Brady's lab,
  the carnival games (in the room) and the buddy games have their real
  ids, and every game its "Play!" picture
- lists the server has nothing of its own for are answered as the official
  server did (lib/official-lists.json): the Journey Book's facts, and its
  pages and four of the Chamber of Knowledge's books rebuilt from the media
  files; Jam-A-Gram stamps are the official ones
- feedback windows send to the staff panels' feedback, over the game's own
  connection; museum gem donations are taken (cd)
- fact cards and museum exhibits missing from a list are had by their id
  (factDefs), and their arrows do nothing past the list
2026-10-23 21:52:59 +03:00
Burrowdev 6c273554d7 fix: trading, machine rewards and claw prizes from the owner's list
- a completed trade no longer plays the failure sound over the success one
- a sign over players who are trading, seen by everyone in the room
- every item added to a trade list is shown; lists keep up to 200 items
- the drink, popcorn and cotton candy machines always hand over what they
  made (the game sent nothing when it was like the last one it gave), the
  smoothie machine even when the game it is was not noted down, and the
  server takes a game's message for a moment after it is left
- claw machine, Phantom Invasion and Sky High prizes are the game's own
  items only: a custom item could be missing from the winner's game
2026-10-23 21:29:49 +03:00
Burrowdev 22fb7f0fa5 fix: settings, chat, video spots and other bugs from the owner's list
- Jam-A-Gram privacy: the inbox's options were taken the wrong way round
- report window: no instruction text over the reason
- the museum's theatre and other unnamed rooms get names; every shop a title
- "How did you hear?" is never offered (its window soft locked the game)
- video spots with nothing to play open a "Your Video" box on the game page;
  the trade list's help plays a video; the theatre's box no longer vanishes
- emotes, actions and phrases are limited per player, as typed chat is
- phrases from the menus come in the sender's chat bubble style
- settings: WASD, blocked players and custom items as two-sided switches,
  graphics at their best by default, a switch for bubble animations, and
  Manage Account beside two-step sign-in opens the account page
- pressing a @mention in a bubble no longer walks the player there
2026-10-23 21:12:04 +03:00
Burrowdev e9097a9a4f feat(items): beta-era colours for seven clothing items
colours from a dump of a beta-era inventory, added after each item's own
so the colours already given keep their place: Rare Eyeball Hat, Creature
Mask, Tiara (two), Arctic Hood, Elf Helmet, Furry Hat and Turquoise Ring.
the shop shows a list's first 8, so these are had from the item givers.
2026-10-23 19:56:44 +03:00
Burrowdev 7cfef493fa feat(account): web item giver with colour pickers, den variants, tints and previews
/account/items, linked from the account page and using its sign-in, gives
items to the account signed in:

- clothing: the item's own colours, or four colours of your own as a
  picker, #RRGGBB, or AJ's numbers (palette places, or the whole item's
  colour id signed or unsigned), converted as you type; hex colours not in
  the palette become an exact custom colour
- den items: the variants their art has (lib/den-variants.json, made by
  tools/den-variants.sh) and a whole-item tint with a strength, kept in the
  item's version above the variant and drawn by DenItemHelper (build 83)
- a preview of each: clothing icons coloured on the page as the game
  colours them, den items played by Ruffle in a sandboxed frame through
  public/item-preview.swf (tools/preview-host)

a give with a custom colour id that does not exist is refused.
2026-10-23 19:14:49 +03:00
Burrowdev 44af83f1c5 feat(account): sign in to the account page with the Burrow client
"Sign in with the Burrow client" on the account page's sign-in screen
opens burrow://account?n=<nonce>; the browser asks whether to open
Burrow. The client asks for a ticket with its login token
(POST /account/api/client-ticket) and opens /account/client?ticket= in
the browser, which signs in there. A ticket lasts 2 minutes, is good
once, and signs in only the browser holding the nonce's cookie, so a
burrow:// link from elsewhere signs nobody in and a ticket sent to
someone else opens nothing. The tab that started it follows by itself;
once it has worked in a browser, the page asks for Burrow by itself.
2026-10-23 07:04:45 +03:00
BurrowdevandClaude Opus 5.5 b22708a4ba feat(devices): hardware bans and alts need 3 matching IDs
A computer is taken for a banned one, and an account for an alt, only
when they share at least 3 hardware IDs (system, board, disk, the
client's own); one or two in common was too often someone else's.
Network card addresses still do not count. A hardware ban is refused
for an account with fewer than 3 IDs known, as it could match nobody.
MAC-only ("weak") alts no longer exist, so the flag is gone from the
panels.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 04:46:23 +03:00
SnipzilandClaude Opus 5.5 494f252c5b fix(avatars): switching animals no longer copies the new one over the old
Since 3423df1 the server followed an animal switch ("as") with that
animal's "ad" and full "il". The client swaps animals partway through the
transform animation: at "hideAvatar" it copies the in-world avatar into the
switcher slot being left, then loads the new animal onto the in-world one.
The extra "ad" arrived before that frame, had no request waiting for it, and
so was applied to the in-world avatar, and the "il" then matched it too. The
slot got a copy of the new animal, the old one was gone from the switcher,
and the other slots drew blank until the next login.

This reverts 3423df1. A newly bought animal's editor not opening until the
next login comes back with it and needs a fix that goes through the
client's own "ad" request.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 23:37:06 -04:00
SnipzilandClaude Opus 5.5 6b707fbc1d fix(theatre): a site the client keeps out opens in the player's own browser
The desktop client now shows only a few listed sites in the theatre's
browser (DuckDuckGo and Wikipedia, burrow-client "the browser shows a few
listed sites"), as its old Chromium has holes that will never be mended.
When it keeps an address out, browserState says so: the bar then reads
"<host> opens in your own browser, not here.", with the sites it shows
in the title, and "Open in your browser" hands the address to the client
to open in the system browser. A click on the notice goes back to the
address. A client that sends no `blocked` shows the bar as before.

duckduckgo.com, the browser's start page since 9720d30, is now listed
in .github/allowed-hosts.json, which the security check wanted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 23:06:05 -04:00
SnipzilandClaude Opus 5.5 b45fd195df fix(discord-bot): the public status card counts the players online
publishStatus gave the card players: 0 and rooms: 0, so the public card
always said "0 online • 0 rooms". It now counts world.players() and their
rooms, as /burrow status does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:54:27 -04:00
SnipzilandClaude Opus 5.5 e2454447d9 test(signin): Discord sign-ins take a 2FA code, and email recovery its limits
test/signin.js goes through both dashboards' Discord sign-in against a
stand-in for Discord's OAuth2 API (test/fake-discord.js, loaded into the
server with NODE_OPTIONS), and through email recovery against a mail
webhook of its own: Discord alone opens neither dashboard, a waiting
sign-in is used once and dies after five wrong codes, 2FA is removed by
email only with the password, not right after an email password reset and
never for staff, and one account gets three recovery emails an hour. It
fails without the two commits before it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:54:26 -04:00
SnipzilandClaude Opus 5.5 0da5daabc9 fix(account): removing 2FA by email also needs the password, and never for staff
A recovery link (7dee290) removed 2FA on the email alone, and a password
reset is email alone too, so a player's mailbox was their account, 2FA or
not. For staff, 2FA removed and turned on again with another app made
whoever had the mailbox active staff.

- a 2FA reset by email also takes the account's current password, and is
  refused for 7 days after a password reset by email
  (emailPasswordResetAt), so the two cannot be chained.
- never for an account with a staff role: they ask the admin, whose
  temporary password can turn 2FA off.
- at most three recovery emails an hour for one account, from any address.

The address is still never confirmed, nor shown or changed on the
account page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:54:26 -04:00
SnipzilandClaude Opus 5.5 3b53c8dab8 fix(staff): a Discord sign-in asks for the 2FA code, and the bot needs one too
Since 7dee290 a Discord account linked to a staff member opened the
moderator panel for 12 hours on Discord's word alone, with no password and
no 2FA code, though the normal sign-in asks for both every time; and since
b11ae1d the bot took /moderate and /burrow commands from that Discord
account alone. The link outlives a new password and "sign out
everywhere", so a taken-over Discord account was enough to act as the
staff member. The admin dashboard's Discord sign-in (adminDashboardAccess)
skipped its password the same way.

- /mod/discord/callback and /admin/discord/callback no longer sign in:
  they keep a pending sign-in for 5 minutes (a Strict cookie) and the page
  asks for the linked account's 2FA code (POST .../api/discord/code). Five
  wrong codes and it must start again at Discord. The admin one also needs
  the account to have 2FA on and not be locked.
- the bot's commands and buttons count only for a staff member with a
  panel session that took a code (modpanel.discordBot.commandActor): the
  password sign-in, or Discord and a code; not the game's token sign-in. A
  new password, signing out everywhere or 2FA turned off end those
  sessions (forget), and so the bot's use. Whose Discord it is still keeps
  linked staff out of /discord moderation, and lets them close tickets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:54:26 -04:00
SnipzilandClaude Opus 5.5 83c2fc3b0b feat(chat): custom chat bubbles
Players choose how their chat bubble looks, and everyone sees it.

- style: a gradient of 2 to 5 colour stops (linear at any 45° step,
  radial, or solid), its strength, text and border colours, outline
  thickness 0-4, opacity 25-100%, and an animation (still, pulse, shimmer,
  flow, rainbow) at 40-300% speed. lib/chatstyles.js keeps the one
  canonical form: forgiving for saved accounts, strict for requests.
- in the game: Settings > Chat Bubble > Customize opens an editor with
  presets (Ocean, Sunset, Forest, Midnight, Candy, Rainbow), a palette,
  Swap, Random, Reset and Save, and a live preview. "Custom bubbles: Off"
  draws everyone's bubbles normally on this computer only.
- on the web: the account page has a Chat bubble section with the same
  choices.
- wire: xcs with no fields asks for the saved style, with twelve (or an
  older client's 7, 10 or 11) saves it; the reply is the canonical twelve.
  A typed line ("uc") carries its sender's style after the stock extra
  field, only when it is not the default, so message and type stay where
  the game reads them and unpatched clients are unaffected.

ajclient.swf is built with this and the six client commits before it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:11 -04:00
SnipzilandClaude Opus 5.5 c1a85f9b5d test(smoke): a login choice cannot make a player a guide
Since a860a67 only the admin makes guides, so login_choices' isGuide is
refused; the smoke test still expected it to stick.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:11 -04:00
SnipzilandClaude Opus 5.5 d44612bd08 feat(client): any animation the client has, sent as "sja:<anim>,<flip>"
An action message "sja:<anim>,<flip>" plays animation <anim> (1 to 255)
on the sender's avatar for everyone else, and holds it as their idle
(AvatarWorldView.holdIdleAnim) until they walk or do another action, so the
game's idle refreshes don't stand them back up. Not in minigames. A
client without this finds no action by that name and ignores it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:11 -04:00
SnipzilandClaude Opus 5.5 9156c6e392 fix(chat): actions stay out of the chat history
Doing an action put its wire command (":sitS:", ":sitSW:" and the like)
in the player's own chat history. Actions still animate the avatar; they
are no longer added as chat lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:11 -04:00
SnipzilandClaude Opus 5.5 3930d2dabe feat(client): Expanded Inventory, more and smaller items a row
Strawberry Jam's setting, under Settings: the clothes picker and the
item, den and gift pickers show 3, 4 or 5 items a row instead of the
game's three, each scaled so a row is as wide as before. A + and - at the
avatar editor's item counter step between them. User vars 9009 (on) and
9010 (a row; unset is 5).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:11 -04:00
SnipzilandClaude Opus 5.5 9985ae7625 feat(dens): Back, Front and Auto beside the selected den item
The layer controls move from the den editor's top corner into the selected
item's own buttons (DenItemHolder), under the flip and link buttons'
column: Back, Front and Auto (natural depth). They show only for an item
that can be stacked, reorder it on screen at once, and a mouse-up between
the item and its buttons no longer deselects it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:11 -04:00
SnipzilandClaude Opus 5.5 3139384ef3 fix(client): every worn item drawn from a shared art layer is painted
LayerAnim kept one place and one colour for each requested image, so when
two worn items used the same art layer only the last was drawn. _order now
keeps every place (and its colour) an image is used in, and one image
response paints each of them, in their worn order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:10 -04:00
SnipzilandClaude Opus 5.5 e67fbe95e1 fix(jamagrams): moderators are not held to the Jam-a-Gram send limits
Moderators send follow-up cards while helping players. The server skips its
sends-per-ten-minutes limit for them, and the client's per-recipient
session cap (ECardXtCommManager, now in swf-src and built from there) is
skipped for userInfo.isModerator.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:10 -04:00
SnipzilandClaude Opus 5.5 3423df10f8 fix(avatars): a newly switched-to animal's editor opens
Switching animals ("as") changed the active animal, but the client keeps
an editor model of each animal and was never sent the new one's data or
clothes, so an animal bought this session showed in the switcher and its
editor would not open until the next login. The switch is now followed by
its "ad" and its full item list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:10 -04:00
SnipzilandClaude Opus 5.5 8839f86e6c feat(discord-bot): a public status card with a banner, and log cards with fields
- The status card is the players' card now: a title, "Online" and the
  admin's message, players and rooms, uptime and memory, an optional banner
  image and a "Play Burrow" button. The open report count is staff data and
  is no longer on it.
- The admin page's Discord tab takes a banner image URL (http(s), at most 500
  characters, blank for none), saved as discordBotStatusBanner and named in
  the mod log. GET /burrow-status-banner.png serves a banner of our own.
- The game activity, moderation, bot audit and security logs are one card
  shape (logCard): a summary line, a list of fields and when it was logged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:10 -04:00
SnipzilandClaude Opus 5.5 92ebb4d07c fix(limits): behind Cloudflare, a visitor is their CF-Connecting-IP
With a trusted local proxy the address was the last X-Forwarded-For hop,
which behind Cloudflare is Cloudflare's own edge: every visitor shared a
handful of addresses for the rate limits, and the Turnstile check was sent
an edge as remoteip. When that last hop is in Cloudflare's published
ranges (https://www.cloudflare.com/ips/), CF-Connecting-IP is used, if it
is an address. From anywhere else the header is ignored: someone who
reaches the server directly could otherwise name any address, past the
rate limits, address bans and AJ_ADMIN_ALLOW. Neither header is read
unless config.trustedProxy is on and the request came from loopback.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:42:10 -04:00
SnipzilandClaude Opus 5.5 974f68490e fix(captcha): cap Cloudflare checks in flight, and let a blocked widget be retried
- server: at most config.maxConcurrentCaptchaChecks (AJ_CAPTCHA_MAX_CONCURRENT,
  24 by default, 1 to 100) Turnstile checks wait on Cloudflare at once; past
  that the answer is captcha_unavailable at once, so a slow Cloudflare cannot
  hold thousands of sockets open. The page's policy lets it connect to
  challenges.cloudflare.com too.
- page: public/captcha.js gives up on a widget that has not loaded in 15 s,
  or that loaded without turnstile.render, instead of waiting for ever, and a
  render that throws counts as a failed answer. The game's captcha window says
  to check the connection or a content blocker, with a "Try again" button.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:24:59 -04:00
SnipzilandClaude Opus 5.5 43f2717b44 perf(signup): derive a web sign-up's password off the main thread
POST /api/register used accounts.register, whose scryptSync froze every
player for as long as each password took, so a burst of sign-ups was felt
in the game. accounts.registerAsync checks the same things, derives the
hash on libuv's pool (hashPasswordAsync), checks the name again after it
(another request may have taken it meanwhile) and inserts the account as
before. The game's own Create Account keeps the sync path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:24:59 -04:00
BurrowdevandClaude Opus 5.5 6645bf66b3 fix(theatre): the staff room video window plays, in the Your Video look
The VIDEOS sign's window threw on Play and Stop since 8babe9c
(onTheatreControl read _loc1 for _loc1_, ReferenceError #1065), so a
room video never started. It is now drawn as the page's Your Video box:
cream panel, outlined title, a white link box, green "Play for room"
and red "Stop" pills and the red round close button, over the middle of
the theatre's screen, with no dark cover over the stage. Enter plays,
Escape closes.

ajclient.swf is built with this and the two commits before it;
buildVersion 82.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 20:50:44 +03:00
BurrowdevandClaude Opus 5.5 43ae95fbca feat(filter): the chat filters cover animals' and pets' names
- server: a typed name the filter (lib/chat-filter.txt) stops is
  refused at xrn, with the game's warning and a line in the log; one
  saved before is cleared at login (the animal takes the username, the
  pet is "Pet"). the game's own word-id names are never looked at.
- client: LocalizationManager.translateAvatarName and translatePetName
  pass a typed name through the player's own filter
  (AJClient.filterName), wherever the game shows it. a name cannot be
  left out, so with "Hide the whole message" its words are starred.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 20:50:44 +03:00
BurrowdevandClaude Opus 5.5 34db374527 feat(pets): the pet form's name follows the Usernames / Animal Names switch
Playing as a pet showed the pet's name over it whatever the settings
menu said. Now it shows the player's username, as the switch does by
default, or the pet's name with Animal Names, and changes when the
switch is flipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 20:50:44 +03:00
BurrowdevandClaude Opus 5.5 3256135df3 feat(legal): Burrow is for players 16 and over
The website's sign-up box, the Terms of Service and the Privacy Policy
said 13 and over; they say 16 now, as the client does. The privacy
policy's "or the higher age your country sets (up to 16)" is gone, 16
being that highest age. termsVersion 2026-10-21.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 20:50:44 +03:00
BurrowdevandClaude Opus 5.5 9efb2558fc feat(roles): masterpieces.approve, its own permission
Approving and removing framed paintings was items.approve, which also
judges the items and pictures players make. masterpieces.approve now
guards it, on the server (POST /mod/api/masterpiece) and in the mod
panel's buttons and its "only ones I approved" filter. Moderators and
admins have it by default; seeing the Masterpieces page is still
player.view.

roles.load, once at start (setting permissionSplitMasterpieces): a role
list the admin changed, and a staff member's own grants and denies, that
held items.approve are given masterpieces.approve too, so nobody gains or
loses anything by the split.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 20:50:44 +03:00
BurrowdevandClaude Opus 5.5 9720d309fa feat(theatre): an experimental web browser on the theatre screen
In a theatre, "Browser" puts a web page on the screen for that player
alone, beside "Your Video". The desktop client (1.3.3) draws it in a
sandboxed webview of its own over the game page, which tells it where,
what the game draws over it, and where to go; nothing of it goes to the
server.

- off by default: the admin panel's Debug tab turns it on for everyone
  (setting theatreBrowser). the server marks the game page with
  data-theatre-browser="on" as it sends it (lib/http.js), and the page
  shows the button only when the server allows it and the client says it
  can draw it, so older clients never see a button that does nothing.
- the boxes over the screen share one style (.aj-box), and a clicked
  button no longer keeps Chromium 87's focus ring.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 20:50:44 +03:00
BurrowdevandClaude Opus 5.5 64eab1f8ad ci: allow the theatre's YouTube and Vimeo players
8fb5cfe's own-video player names www.youtube-nocookie.com and
player.vimeo.com in public/game.html, which the security check's
invariants refused: neither was in .github/allowed-hosts.json.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 20:50:44 +03:00
BurrowdevandClaude Opus 5.5 a8ab031616 fix(discord-bot): start the server without discord.js installed
b11ae1d made the server load discord.js at start, through lib/discordbot.js,
even with the bot off. update.sh installs no npm packages, so prod had none,
and every start failed with "Cannot find module 'discord.js'".

- lib/discordbot.js loads discord.js when the bot starts (a token and guild
  id set), not with the server. without the package the bot stays off, with
  a line in the log, and the panel's Start says to run npm ci. the two
  message flags cards use are written as numbers, and the slash commands
  are made when they are synchronized.
- deploy/update.sh runs npm ci --omit=dev when package-lock.json changed or
  node_modules is missing. a failed install leaves the bot off; the game
  needs no package.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 12:16:57 +03:00
Snipzil b11ae1dfa8 feat: add unified Discord bot and dashboard 2026-10-20 22:13:50 -04:00
Snipzil 113bf9342e fix: show developer badge to all players 2026-10-20 22:13:50 -04:00
Snipzil 131fb8b025 docs(contributing): add security guidelines for GitHub webhooks
Include instructions on verifying route signatures for signed push
webhooks and precautions against exposing webhook secrets in logs,
commits, or pull requests.
2026-10-20 21:42:02 -04:00
Snipzil 8afc66de21 docs: add CONTRIBUTING.md
Add a contribution guide outlining local setup instructions,
testing requirements, security protocols, and development standards
for the project.
2026-10-20 20:35:20 -04:00
Snipzil 059f059a9e Merge branch 'main' of https://github.com/burrow-dev/burrow-server 2026-10-20 19:16:08 -04:00
Snipzil d20920dc3c chore(deploy): add OpenRC support and deployment helpers
Add OpenRC service and configuration files to support automated server
updates on systems without systemd timers.

- Add `deploy/update-loop.sh` to handle periodic updates for OpenRC.
- Add `deploy/burrow-update.openrc` and `deploy/burrow-update.conf`.
- Update `deploy/update.sh` to support both systemd and OpenRC service
  restarts.
- Add `deploy/README.md` with installation instructions.
- Update `.gitignore` to allow the deployment documentation.
2026-10-20 19:16:04 -04:00
BurrowdevandClaude Opus 5.5 8fb5cfe6d8 feat(theatre): a video of your own on the theatre screen, fitted to it
In a theatre, "Your Video" opens a box for a YouTube, Vimeo or .mp4 /
.webm / .mp3 link that plays for that player alone; nothing of it goes to
the server. A staff video for the room comes first and the player's own
waits for it.

The game now tells the page where the theatre's screen is
(AJClient.reportTheatreScreen: the original player's 512 by 288, in stage
coordinates), so both videos sit exactly on it at any window size. It
also tells which parts of it the game's windows, buttons and chat
balloons are drawn over, and the page cuts those out of the videos and
hides its controls under them: a web page is otherwise always drawn over
the game.

The box is in the game's own look. Desktop players need client 1.3.2,
which lets the game page load the video players and the one file link the
player chose. buildVersion 78.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 02:13:42 +03:00
BurrowdevandClaude Opus 5.5 8368692b99 feat(modpanel): the mod log as its own page
The admin panel's "What they did" table, in the moderator panel too: the
latest 300 entries. A new permission, staff.log, which moderators and
admins have by default, guards the page and its route.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 23:44:16 +03:00
BurrowdevandClaude Opus 5.5 0f367c55b8 feat(admin): a temporary password for a player who lost access
The account view's Lost access box gives the account a new random password
(12 characters, none that look alike), shown once with a Copy button. It
signs them out everywhere and forgets trusted devices; "Turn off their 2FA
too" is for a lost authenticator. Written to the mod log, without the
password.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 23:44:16 +03:00
BurrowdevandClaude Opus 5.5 a860a67626 feat(guide): guides only by the admin, and seen by everyone
The login's Guide option made a player a guide on their own screen only:
the room's avatar packet never said so, so everyone else drew a plain
player. "ac" now sends the guide field (bit 4, after a blend colour of 0),
which gives the guide's name tag and chat bubble on every client.

Guide is now given in the admin panel (Make guide / Remove guide, logged).
Asked for at login by anyone else, it is refused, with a plain message on
arrival. A guide's custom client can still leave it off; the official
launcher asks nothing, and a guide shows as one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 23:44:11 +03:00
BurrowdevandClaude Opus 5.5 da9f2fd5a6 feat(rules): the game's rules window shows data/rules.txt
The rules were written into the client, so changing them meant a new
build. GET /rules.txt reads data/rules.txt on every ask (no restart
needed; data/ is what prod keeps between deploys and lets the server
write), making it with "Example" when there is none. The rules window
fetches it each time it opens: a line starting "# " is a heading in the
old rules' heading style, the rest is shown as it is written (escaped,
never HTML). 64 KB at most. buildVersion 75.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 16:26:12 +03:00
BurrowdevandClaude Opus 5.5 0c3bfd97b3 feat(masterpieces): daily limit, a day's wait, the same picture approved again
- accounts under a day old cannot paint for a frame: the easel's token is
  refused and a message box says how long is left
  (AJ_MASTERPIECE_MIN_AGE, 86400; the tests use 0).
- 10 new pictures an account in any 24 hours (config.masterpiecesPerDay),
  counted in the database (masterpiece_uploads) so a restart does not
  forget them; past it HQ says when the next one may go. a picture
  approved before is not a new one.
- a picture a moderator or the admin approved is approved again as it is
  framed, and the same picture waiting is approved with it, its makers
  told: the same file (SHA-256), or the same painting saved and painted
  again, which comes back as other bytes. lib/jpegprint.js reads every
  8x8 block's average from a baseline JPEG's DC coefficients (~2.6 ms for
  the Art Studio's 711x434); the same size with no block more than 2 of
  255 apart is the same picture (a saved .ajart painted again: 1).
- staff taking a painting back forgets its picture.
- paintings from before get their hash and fingerprint a few at a time
  after start; those a person approved make their pictures approved ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 16:21:20 +03:00
BurrowdevandClaude Opus 5.5 096ceafea7 feat(pets): play as your pet in any room, from the pet chooser
A switch in the pet chooser (the settings menu's own On/Off switch, at
the top left of the pet's picture) puts the pet that is out in the
avatar's place, for everyone, as at a Play-As-Your-Pet party: the pet
at the party's size where the avatar stands, turning as it walks, its
name on the name bar, chat balloons and emotes over it, the pet in the
HUD. Hidden at the party itself.

- kept as user var 9008 (9007 is the performance profile), so it holds
  through rooms and logins and is kept for the next pet when the pet is
  put away. the server tells the room by user communication type 13,
  also to players coming in later.
- WorldPet and AvatarWorldView ask the avatar's own form instead of the
  room-wide party test; a pet that cannot come into the room leaves the
  avatar shown.
- the type-13 handler read a variable it never set, so every client took
  every message for "off" and nobody else saw the form.
- the action menu's pet button does the pet's trick again (5c9b2e0 had
  made it the switch, which only hid the avatar).

Flying pets keep to the ground's walls (the party lets them over).
buildVersion 74.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 15:25:35 +03:00
BurrowdevandClaude Opus 5.5 2344270291 feat(music): staff upload MP3s as den music tracks
A "Music" page in both panels: an MP3 (MPEG layer III frames, 4 KB to
15 MB) becomes a den music track at once, with no restart.

- lib/custommusic.js: a custom den item made from "Jam On" (614) with a
  new `audio` column, the file's version. Its abbrName is
  CustomMusic<id>_<version>, which the content handler answers from
  data/custom-music/<id>-<version>.mp3, so a new upload is a new name and
  no game plays an old copy from its cache.
- games get it by "xdi" with no client change; players from the item
  finder, or the shop when staff tick "on sale".
- deleting it takes it from every inventory and removes the file.
- /mod/api/music and /admin/api/music: list, play, upload (name, cost,
  inShop in the query), delete; 30 uploads an hour per staff member;
  "music uploaded"/"music deleted" in the mod log.
- new permission music.upload, on the Admin role by default; a role list
  the admin has changed needs it ticked. The panels' CSP allows
  media-src 'self' for the preview players.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 15:25:27 +03:00
BurrowdevandClaude Opus 5.5 a77a1bcfb4 fix(pets): name a hatched egg without throwing
"pn" (EggPetHatchedPopup) saved `account`, which that handler never
defined since aa455f5: a ReferenceError after the name was set in
memory, so no reply went out and the game's loading spiral never ended,
and the name was not saved, so the popup came back at every login.
"account is not defined" at lib/pets.js in prod's log several times an
hour since 10-17.

qol.js names the egg it buys and waits for the answer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 15:25:12 +03:00
BurrowdevandClaude Opus 5.5 04b8d325ea perf(defpacks): make the item packs again without holding the game up
A custom item change made the item and name packs again on the next
fetch, on the one thread every game shares: ~360 ms at 5000 items,
~1.6 s at 50000, after every change, players making them many times a
minute. Nearly all of it was the AMF3 writer.

- the writer fills one growing buffer instead of a Buffer per value
  (byte-identical output, checked against the old one on every cached
  pack): the item pack 230 -> 52 ms at 5000 items, 1524 -> 231 ms at 50000.
- a changed pack is made again at most every AJ_PACK_REMAKE_MS (15 s);
  until then the one made before goes out with the custom item version
  it has, and customItems.sendAll sends a game logging in what its packs
  lack by that version. one remake at a time; deflated on libuv's threads.
- tests make the packs again at once (AJ_PACK_REMAKE_MS=0), and a run of
  the items test checks the throttled case.

Busy evening simulated in-process (a change every 3 s, packs fetched
6 a second, 30 s): longest hold-up 329 -> 61 ms at 5000 items, 1648 ->
359 ms at 50000 (p99 240 -> 6 ms).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 14:44:07 +03:00
BurrowdevandClaude Opus 5.5 c5b1bc37d9 fix: send a game at login only the custom items its packs lack
Every custom item's full def row went to every game at login, though the
item and name packs it fetched minutes before already have them all: with
5000 clothing and 452 den items that was 3.3 MB, 4.2 MB with the colours,
over the send backlog limit (94b8de8 raised it).

- a fetch of the item, den item or name pack notes, per address, how far
  the custom items had changed; at login a game is sent the items changed
  since, and those with a picture (the packs have no pictures). an address
  that fetched nothing lately is sent all, as before.
- "xdi" rows carry the fields the client reads (addItemDef,
  addDenItemDef), not the whole base row, and clothing is for any animal
  as in the pack.
- accounts keep a digest of the state last written, not a copy of it
  (~13 KB an account, ~185 MB on prod).

Measured locally with prod-sized data (20000 colours, 5452 items, 14k
accounts): the login burst 4.2 MB -> 1.5 MB (the colours are most of what
is left), live heap after start 419 -> 297 MB.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 14:44:07 +03:00
Snipzil 9f69b3511b fix(dashboard): keep player search and review data current
Prevent slow or periodic account/player lookup responses from replacing a newer search, make both dashboard layouts usable on narrow screens, and use the unified dashboard masterpiece routes for staff and owner review images. Propagate approved username changes through moderation-facing history and cover report-name propagation with an end-to-end regression test.
2026-10-19 12:29:09 -04:00
Snipzil 8e7b193621 fix(world): replay active actions for late room joins
Remember a standing avatar's valid action and mirror marker, replay it after avatar creation for players entering or reloading a room, and clear it on movement or exit. Add an end-to-end regression test for late join animation sync.
2026-10-19 12:14:02 -04:00
128 changed files with 29525 additions and 2520 deletions

No files matched your search

+5 -2
View File
@@ -3,12 +3,15 @@
"ajcontent.akamaized.net",
"burrow.moe",
"cdn.jsdelivr.net",
"discord.com",
"challenges.cloudflare.com",
"discord.com",
"duckduckgo.com",
"play.burrow.moe",
"player.vimeo.com",
"vision.googleapis.com",
"www.cloudflare.com",
"www.w3.org"
"www.w3.org",
"www.youtube-nocookie.com"
],
"swf": [
"academy.animaljam.com",
+27 -8
View File
@@ -4,7 +4,8 @@
// what the security audit of 2026-10-16 found true of this server, checked on
// every push so that it stays true (or is changed on purpose):
//
// - it uses no npm packages, so there is no supply chain to break into
// - it has only the one pinned Discord gateway dependency needed by the
// optional staff bot; additions are refused to keep the supply chain small
// - the server code starts no other programs and runs no generated code
// - the server code names no web address outside .github/allowed-hosts.json
// - no private key, certificate key or .env file is committed
@@ -22,17 +23,35 @@ const tracked = execFileSync("git", ["ls-files", "-z"], {encoding: "utf8"}).spli
const problems = [];
const fail = (file, message) => problems.push({file, message});
// no npm packages
// The server stayed dependency-free until the optional Discord staff bot. Its
// maintained gateway/components implementation is pinned exactly and captured
// in package-lock.json; no other package is permitted without deliberately
// extending this allowlist and its review surface.
const pkg = JSON.parse(fs.readFileSync("package.json", "utf8"));
const ALLOWED_DEPENDENCIES = {dependencies: {"discord.js": "14.26.4"}};
for (const field of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies", "bundledDependencies"]) {
if (pkg[field] && Object.keys(pkg[field]).length) {
fail("package.json", `${field} is not empty. The server has no npm packages on purpose; if one is really needed, change this check in the same pull request and say why.`);
const actual = pkg[field] || {};
const allowedDependencies = ALLOWED_DEPENDENCIES[field] || {};
if (JSON.stringify(Object.keys(actual).sort().map(name => [name, actual[name]])) !== JSON.stringify(Object.keys(allowedDependencies).sort().map(name => [name, allowedDependencies[name]]))) {
fail("package.json", `${field} differs from its approved dependency allowlist. Keep dependencies empty except for the pinned Discord staff-bot gateway, or deliberately update this check and explain why.`);
}
}
for (const lock of ["package-lock.json", "yarn.lock", "pnpm-lock.yaml"]) {
if (tracked.includes(lock)) {
fail(lock, "a lockfile means npm packages; see package.json above.");
for (const lock of ["yarn.lock", "pnpm-lock.yaml"]) {
if (tracked.includes(lock)) fail(lock, "use the reviewed package-lock.json; alternate package-manager lockfiles are not allowed.");
}
if (fs.existsSync("package-lock.json")) {
try {
const lock = JSON.parse(fs.readFileSync("package-lock.json", "utf8"));
if (lock.lockfileVersion !== 3 || lock.packages?.[""]?.dependencies?.["discord.js"] !== "14.26.4") {
fail("package-lock.json", "must be the npm v3 lockfile for the pinned [email protected] dependency.");
}
}
catch {
fail("package-lock.json", "is not a readable npm lockfile.");
}
}
else {
fail("package-lock.json", "is required to review the pinned Discord bot dependency.");
}
// the server's own code: what the game server runs
@@ -88,4 +107,4 @@ if (problems.length) {
}
process.exit(1);
}
console.log(`${serverCode.length} server files and ${tracked.length} tracked files checked: no packages, no program starts or generated code, no unlisted hosts, no keys, everything parses`);
console.log(`${serverCode.length} server files and ${tracked.length} tracked files checked: only the pinned Discord bot dependency, no program starts or generated code, no unlisted hosts, no keys, everything parses`);
+2
View File
@@ -20,6 +20,8 @@ __pycache__/
# internal markdown files
*.md
!deploy/README.md
!/CONTRIBUTING.md
/HANDOFF.md
/DISCOVERIES.md
/GOING-PUBLIC.md
+77
View File
@@ -0,0 +1,77 @@
# Contributing to Burrow
Thanks for helping make Burrow safer, kinder, and more reliable. Keep changes small, explain the player-facing effect, and open a pull request against the repository's default branch.
## Local setup
Use Node.js 22.5 or later, Git, and an existing checkout containing the tracked client and cached game assets. Install the reviewed runtime dependency with:
```sh
npm ci
```
Run the server with:
```sh
npm start
```
The local web server defaults to `http://127.0.0.1:8080` and the game server to port `9339`. Do not commit `data/`, `cache/`, `.env` files, tokens, recovery-mail credentials, Discord bot tokens, or production exports.
## Before opening a pull request
Run the smoke suite and repository invariants from the repository root:
```sh
npm test
node .github/scripts/invariants.js
```
Add focused coverage under `test/` when changing a game protocol, permissions, account state, moderation, or web route. Explain any test that cannot run locally and include the exact failure output.
Use Conventional Commit messages; the pull-request workflow checks them. Keep the change limited to its purpose and describe security implications, especially for authentication, staff permissions, moderation, player data, network input, or media.
## Security requirements
Burrow handles account credentials, 2FA, game sessions, player reports, and moderation records. Treat every browser, game, and Discord input as untrusted.
- Never log, display, or commit passwords, session tokens, recovery links, IP addresses, device identifiers, private keys, or bot tokens.
- Do not add web hosts, execute programs from server code, evaluate generated text, or add dependencies without updating and explaining the invariant checks.
- `[email protected]` is the only approved runtime dependency. Keep it exactly pinned and update `package-lock.json` in the same pull request when its reviewed version changes.
- Preserve permission checks and staff-rank protections. New moderation actions must use the existing role model and leave an audit record.
The CI security workflow parses all server JavaScript, checks allowed external hosts, scans commits for secrets, and reviews the Flash files that clients load.
## Discord bot changes
The optional Discord staff bot is enabled only with `AJ_DISCORD_BOT_TOKEN` and `AJ_DISCORD_GUILD_ID`. It trusts a Discord user only after the user has linked that identity to an active Burrow staff account with 2FA. Do not create an alternate Discord-only permission system.
All visible bot messages, including errors, status cards, reports, audit logs, and interaction updates, must use Discord Components V2: set `MessageFlags.IsComponentsV2` and use containers/text displays rather than `content` or embeds. Keep player-supplied text safe from mentions and avoid relaying chat, addresses, device data, or tokens to Discord.
GitHub update cards are produced only from signed push webhooks. Keep that route signature-verified before parsing or posting a payload, limit request size, and do not expose webhook secrets in commits, logs, cards, or pull requests.
## Server and panel changes
The server code lives in `lib/`; browser pages live in `public/`; protocol behavior is primarily in `lib/world.js` and the related feature modules. Reuse the panel's shared moderation action path instead of copying bans, warnings, silences, or rank checks into a new surface.
Document new environment variables in `README.md`. Make optional integrations fail closed or remain disabled when configuration is absent; they must never stop gameplay, moderation records, or account storage when an external service is unavailable.
## Client and asset changes
Changes under `swf-src/` require rebuilding the tracked client with Java and JPEXS/FFDec:
```sh
tools/build-client.sh
```
On Windows, run the script through Git Bash or an equivalent POSIX shell. Commit both the source change and the resulting `swf/ajclient.swf` when the client is changed. Do not edit files under `tools/decompiled/` unless the build tool explicitly consumes that source; they are reference output.
Badge artwork is generated by `tools/make-badges.py`; follow the script's usage notes and commit all generated badge assets together.
## Pull-request checklist
- [ ] The change has a clear player, staff, or maintenance outcome.
- [ ] Tests and invariants pass, or the exception is explained.
- [ ] No secret, personal data, cache, database, or generated local output is included.
- [ ] New Discord output uses Components V2 and respects the existing permission/audit model.
- [ ] Client source and rebuilt SWF are both included when applicable.
+10
View File
@@ -5,6 +5,16 @@ Burrow is a private server for AJ Classic.
Set `AJ_RECOVERY_MAIL_URL` and `AJ_RECOVERY_MAIL_TOKEN` to an HTTPS mail-relay or transactional-email webhook. Burrow posts `{to, subject, text}` with a Bearer token. Until both are configured, email recovery intentionally does not issue a usable reset link. New web sign-ups are asked for a recovery email; password and 2FA recovery require the one-time link sent there.
## Discord staff bot
Set `AJ_DISCORD_BOT_TOKEN` and `AJ_DISCORD_GUILD_ID` to enable Burrow's Discord bot. It registers `/burrow status|player|reports|staff|announce`, `/moderate warn|silence|unsilence|kick|ban|unban`, and Discord-server moderation commands `/discord timeout|untimeout|kick|ban|unban|purge`. A Discord user must first link their account through Burrow's existing Discord sign-in and hold active Burrow staff status with 2FA; every command then follows the same role permissions, staff-rank safeguards, actions, and audit log as the moderator panel. Discord-native actions cannot target active linked Burrow staff accounts and also require the bot's Discord role to have the matching server permission.
`AJ_DISCORD_REPORTS_CHANNEL_ID` optionally posts each new in-game report with a **Mark handled** button. `AJ_DISCORD_STATUS_CHANNEL_ID` optionally maintains a public live-status card. Set `AJ_DISCORD_GAME_LOGS_CHANNEL_ID` for player sign-in/sign-out logs, `AJ_DISCORD_MOD_LOGS_CHANNEL_ID` for the full moderation audit trail (web panel, in-game staff commands, admin actions, and Discord moderation), and `AJ_DISCORD_BOT_LOGS_CHANNEL_ID` for Discord command/button audit events. Game logs deliberately omit IPs, device IDs, auth tokens, and chat text. All bot replies and notifications use Discord Components V2 (containers and text displays), not legacy message content or embeds.
The owner dashboard's **Discord** tab can start, stop, reconnect, and synchronize the bot; edit notification-channel IDs, the GitHub repository, public status card, security rules, support-ticket settings, and welcome/goodbye notices; and publish the public card immediately. Environment values supply the initial channel configuration. The bot token, guild ID, and GitHub webhook secret deliberately stay in the server environment rather than in the dashboard database.
For GitHub update cards, set `AJ_GITHUB_REPOSITORY` to `owner/repository`, `AJ_GITHUB_WEBHOOK_SECRET`, and `AJ_DISCORD_UPDATES_CHANNEL_ID`. Then add a GitHub webhook for `https://your-public-burrow-host/discord/github`, choose `application/json`, use the same secret, and subscribe to **Pushes**. Signed pushes appear as polished Components V2 cards with commit summaries and a GitHub compare button; commits that change the Flash client or client assets are labelled **Game update**, while other pushes are **Server update**.
# Security
An independent security audit by a Strawberry Jam contributor, who is not part of the Burrow team, found no malware in the Burrow client or server (client v1.2.0, server as of 17 October 2026). Every file in every installer was checked against its source and against the official Electron, NSIS and Adobe Flash releases. The report also lists the weaknesses found, with fixes, and every check can be repeated by anyone.
+40 -3
View File
@@ -101,6 +101,10 @@ module.exports = {
// tried or an account is made, with both set. off without them.
turnstile: env.AJ_TURNSTILE_SITE_KEY && env.AJ_TURNSTILE_SECRET
? {siteKey: env.AJ_TURNSTILE_SITE_KEY, secret: env.AJ_TURNSTILE_SECRET} : null,
// A stalled CAPTCHA provider must not consume all of the VPS's outbound
// sockets. This only limits simultaneous verification requests; normal
// players use one, and a rejected request can safely be retried.
maxConcurrentCaptchaChecks: Math.max(1, Math.min(100, Number(env.AJ_CAPTCHA_MAX_CONCURRENT) || 24)),
// Account-recovery mail is delivered to this HTTPS webhook. It receives
// {to, subject, text}; point it at the transactional-mail provider or
@@ -134,6 +138,19 @@ module.exports = {
clientSecret: env.AJ_DISCORD_CLIENT_SECRET || "",
botToken: env.AJ_DISCORD_BOT_TOKEN || "",
guildId: env.AJ_DISCORD_GUILD_ID || "",
// Optional Components V2 notification channels. Leave any empty to
// disable that stream: reports, public status, game joins/leaves, the
// moderation audit trail, and Discord bot command/audit events.
reportsChannelId: env.AJ_DISCORD_REPORTS_CHANNEL_ID || "",
statusChannelId: env.AJ_DISCORD_STATUS_CHANNEL_ID || "",
gameLogsChannelId: env.AJ_DISCORD_GAME_LOGS_CHANNEL_ID || "",
moderationLogsChannelId: env.AJ_DISCORD_MOD_LOGS_CHANNEL_ID || "",
botLogsChannelId: env.AJ_DISCORD_BOT_LOGS_CHANNEL_ID || "",
// A signed GitHub push webhook at /discord/github can turn commits into
// a Components V2 update card. All three values are needed to enable it.
githubRepository: env.AJ_GITHUB_REPOSITORY || "", // owner/repository
githubWebhookSecret: env.AJ_GITHUB_WEBHOOK_SECRET || "",
updatesChannelId: env.AJ_DISCORD_UPDATES_CHANNEL_ID || "",
},
deployVersion: env.AJ_DEPLOY_VERSION || "1830",
// older builds the CDN still serves, asked in turn for a room file the
@@ -153,9 +170,11 @@ module.exports = {
// 41: the game's text says "Burrow" where it said Animal Jam.
// 48: the item giver (the item finder renamed) with previews and hex colours;
// 49 and 50: its link to a colour picker.
// 61: the Owner, Moderator and Verified name tag badges seen by everyone.
// 61: the Owner, Moderator, Developer and Verified name tag badges seen by everyone.
// 62: "Custom pictures" in the settings menu, to hide players' item pictures.
buildVersion: env.AJ_BUILD_VERSION || "71",
// 83: den items tinted (the tint in their version, DenItemHelper.applyTint).
// 84: fixes from the owner's list of bugs (bugs.txt, 2026-10-23).
buildVersion: env.AJ_BUILD_VERSION || "92",
// what the official CDN is asked for; not ours to change.
upstreamBuildVersion: "3",
@@ -188,7 +207,7 @@ module.exports = {
// are written into both pages. the emails and the host's country are
// placeholders until set; the operator is, at the owner's word, said to
// be in the EU without a name or a country.
termsVersion: "2026-10-17",
termsVersion: "2026-10-24",
legalEmail: env.AJ_LEGAL_EMAIL || "[email protected]",
adminEmail: env.AJ_ADMIN_EMAIL || "[email protected]",
operator: env.AJ_OPERATOR || "an individual based in the European Union",
@@ -297,6 +316,9 @@ module.exports = {
// world N after the Nth name of its own list (551 Aldan, 552 Congo...,
// generic list 16), so the names here are only for the panels and logs.
// AJ_WORLDS: how many (the tests' is one).
// the admin panel can change how many while the server runs (lib/world.js
// setWorldCount), which then outlasts a restart.
worldNames: ["Aldan", "Congo", "Draa", "Grande", "Kama", "Nile", "Pecos", "Ramu", "Tigris", "Zambezi"],
shards: ["Aldan", "Congo", "Draa", "Grande", "Kama", "Nile", "Pecos", "Ramu", "Tigris", "Zambezi"]
.slice(0, Math.min(10, Math.max(1, Number(env.AJ_WORLDS) || 2))).map((name, i) => ({id: i + 1, name})),
maxUsersPerRoom: 40,
@@ -327,6 +349,14 @@ module.exports = {
cacheMissesPerTenMinutes: 1500, // a first visit with an empty cache fetches several hundred files
upstreamTimeoutMs: 20000,
maxCacheBytes: Number(env.AJ_MAX_CACHE_MB || 8192) * 1024 * 1024,
// how often at most the packs with custom items in are made again after
// one changes (lib/defpacks.js clientPack); the tests use 0, made at once.
packRemakeMs: env.AJ_PACK_REMAKE_MS === undefined ? 15000 : Number(env.AJ_PACK_REMAKE_MS),
// masterpieces (lib/masterpieces.js): seconds an account must have had
// before it paints one (AJ_MASTERPIECE_MIN_AGE; the tests use 0), and new
// pictures an account may post in any 24 hours.
masterpieceMinAccountAge: env.AJ_MASTERPIECE_MIN_AGE === undefined ? 86400 : Number(env.AJ_MASTERPIECE_MIN_AGE),
masterpiecesPerDay: 10,
maxConnections: 2000,
maxHttpConnections: 2000, // open at once, in all
maxHttpConnectionsPerAddress: 40, // the game opens a good many at once while it loads
@@ -355,6 +385,13 @@ module.exports = {
chatLogDays: env.AJ_CHAT_LOG_DAYS === undefined ? 30 : Math.max(0, Number(env.AJ_CHAT_LOG_DAYS) || 0),
chatLinesPerWindow: 5, // typed chat lines one player may send ...
chatWindowMs: 3000, // ... in this long
roomActionsPerWindow: 6, // emotes, actions and the like one player may send a room ...
roomActionWindowMs: 3000, // ... in this long (the rest reach nobody)
// eco den items (lib/eco.js): credits an hour for each point of eco power
// placed in a den, and what an account is given the first time it looks
// (an Eco Solar Panel's price)
ecoCreditsPerPointHour: 1,
ecoStartCredits: 1500,
maxBytesPerTenSeconds: 512 * 1024, // per game socket; saving a full den is about 40 KB
// custom colours (lib/colours.js). every one ever made is sent to every
// player at every login and is never taken out again, so there is an end
+31
View File
@@ -0,0 +1,31 @@
# Deployment helpers
`update.sh` fetches the configured branch, fast-forwards only, validates changed
JavaScript, and restarts the server only when a loaded server file changed. It
runs as root, but uses `BURROW_USER` for Git operations.
## systemd
The existing `burrow-update.service` and `burrow-update.timer` check for an
update every two minutes.
## OpenRC
The OpenRC service keeps a small foreground loop alive and runs the same
updater every two minutes. It does not require cron.
```sh
install -m 755 deploy/burrow-update.openrc /etc/init.d/burrow-update
install -m 644 deploy/burrow-update.conf /etc/conf.d/burrow-update
rc-update add burrow-update default
rc-service burrow-update start
```
Uncomment and change values in `/etc/conf.d/burrow-update` when the server is
not installed at `/home/aj/ajc-private-server`, runs as a different user, or
uses a differently named OpenRC service. `BURROW_UPDATE_INTERVAL` is a positive
number of seconds and defaults to `120`.
`update.sh` selects OpenRC automatically when run by OpenRC. Set
`BURROW_INIT=openrc` when running it manually or from another supervisor. Set
`BURROW_INIT=systemd` to force systemd.
+9
View File
@@ -0,0 +1,9 @@
# Copy to /etc/conf.d/burrow-update to override these values for OpenRC.
# This file is intentionally safe to source as a shell configuration file.
# BURROW_DIR=/home/aj/ajc-private-server
# BURROW_USER=aj
# BURROW_SERVICE=burrow
# BURROW_BRANCH=main
# BURROW_UPDATE_INTERVAL=120
# BURROW_INIT=openrc
+17
View File
@@ -0,0 +1,17 @@
#!/sbin/openrc-run
# Install as /etc/init.d/burrow-update (see deploy/README.md).
description="Update the Burrow server from GitHub"
supervisor=supervise-daemon
command=/bin/bash
command_args="${BURROW_DIR:-/home/aj/ajc-private-server}/deploy/update-loop.sh"
pidfile="/run/${RC_SVCNAME}.pid"
stopgroup=yes
# update.sh uses this to choose rc-service when it restarts Burrow.
: "${BURROW_INIT:=openrc}"
export BURROW_INIT
depend() {
need net
}
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
# Runs update.sh repeatedly for init systems without a timer facility.
set -u
interval=${BURROW_UPDATE_INTERVAL:-120}
case "$interval" in
''|*[!0-9]*)
echo "BURROW_UPDATE_INTERVAL must be a positive number of seconds" >&2
exit 2
;;
esac
if [ "$interval" -eq 0 ]; then
echo "BURROW_UPDATE_INTERVAL must be greater than zero" >&2
exit 2
fi
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
while :; do
# A failed fetch or rejected update should not stop future update attempts.
"$script_dir/update.sh" || echo "burrow update failed; will retry in $interval seconds" >&2
sleep "$interval"
done
+34 -3
View File
@@ -1,15 +1,35 @@
#!/usr/bin/env bash
# brings the server to origin's main and restarts it when the change needs it.
# run as root by burrow-update.timer; git itself runs as the server's user.
# Brings the server to origin's main and restarts it when the change needs it.
# Run as root by either burrow-update.timer or the OpenRC updater service; git
# itself runs as the server's user.
set -euo pipefail
dir=${BURROW_DIR:-/home/aj/ajc-private-server}
user=${BURROW_USER:-aj}
service=${BURROW_SERVICE:-burrow}
branch=${BURROW_BRANCH:-main}
init=${BURROW_INIT:-}
git() { runuser -u "$user" -- git -C "$dir" "$@"; }
restart_service() {
case "$init" in
systemd) systemctl restart "$service" ;;
openrc) rc-service "$service" restart ;;
"")
if [ -d /run/openrc ] || [ -n "${RC_SVCNAME:-}" ]; then
rc-service "$service" restart
else
systemctl restart "$service"
fi
;;
*)
echo "unknown BURROW_INIT value: $init (expected systemd or openrc)" >&2
return 2
;;
esac
}
git fetch --quiet origin "$branch"
old=$(git rev-parse HEAD)
new=$(git rev-parse "origin/$branch")
@@ -27,13 +47,24 @@ for file in $(git diff --name-only "$old" "$new" -- '*.js'); do
fi
done
# the npm packages (only discord.js, for the optional Discord bot): installed
# again when the lockfile changed, or when they never were. a failed install
# leaves the bot off; the game itself needs none of them.
if [ -f "$dir/package-lock.json" ] && { ! git diff --quiet "$old" "$new" -- package-lock.json || [ ! -d "$dir/node_modules" ]; }; then
if command -v npm >/dev/null && runuser -u "$user" -- npm --prefix "$dir" ci --omit=dev --no-audit --no-fund; then
echo "npm packages installed"
else
echo "npm packages could not be installed; the Discord bot stays off" >&2
fi
fi
# public/ is read from disk on every request; the rest is loaded once, at start.
# the list is taken whole first: piped straight into grep -q, a long one (a
# push of many files) had git cut off mid-write ("Broken pipe"), which
# pipefail read as nothing to restart for.
changed=$(git diff --name-only "$old" "$new")
if grep -qvE '^(public/|client-updates/|test/|tools/|deploy/|[^/]+\.md$|\.gitignore$)' <<<"$changed"; then
systemctl restart "$service"
restart_service
echo "updated $old -> $new, restarted $service"
else
echo "updated $old -> $new, no restart needed"
+66 -12
View File
@@ -46,7 +46,7 @@ const SCHEMA = `
// fields stored in their own columns rather than in `state`.
const COLUMN_FIELDS = ["id", "username", "salt", "hash", "createdAt"];
// how the game treats the account this session; set again at every login.
const SESSION_FIELDS = ["accountType", "isGuide", "isModerator", "membershipDays", "startInDen", "startRoom"];
const SESSION_FIELDS = ["accountType", "isGuide", "guideRefused", "isModerator", "membershipDays", "startInDen", "startRoom"];
const DEFAULT_MEMBERSHIP_DAYS = 9999;
const MAX_ACCOUNT_TYPE = 5;
const MEMBERSHIP_TYPES = [0, 2]; // non-member, member
@@ -61,6 +61,7 @@ const USER_VAR_SETTINGS = 363; // the settings menu's switches, a bit each (gui.
// the chat filter an account starts with: level 1 slurs and threats, mode 1
// the whole message left out (see account.filter below).
const DEFAULT_FILTER = {level: 1, mode: 1, words: ""};
const chatStyles = require("./chatstyles.js");
const MAX_PASSWORD_LENGTH = 100;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// parts of the game a player can switch off for their own account, each
@@ -78,7 +79,10 @@ const LOGIN_DAYS_KEPT = 90; // and none older than this: they hold addresses
let db = null;
const byKey = new Map(); // lowercased username -> account
const byId = new Map();
const savedState = new Map(); // account id -> state JSON as last written
// account id -> digest of the state JSON as last written: enough to tell a
// change, without a second copy of every account's state (~13 KB each).
const savedState = new Map();
const stateDigest = json => crypto.createHash("sha256").update(json).digest("base64");
// A name somebody gave up (a rename, a deleted account) is nobody's to take
// for a while: whoever had it is still known by it to the players they met.
const NAME_HELD_DAYS = 30;
@@ -247,6 +251,9 @@ const normalize = account => {
// the name tag: colour in the low byte, badge above it, bit 16 hides the
// adventure level shape (avatar.NameBar.setColorAndBadge).
account.nameBarData = Number.isInteger(account.nameBarData) ? account.nameBarData : 0;
// Personal chat appearance. The renderer receives it with each spoken line
// (lib/world.js), never as a client-controlled packet field.
account.chatStyle = chatStyles.normalize(account.chatStyle);
account.disguise = Number.isInteger(account.disguise) ? account.disguise : 0; // NPC id, see lib/disguises.js
// shown on the player's card: lib/badges.js.
account.discord = typeof account.discord === "string" ? account.discord : ""; // their Discord username, as Discord gave it (lib/discord.js)
@@ -299,13 +306,17 @@ const MAX_START_ROOM = 80;
function setLoginChoices(account, choices) {
const asked = config.loginChoices && choices && typeof choices === "object" ? choices : {};
const whole = (value, max) => Number.isInteger(value) && value >= 0 && value <= max;
// member or not, and guide or not, are the player's own choice on any
// server; the rest only with config.loginChoices: another account type
// shows to everyone.
// member or not is the player's own choice on any server; the rest only
// with config.loginChoices: another account type shows to everyone.
const own = choices && typeof choices === "object" ? choices : {};
const type = MEMBERSHIP_TYPES.includes(own.accountType) ? own.accountType : asked.accountType;
account.accountType = whole(type, MAX_ACCOUNT_TYPE) ? type : config.defaultAccountType;
account.isGuide = own.isGuide === true;
// guide (the name tag, the chat bubble, what others see) only for an
// account the admin made one (lib/panel.js); asked for without that, it is
// refused. a guide's own client may leave it off; the official launcher
// asks nothing, and a guide is one.
account.isGuide = account.guideGiven === true && (choices && typeof choices === "object" ? own.isGuide === true : true);
account.guideRefused = own.isGuide === true && account.guideGiven !== true;
account.isModerator = asked.isModerator === true;
account.membershipDays = whole(asked.membershipDays, MAX_MEMBERSHIP_DAYS) ? asked.membershipDays : DEFAULT_MEMBERSHIP_DAYS;
// where to start is the player's to say on any server: their own den in
@@ -331,7 +342,7 @@ const insert = (username, salt, hash, createdAt, state) => {
const result = db.prepare("INSERT INTO accounts (username, username_key, password_salt, password_hash, created_at, state) VALUES (?, ?, ?, ?, ?, ?)")
.run(username, username.toLowerCase(), salt, hash, createdAt, json);
account.id = Number(result.lastInsertRowid);
savedState.set(account.id, json);
savedState.set(account.id, stateDigest(json));
remember(account);
touch(account);
return account;
@@ -381,7 +392,7 @@ const load = () => {
createdAt: row.created_at,
...JSON.parse(row.state),
});
savedState.set(account.id, row.state);
savedState.set(account.id, stateDigest(row.state));
remember(account);
}
importLegacyFile();
@@ -475,7 +486,7 @@ const release = account => {
const changedState = (account, changed) => {
const json = stateJson(account);
if (savedState.get(account.id) !== json) {
if (savedState.get(account.id) !== stateDigest(json)) {
changed.push([account.id, json]);
return true;
}
@@ -583,7 +594,7 @@ const flush = ({some = false} = {}) => {
throw err;
}
for (const [id, json] of changed) {
savedState.set(id, json);
savedState.set(id, stateDigest(json));
}
};
@@ -730,6 +741,34 @@ const register = (username, password, avatar = {}) => {
return {account};
};
// Public sign-ups can arrive in a burst. scryptSync is fine for the local,
// legacy Create Account socket but it would freeze all players while each web
// registration is derived. Keep the same validation and database insert on
// the main thread, but derive its password on libuv's worker pool. Check the
// username again after awaiting: another request may have claimed it first.
const registerAsync = async (username, password, avatar = {}) => {
username = typeof username === "string" ? username.trim() : username;
let error = usernameProblem(username) || passwordProblem(password, username) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal");
if (error) {
return {error};
}
const salt = crypto.randomBytes(16).toString("hex");
const hash = await hashPasswordAsync(password, salt);
error = usernameProblem(username) || passwordProblem(password, username) || (defpacks.avatarDef(avatar.type) ? null : "choose_animal");
if (error) {
return {error};
}
const type = Number(avatar.type);
const account = insert(username, salt, hash, now(), {
avatars: [newAvatar({perUserAvId: 1, avInvId: 1}, avatar.name || username, type, -1)],
activeAvatar: 1,
badges: byId.size < EARLY_MEMBERS ? [EARLY_BADGE] : [],
recoveryEmail: typeof avatar.email === "string" && EMAIL_PATTERN.test(avatar.email.trim()) ? avatar.email.trim().toLowerCase() : "",
});
console.log(`[accounts] registered "${logText(username)}" (id ${logText(account.id)})`);
return {account};
};
const authenticate = (username, password) => {
// "name" and "name " are the same account.
const account = typeof username === "string" ? touch(byKey.get(username.trim().toLowerCase())) : null;
@@ -803,7 +842,10 @@ const storableUsernameProblem = username => {
};
// gives the account a new username, and carries it into everyone's buddy and
// block lists. returns "invalid_username" or "username_taken", else null.
// block lists. The staff dashboard stores a few human-readable names beside
// account ids; keep those labels current too, so a rename does not split a
// player's history across two names. Returns "invalid_username" or
// "username_taken", else null.
// the player must not be online: the game knows them by the old name.
// with `anyName` (the admin panel) the sign-up rules about length and
// characters do not apply; see storableUsernameProblem.
@@ -825,6 +867,18 @@ const rename = (account, username, anyName = false) => {
}
db.prepare("UPDATE accounts SET username = ?, username_key = ? WHERE id = ?").run(username, newKey, account.id);
console.log(`[accounts] renamed "${logText(account.username)}" to "${logText(username)}" (id ${logText(account.id)})`);
for (const [table, column] of [
["reports", "reporter"], ["reports", "target"], ["feedback", "username"],
["chat_log", "username"], ["chat_log", "to_name"], ["appeals", "username"],
["ban_log", "username"], ["mod_log", "by"], ["mod_log", "target"],
]) {
// A few lean unit tests load the account store without every dashboard
// module. The tables are present in the actual server, but keep rename
// usable in that smaller setup too.
if (db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(table)) {
db.prepare(`UPDATE ${table} SET ${column} = ? WHERE ${column} = ? COLLATE NOCASE`).run(username, account.username);
}
}
byKey.delete(oldKey);
account.username = username;
byKey.set(newKey, account);
@@ -932,4 +986,4 @@ const all = () => [...byId.values()];
const database = () => db;
module.exports = {FEATURES, featureOn, recordLogin, revokeTokens, load, save, flush, hold, release, startBackups, database, setLoginChoices, setPassword, rename, remove, setting, setSetting, hashPassword, register, usernameProblem, authenticate, authenticateAsync, issueToken, byToken, byName, nameOf, byId: accountById, newAvatar, freeAvatarSlot, all};
module.exports = {FEATURES, featureOn, recordLogin, revokeTokens, load, save, flush, hold, release, startBackups, database, setLoginChoices, setPassword, rename, remove, setting, setSetting, hashPassword, register, registerAsync, usernameProblem, authenticate, authenticateAsync, issueToken, byToken, byName, nameOf, byId: accountById, newAvatar, freeAvatarSlot, all};
+140 -4
View File
@@ -2,6 +2,8 @@
const accounts = require("./accounts.js");
const bans = require("./bans.js");
const cdn = require("./cdn.js");
const colours = require("./colours.js");
const captcha = require("./captcha.js");
const defpacks = require("./defpacks.js");
const devices = require("./devices.js");
@@ -10,6 +12,7 @@ const roles = require("./roles.js");
const dens = require("./dens.js");
const itemControl = require("./itemcontrol.js");
const customItems = require("./customitems.js");
const itemArt = require("./itemart.js");
const limits = require("./limits.js");
const world = require("./world.js");
const {addClothing, sendClothingAdded, isUint} = require("./player.js");
@@ -71,6 +74,24 @@ const search = (params, favourites = null, seesLocked = false, askerId = null) =
};
};
// the variants each den item's art has (tools/den-variants.sh):
// {versions: [...], colours?: [[hex, ...] per variant]}, or null.
let denVariants = null;
const variantsOf = id => {
if (!denVariants) {
try {
denVariants = require("./den-variants.json");
}
catch (err) {
denVariants = {};
}
}
return denVariants[Number(id)] || null;
};
const SPECIAL_MANNEQUIN = "4";
const MAX_TINT_SLOT = 0x7FFFFF; // what fits above a den item's variant (8 bits) in its version, kept positive
const MAX_PRESETS = 40;
// one to four "#RRGGBB", spaces or commas between. the # is wanted: six
// digits alone are a colour id
const HEX_COLOURS = /^#[0-9a-f]{6}([\s,]+#[0-9a-f]{6}){0,3}$/i;
@@ -89,6 +110,7 @@ const give = (body, seesLocked = false) => {
return {status: 403, body: {error: "That item is locked out of the item finder."}};
}
const session = world.findOnline(account.username);
const given = {}; // what the item was given as: its colour, or its version
if (body.kind === "clothing") {
const def = defpacks.itemDef(body.id);
const colors = def ? String(def.colors).split(",") : [];
@@ -119,6 +141,9 @@ const give = (body, seesLocked = false) => {
if (custom && !isUint(custom)) {
return {status: 400, body: {error: "Colour: an id, or #RRGGBB"}};
}
if (custom && !colours.known(Number(custom))) {
return {status: 400, body: {error: "No such custom colour"}};
}
const color = custom || colors[Number(body.colorIndex) || 0];
if (!def || !defpacks.clothingIds().includes(Number(def.id)) || color === undefined) {
return {status: 400, body: {error: "No such clothing item or colour"}};
@@ -127,6 +152,7 @@ const give = (body, seesLocked = false) => {
if (!item) {
return {status: 409, body: {error: "That inventory is full"}};
}
given.color = Number(color);
accounts.save(account);
if (session) {
sendClothingAdded(session, item);
@@ -136,12 +162,48 @@ const give = (body, seesLocked = false) => {
if (!defpacks.denItemIds().includes(Number(body.id))) {
return {status: 400, body: {error: "No such den item"}};
}
if (!dens.giveDenItem(account, body.id)) {
// `version`: one of the variants its art has (above), 0 by default.
// `tint` ("#RRGGBB") and `tintStrength` (1-100, 100 by default): the
// whole item in shades of that colour, which the patched client draws
// (DenItemHelper.applyTint). the tint is a custom colour entry
// (lib/colours.js, [rgb, strength, 0, 0]), and 1 + its number goes in
// the version above the variant's 8 bits, so it goes wherever the item
// goes: dens, trades, gifts.
const variants = variantsOf(body.id);
const variant = body.version === undefined || body.version === "" ? 0 : Number(body.version);
if (!Number.isInteger(variant) || (variant !== 0 && !(variants && variants.versions.includes(variant)))) {
return {status: 400, body: {error: "That item has no such variant"}};
}
let version = variant;
const tint = typeof body.tint === "string" ? body.tint.trim() : "";
if (tint) {
const strength = body.tintStrength === undefined || body.tintStrength === "" ? 100 : Number(body.tintStrength);
if (!/^#[0-9a-f]{6}$/i.test(tint) || !Number.isInteger(strength) || strength < 1 || strength > 100) {
return {status: 400, body: {error: "Tint: #RRGGBB, strength 1 to 100"}};
}
if ((defpacks.denItemDef(body.id) || {}).specialType === SPECIAL_MANNEQUIN) {
return {status: 400, body: {error: "Mannequins cannot be tinted"}};
}
const entry = world.makeColour(account, [parseInt(tint.slice(1), 16), strength, 0, 0], session);
if (!entry) {
return {status: 400, body: {error: "Bad colour"}};
}
if (entry.full) {
return {status: 429, body: {error: "No more new colours today. Colours made before can still be used."}};
}
const slot = entry.id - colours.CUSTOM_BASE + 1;
if (slot > MAX_TINT_SLOT) {
return {status: 503, body: {error: "No more tints can be made"}};
}
version |= slot << 8;
}
if (!dens.giveDenItem(account, body.id, version)) {
return {status: 409, body: {error: "That inventory is full"}};
}
if (session) {
dens.sendDenItems(session);
}
given.version = version;
}
else {
return {status: 400, body: {error: "Unknown item kind"}};
@@ -152,7 +214,81 @@ const give = (body, seesLocked = false) => {
const kept = Object.entries(account.finderGiven).sort((one, other) => other[1].at - one[1].at).slice(0, MAX_FAVOURITES);
account.finderGiven = Object.fromEntries(kept);
accounts.save(account);
return {status: 200, body: {ok: true, online: Boolean(session)}};
return {status: 200, body: {ok: true, online: Boolean(session), ...given}};
};
// the game's 256 colours (the CDN's paletteData; PaletteHelper.setGamePalette),
// as "rrggbb", once read. null while the file cannot be had.
let palette = null;
const loadPalette = async () => {
if (!palette) {
const file = await cdn.get(cdn.hashedPath("paletteData"));
if (file && file.length >= 4 && file.readInt32BE(0) === 1024) {
palette = Array.from({length: 256}, (unused, index) => (file.readUInt32BE(4 + index * 4) & 0xFFFFFF).toString(16).padStart(6, "0"));
}
}
return palette;
};
// a packed colour's four, as "rrggbb" (a custom colour's own, or the
// palette's at each of its four bytes, colour 1 the top one).
const coloursOf = id => {
const custom = colours.rgbsOf(id);
if (custom) {
return custom.map(rgb => rgb.toString(16).padStart(6, "0"));
}
return palette ? [24, 16, 8, 0].map(shift => palette[(id >>> shift) & 0xFF]) : null;
};
// the web item giver (/account/items, lib/manage.js): a search as the
// in-game one, with what each item may be given as: a clothing item's own
// colours, a den item's variants and whether it takes a tint.
const searchFor = async (account, params) => {
await loadPalette();
const found = search(params, account.finderGiven, roles.can(account, "items.create"), account.id);
return {...found, results: found.results.map(result => {
// a custom item's own picture, which the game shows in place of its art
const custom = customItems.get(result.kind, result.id);
const entry = {...result, art: custom ? itemArt.urlOf(custom, "/account/api/itemart") : null};
if (entry.kind === "clothing") {
const def = defpacks.itemDef(entry.id);
const ids = def ? String(def.colors).split(",").map(Number).filter(Number.isInteger).slice(0, MAX_PRESETS) : [];
return {...entry, presets: ids.map(id => ({id: id >>> 0, colours: coloursOf(id >>> 0)}))};
}
const variants = variantsOf(entry.id);
return {...entry, variants: variants ? variants.versions : [], variantColours: variants && variants.colours ? variants.colours : null,
tintable: (defpacks.denItemDef(entry.id) || {}).specialType !== SPECIAL_MANNEQUIN};
})};
};
// ... and its colour boxes, which turn colours to the game's numbers and
// back as they are typed: with `id`, a custom colour's four ("rrggbb"); with
// `rgbs` (four "rrggbb", commas between), the custom colour already made of
// those four, or null (Give would make it); with neither, the game's 256.
const colourLookup = async params => {
if (params.has("id")) {
const text = params.get("id");
const id = /^-?\d{1,10}$/.test(text) && Number(text) >= -0x80000000 && Number(text) <= 0xFFFFFFFF ? Number(text) >>> 0 : null;
const rgbs = id === null ? null : colours.rgbsOf(id);
return rgbs ? {status: 200, body: {id, colours: rgbs.map(rgb => rgb.toString(16).padStart(6, "0"))}}
: {status: 404, body: {error: "No such custom colour"}};
}
if (params.has("rgbs")) {
const rgbs = params.get("rgbs").split(",").map(hex => (/^[0-9a-f]{6}$/i.test(hex) ? parseInt(hex, 16) : NaN));
const entry = colours.allocate(rgbs, false);
if (!entry) {
return {status: 400, body: {error: "Four colours: rrggbb,rrggbb,rrggbb,rrggbb"}};
}
return {status: 200, body: {id: entry.full ? null : entry.id}};
}
return {status: 200, body: {palette: await loadPalette()}};
};
// ... and its Give, for the account signed in on that page.
const giveAs = (account, body) => {
if (!givesPerMinute.allow(account.id)) {
return {status: 429, body: {error: "Too many at once. Try again in a minute."}};
}
return give({...body, username: account.username}, roles.can(account, "items.create"));
};
const FORBIDDEN = {status: 403, body: {error: "forbidden"}};
@@ -282,7 +418,7 @@ const handle = async (route, params, body, from) => {
if (!STARTER_ANIMALS.includes(avatarType)) {
return {status: 400, body: {error: "choose_animal"}};
}
const result = accounts.register(username, password, {type: avatarType, email});
const result = await accounts.registerAsync(username, password, {type: avatarType, email});
if (result.account) {
result.account.agreed = {version: config.termsVersion, at: Math.floor(Date.now() / 1000)};
accounts.save(result.account);
@@ -296,4 +432,4 @@ const handle = async (route, params, body, from) => {
}
};
module.exports = {handle, search};
module.exports = {handle, search, searchFor, colourLookup, giveAs};
+4 -1
View File
@@ -537,9 +537,12 @@ module.exports = {
for (const number of [2, 3, 4]) {
set(q, `cork_${number}${pick("abc")}`, 1, 1, 0);
}
for (const number of [1, 2, 3, 4]) {
// the last key's other places lie off where an animal can walk:
// players had to jump to it. it lies where the recording had it.
for (const number of [1, 2, 3]) {
set(q, `bunny_key_${number}${pick("abcdef")}`, 1, 1, 0);
}
set(q, "bunny_key_4c", 1, 1, 0);
});
},
+105 -32
View File
@@ -177,40 +177,89 @@ class Amf3Reader {
// writer for what the reader above produces from a defPack: plain objects,
// arrays (with or without string keys), strings, numbers, booleans and null.
// nothing is written as a reference except repeated strings.
// written into one buffer that grows: a pack is megabytes of small values,
// and a Buffer for each of them took seconds for the item pack.
class Amf3Writer {
constructor() {
this.parts = [];
this.buf = Buffer.allocUnsafe(1 << 16);
this.pos = 0;
this.strings = new Map();
}
room(bytes) {
if (this.pos + bytes > this.buf.length) {
let size = this.buf.length * 2;
while (size < this.pos + bytes) {
size *= 2;
}
const bigger = Buffer.allocUnsafe(size);
this.buf.copy(bigger, 0, 0, this.pos);
this.buf = bigger;
}
}
byte(value) {
this.room(1);
this.buf[this.pos++] = value;
}
u29(value) {
this.room(4);
const {buf} = this;
if (value < 0x80) {
this.parts.push(Buffer.from([value]));
buf[this.pos++] = value;
}
else if (value < 0x4000) {
this.parts.push(Buffer.from([(value >> 7) | 0x80, value & 0x7f]));
buf[this.pos++] = (value >> 7) | 0x80;
buf[this.pos++] = value & 0x7f;
}
else if (value < 0x200000) {
this.parts.push(Buffer.from([(value >> 14) | 0x80, ((value >> 7) & 0x7f) | 0x80, value & 0x7f]));
buf[this.pos++] = (value >> 14) | 0x80;
buf[this.pos++] = ((value >> 7) & 0x7f) | 0x80;
buf[this.pos++] = value & 0x7f;
}
else {
this.parts.push(Buffer.from([(value >> 22) | 0x80, ((value >> 15) & 0x7f) | 0x80, ((value >> 8) & 0x7f) | 0x80, value & 0xff]));
buf[this.pos++] = (value >> 22) | 0x80;
buf[this.pos++] = ((value >> 15) & 0x7f) | 0x80;
buf[this.pos++] = ((value >> 8) & 0x7f) | 0x80;
buf[this.pos++] = value & 0xff;
}
}
string(text) {
if (text === "") {
this.u29(1);
return;
}
else if (this.strings.has(text)) {
this.u29(this.strings.get(text) << 1);
const known = this.strings.get(text);
if (known !== undefined) {
this.u29(known << 1);
return;
}
else {
this.strings.set(text, this.strings.size);
const bytes = Buffer.from(text, "utf8");
this.u29((bytes.length << 1) | 1);
this.parts.push(bytes);
this.strings.set(text, this.strings.size);
// nearly every string of a pack is short and ASCII: its bytes are its
// characters, copied here rather than through Buffer's utf8 writer.
if (text.length < 64) {
let ascii = true;
for (let i = 0; i < text.length; i++) {
if (text.charCodeAt(i) > 0x7f) {
ascii = false;
break;
}
}
if (ascii) {
this.u29((text.length << 1) | 1);
this.room(text.length);
for (let i = 0; i < text.length; i++) {
this.buf[this.pos++] = text.charCodeAt(i);
}
return;
}
}
const length = Buffer.byteLength(text, "utf8");
this.u29((length << 1) | 1);
this.room(length);
this.pos += this.buf.write(text, this.pos, "utf8");
}
pairs(entries) {
@@ -222,45 +271,69 @@ class Amf3Writer {
}
value(value) {
if (value === undefined) {
this.parts.push(Buffer.from([0x00]));
// most values of a pack are strings: asked first
if (typeof value === "string") {
this.byte(0x06);
this.string(value);
}
else if (value === undefined) {
this.byte(0x00);
}
else if (value === null) {
this.parts.push(Buffer.from([0x01]));
this.byte(0x01);
}
else if (typeof value === "boolean") {
this.parts.push(Buffer.from([value ? 0x03 : 0x02]));
this.byte(value ? 0x03 : 0x02);
}
else if (typeof value === "number") {
if (Number.isInteger(value) && value >= -0x10000000 && value < 0x10000000) {
this.parts.push(Buffer.from([0x04]));
this.byte(0x04);
this.u29(value & 0x1fffffff);
}
else {
const bytes = Buffer.alloc(9);
bytes[0] = 0x05;
bytes.writeDoubleBE(value, 1);
this.parts.push(bytes);
this.byte(0x05);
this.room(8);
this.pos = this.buf.writeDoubleBE(value, this.pos);
}
}
else if (typeof value === "string") {
this.parts.push(Buffer.from([0x06]));
this.string(value);
}
else if (Array.isArray(value)) {
this.parts.push(Buffer.from([0x09]));
this.byte(0x09);
this.u29((value.length << 1) | 1);
// string keys set on the array beside its numbered elements.
this.pairs(Object.entries(value).filter(([key]) => !/^\d+$/.test(key)));
// string keys set on the array beside its numbered elements (an array
// with as many keys as elements has none).
const keys = Object.keys(value);
this.pairs(keys.length === value.length ? [] : keys.filter(key => !/^\d+$/.test(key)).map(key => [key, value[key]]));
for (const element of value) {
this.value(element);
}
}
else if (typeof value === "object" && !Buffer.isBuffer(value)) {
else if (value instanceof Date) {
// A date (a room file's timestamps): its milliseconds, written in place.
this.byte(0x08);
this.u29(1);
this.room(8);
this.pos = this.buf.writeDoubleBE(value.getTime(), this.pos);
}
else if (Buffer.isBuffer(value)) {
// A ByteArray (a room file's pictures and shapes).
this.byte(0x0c);
this.u29((value.length << 1) | 1);
this.room(value.length);
this.pos += value.copy(this.buf, this.pos);
}
else if (typeof value === "object") {
// A dynamic object of no class, with its traits written in place.
this.parts.push(Buffer.from([0x0a, 0x0b]));
this.byte(0x0a);
this.byte(0x0b);
this.string("");
// its own keys in Object.keys order, without an array of entries for each object
for (const key in value) {
if (Object.hasOwn(value, key)) {
this.string(key);
this.value(value[key]);
}
}
this.string("");
this.pairs(Object.entries(value));
}
else {
throw new Error("Cannot write this value as AMF3");
@@ -273,6 +346,6 @@ module.exports = {
encode: value => {
const writer = new Amf3Writer();
writer.value(value);
return Buffer.concat(writer.parts);
return writer.buf.subarray(0, writer.pos);
},
};
+6
View File
@@ -97,6 +97,12 @@ module.exports = ({others, findOnline, findBySfsId, refreshForOthers, petFields}
const messageRoom = session.room ? session.room.id : -1;
const common = [1, session.id, avatar.perUserAvId, avatar.avInvId, avatar.customAvId, avatar.type, ...avatar.colors, avatar.name];
session.sendXt("as", messageRoom, ...common, avatar.petInvId, avatar.questLevel || 0);
// Nothing more goes to the switching player here. The client swaps the
// animals during the transform animation (AvatarSwitch "hideAvatar"),
// copying the in-world avatar into the switcher slot first and asking
// for "ad" itself when it needs to. An unasked "ad"/"il" lands on the
// in-world avatar before that copy, so the old animal vanished from the
// switcher and the new one showed twice.
if (session.pos) {
for (const other of others(session)) {
other.sendXt("as", messageRoom, ...common, ...petFields(activePet(account)), avatar.questLevel || 0);
+3 -3
View File
@@ -33,9 +33,9 @@ const cdn = require("./cdn.js");
// there are no more than a hundred (lib/accounts.js); the admin may give
// it and take it away like any other.
// in the order they are listed and drawn. the Verified, Owner and Moderator
// name tags show their badge to everyone, not only to buddies: their def ids
// are in PUBLIC_BADGE_IDS of swf-src/AvatarWorldView.as.
// in the order they are listed and drawn. the Verified, Owner, Moderator and
// Developer name tags show their badge to everyone, not only to buddies:
// their def ids are in PUBLIC_BADGE_IDS of swf-src/AvatarWorldView.as.
const BADGES = [
// first, so its tick comes straight after the name, as on other sites.
{id: "verified", label: "Verified", tag: {def: 76, media: 20014, bit: 21}},
+13 -1
View File
@@ -26,10 +26,12 @@ const MAX_ANSWER_LENGTH = 2048;
const PASS_MS = 600000;
const PASS_USES = 5;
const MAX_PASSES = 10000;
const MAX_VERIFYING = config.maxConcurrentCaptchaChecks;
const on = Boolean(config.turnstile);
const passes = new Map(); // SHA-256 of a pass -> {id: account id, key: address key, expiry, uses}
const sha256 = text => crypto.createHash("sha256").update(String(text)).digest("hex");
let verifying = 0;
// for the pages: what each answer means
const MESSAGES = {
@@ -70,6 +72,13 @@ const verify = async (answer, from, action) => {
if (typeof answer !== "string" || !answer || answer.length > MAX_ANSWER_LENGTH) {
return "captcha_required";
}
// A burst of valid-looking tokens should not turn an upstream Turnstile
// slowdown into thousands of open fetches on this VPS. Refuse quickly;
// the browser can reset its widget and retry after the short outage.
if (verifying >= MAX_VERIFYING) {
return "captcha_unavailable";
}
verifying++;
const form = new URLSearchParams({secret: config.turnstile.secret, response: answer});
if (!limits.isLoopback(from.address)) {
form.set("remoteip", from.address);
@@ -83,6 +92,9 @@ const verify = async (answer, from, action) => {
console.log(`[captcha] cloudflare did not answer: ${logText(err.message)}`);
return "captcha_unavailable";
}
finally {
verifying--;
}
// an answer made for another form is no answer for this one. cloudflare's
// test keys give none.
if (!result || result.success !== true || (result.action && result.action !== action)) {
@@ -107,7 +119,7 @@ const check = async (body, from, action, account) => {
// a page's security policy: public/captcha.js always (the page calls it even
// when off), and the widget too when it is on.
const policy = csp => (on
? `${csp.replace("script-src ", `script-src 'self' ${ORIGIN} `)}; frame-src ${ORIGIN}`
? `${csp.replace("script-src ", `script-src 'self' ${ORIGIN} `).replace("connect-src ", `connect-src 'self' ${ORIGIN} `)}; frame-src ${ORIGIN}`
: csp.replace("script-src ", "script-src 'self' "));
// a page with public/captcha.js asked for under a name that changes with the
+79
View File
@@ -0,0 +1,79 @@
"use strict";
// The style travels with a chat line, rather than with an avatar-create
// packet, so a new choice takes effect immediately and is seen by everybody
// who sees that line. Keep it small and entirely server-generated: clients
// never get to choose the fields sent to other players.
const DEFAULT = Object.freeze({background: "ffffff", accent: "dfe8ff", text: "445559", border: "9aabb0", opacity: 75,
animation: "none", speed: 100, gradient: "linear", angle: 45, strength: 100, outline: 1,
stops: "ffffff:0;dfe8ff:100"});
const ANIMATIONS = new Set(["none", "pulse", "shimmer", "flow", "rainbow"]);
const GRADIENTS = new Set(["solid", "linear", "radial"]);
const COLOR = /^[0-9a-f]{6}$/i;
const color = (value, fallback) => typeof value === "string" && COLOR.test(value) ? value.toLowerCase() : fallback;
const number = (value, fallback, low, high) => Number.isInteger(value) && value >= low && value <= high ? value : fallback;
const direction = value => {
const angle = number(value, DEFAULT.angle, 0, 315);
return angle % 45 === 0 ? angle : DEFAULT.angle;
};
const stops = (value, background, accent) => {
if (typeof value === "string") {
const parsed = value.split(";").map(stop => {
const match = /^([0-9a-f]{6}):(100|[1-9]?\d)$/i.exec(stop);
return match ? {color: match[1].toLowerCase(), position: Number(match[2])} : null;
});
if (parsed.length >= 2 && parsed.length <= 5 && parsed.every(Boolean)
&& parsed[0].position === 0 && parsed.at(-1).position === 100
&& parsed.every((stop, index) => index === 0 || stop.position > parsed[index - 1].position)) {
return parsed.map(stop => `${stop.color}:${stop.position}`).join(";");
}
}
return `${background}:0;${accent}:100`;
};
const normalize = value => {
const source = value && typeof value === "object" && !Array.isArray(value) ? value : {};
let background = color(source.background, DEFAULT.background);
let accent = color(source.accent, DEFAULT.accent);
const gradientStops = stops(source.stops, background, accent);
const stopParts = gradientStops.split(";");
background = stopParts[0].slice(0, 6);
accent = stopParts.at(-1).slice(0, 6);
return {
background,
accent,
text: color(source.text, DEFAULT.text),
border: color(source.border, DEFAULT.border),
opacity: number(source.opacity, DEFAULT.opacity, 25, 100),
animation: ANIMATIONS.has(source.animation) ? source.animation : DEFAULT.animation,
speed: number(source.speed, DEFAULT.speed, 40, 300),
gradient: GRADIENTS.has(source.gradient) ? source.gradient : DEFAULT.gradient,
angle: direction(source.angle),
strength: number(source.strength, DEFAULT.strength, 0, 100),
outline: number(source.outline, DEFAULT.outline, 0, 4),
stops: gradientStops,
};
};
const same = (one, two) => Object.keys(DEFAULT).every(key => one[key] === two[key]);
// `normalize` is intentionally forgiving when old account data is loaded.
// Incoming editor requests are not: every field must already be canonical.
const valid = value => Boolean(value) && typeof value === "object" && !Array.isArray(value)
&& Object.keys(DEFAULT).every(key => value[key] === normalize(value)[key]);
const fields = value => {
const style = normalize(value);
return [style.background, style.accent, style.text, style.border, style.opacity, style.animation, style.speed,
style.gradient, style.angle, style.strength, style.outline, style.stops];
};
// Twelve comma-separated, URL-safe fields; empty means the original game bubble.
const packet = value => {
const style = normalize(value);
return same(style, DEFAULT) ? "" : fields(style).join(",");
};
module.exports = {DEFAULT, normalize, valid, fields, packet};
+134
View File
@@ -0,0 +1,134 @@
"use strict";
const accounts = require("./accounts.js");
const defpacks = require("./defpacks.js");
// codes players type into the game's "Redeem Code" window
// (gameRedemption.CodeRedemptionPopup, "grc" in lib/world.js), made in the
// admin panel. a code gives one thing: a clothing item (in a colour), a den
// item, gems or diamonds, as a gift from Burrow HQ (lib/ecards.js
// sendFromHq). each account may use a code once; a code may also have an
// end to how many times it is used in all, and is then spent.
const SCHEMA = `
CREATE TABLE IF NOT EXISTS redeem_codes (
code TEXT PRIMARY KEY,
kind TEXT NOT NULL,
item INTEGER NOT NULL DEFAULT 0,
amount INTEGER NOT NULL DEFAULT 0,
color INTEGER,
uses INTEGER NOT NULL DEFAULT 0,
used INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS redeem_uses (
code TEXT NOT NULL,
account_id INTEGER NOT NULL,
at INTEGER NOT NULL,
PRIMARY KEY (code, account_id)
);
`;
const KINDS = ["clothing", "den", "gems", "diamonds"];
const CODE = /^[A-Z0-9-]{3,32}$/; // what the game's box lets be typed (and in capitals)
const MAX_AMOUNT = 10000000;
const MAX_USES = 1000000;
let made = false;
const db = () => {
const database = accounts.database();
if (!made) {
database.exec(SCHEMA);
made = true;
}
return database;
};
const now = () => Math.floor(Date.now() / 1000);
const normal = code => String(code || "").trim().toUpperCase();
const row = entry => ({code: entry.code, kind: entry.kind, item: entry.item, amount: entry.amount, color: entry.color,
uses: entry.uses, used: entry.used, createdAt: entry.created_at});
const list = () => db().prepare("SELECT * FROM redeem_codes ORDER BY created_at DESC").all().map(row);
// {code, kind, item, amount, color, uses}: returns {ok} or {error}.
const create = fields => {
const code = normal(fields.code);
const kind = String(fields.kind || "");
const uses = Number(fields.uses) || 0;
if (!CODE.test(code)) {
return {error: "A code is 3 to 32 letters, digits and dashes."};
}
if (!KINDS.includes(kind)) {
return {error: "A code gives clothing, a den item, gems or diamonds."};
}
if (!Number.isInteger(uses) || uses < 0 || uses > MAX_USES) {
return {error: "Uses: 0 for any number, or how many in all."};
}
let item = 0;
let amount = 0;
let color = null;
if (kind === "clothing") {
item = Number(fields.item);
const def = defpacks.itemDef(item);
if (!def || !defpacks.clothingIds().includes(item)) {
return {error: "No clothing item with that id."};
}
const own = String(def.colors).split(",").map(Number);
const chosen = fields.color === undefined || String(fields.color).trim() === "" ? own[0] : Number(fields.color);
if (!Number.isInteger(chosen) || chosen < -0x80000000 || chosen > 0xFFFFFFFF) {
return {error: "A colour as the game writes it (a whole number), or none for the item's own."};
}
color = chosen >>> 0;
}
else if (kind === "den") {
item = Number(fields.item);
if (!defpacks.denItemIds().includes(item)) {
return {error: "No den item with that id."};
}
}
else {
amount = Number(fields.amount);
if (!Number.isInteger(amount) || amount < 1 || amount > MAX_AMOUNT) {
return {error: "An amount from 1 to 10,000,000."};
}
}
if (db().prepare("SELECT 1 FROM redeem_codes WHERE code = ?").get(code)) {
return {error: "That code is taken."};
}
db().prepare("INSERT INTO redeem_codes (code, kind, item, amount, color, uses, used, created_at) VALUES (?, ?, ?, ?, ?, ?, 0, ?)")
.run(code, kind, item, amount, color, uses, now());
return {ok: `${code} made.`};
};
const remove = code => db().prepare("DELETE FROM redeem_codes WHERE code = ?").run(normal(code)).changes > 0;
// a code typed in the game, for `account`: {gift} for lib/ecards.js
// sendFromHq, or {error: "unknown" | "used" | "spent"}. the use is noted.
const redeem = (account, typed) => {
const code = normal(typed);
const entry = CODE.test(code) ? db().prepare("SELECT * FROM redeem_codes WHERE code = ?").get(code) : null;
if (!entry) {
return {error: "unknown"};
}
if (db().prepare("SELECT 1 FROM redeem_uses WHERE code = ? AND account_id = ?").get(code, account.id)) {
return {error: "used"};
}
if (entry.uses > 0 && entry.used >= entry.uses) {
return {error: "spent"};
}
db().prepare("INSERT INTO redeem_uses (code, account_id, at) VALUES (?, ?, ?)").run(code, account.id, now());
db().prepare("UPDATE redeem_codes SET used = used + 1 WHERE code = ?").run(code);
const gift = entry.kind === "clothing" ? {kind: "clothing", id: entry.item, color: entry.color}
: entry.kind === "den" ? {kind: "den", id: entry.item} : {kind: entry.kind, amount: entry.amount};
return {gift, code};
};
// a use taken back, when the gift could not be sent after all
const unredeem = (account, code) => {
if (db().prepare("DELETE FROM redeem_uses WHERE code = ? AND account_id = ?").run(code, account.id).changes > 0) {
db().prepare("UPDATE redeem_codes SET used = MAX(used - 1, 0) WHERE code = ?").run(code);
}
};
module.exports = {list, create, remove, redeem, unredeem, KINDS};
+4 -1
View File
@@ -71,4 +71,7 @@ const chunks = (size = 200) => {
// the custom range), or an entry of the table?
const known = id => id < CUSTOM_BASE || id > MAX_ID || entries.has(id);
module.exports = {load, allocate, chunks, known, count: () => entries.size};
// the four RGB values of an entry, or null.
const rgbsOf = id => entries.get(id) || null;
module.exports = {CUSTOM_BASE, load, allocate, chunks, known, rgbsOf, count: () => entries.size};
+100 -11
View File
@@ -3,14 +3,15 @@
const {logText} = require("./logtext.js");
const accounts = require("./accounts.js");
const defpacks = require("./defpacks.js");
const limits = require("./limits.js");
// items the staff make while the server runs, with no restart of the server
// or of anybody's game. each is an existing item's art (the clothing piece
// or den item it is made from) under an id, name, price and colours of its
// own. the server's tables and the packs new games fetch have it at once
// (defpacks.setCustomItem); games already playing are sent its def row
// ("xdi", which the patched client adds to its tables), and so is every game
// at login, in case it was started before the item was made.
// ("xdi", which the patched client adds to its tables), and so is a game at
// login if its packs may be older than the item (sendAll).
//
// an item can be taken out of the shop, renamed and repriced, or deleted:
// then it goes from every inventory too (lib/itemcontrol.js).
@@ -29,6 +30,21 @@ const CHUNK = 40; // def rows per "xdi" message
const TYPE_CLOTHING = "1";
const OFFERED_SPECIAL_TYPES = ["0", "4"]; // den items that can be copied: plain, mannequin
const CURRENCY_GEMS = "0";
// the fields of a def row the patched client reads from "xdi"
// (ItemXtCommManager.addItemDef, DenXtCommManager.addDenItemDef): the rest of
// the base's row is only weight, ~600 bytes a row and 5000 rows at login.
const CLIENT_FIELDS = {
clothing: ["id", "layerDefId", "layerId", "type", "value", "titleStrId", "isGiftable", "membersOnly", "itemStatus", "enviroType",
"avatarUseFlags", "recycleValue", "currencyType", "defense", "attack", "attackMediaRefId", "combatType", "modifierType",
"modifierValue", "criticalHit", "combinedCost", "colors", "availabilityStartTime", "availabilityEndTime"],
den: ["id", "abbrName", "combinedCost", "cost", "currencyType", "enviroType", "flag", "gameDefId", "itemStatus", "layer",
"mannequinAvatarDefId", "mannequinCatId", "membersOnly", "nameStrId", "parentArrayId", "promoType", "recycleValue",
"scalePercent", "sortCat", "specialType", "typeCat", "availabilityStartTime", "availabilityEndTime", "ecoPower"],
};
// how long a fetch of the packs is taken to describe a game of that address
// that logs in (sendAll). a game logs in minutes after it fetched them.
const PACKS_SEEN_MS = 2 * 3600000;
const MAX_PACKS_SEEN = 100000; // addresses
const SCHEMA = `CREATE TABLE IF NOT EXISTS custom_items (
kind TEXT NOT NULL, id INTEGER NOT NULL, base INTEGER NOT NULL, name TEXT NOT NULL,
@@ -38,12 +54,22 @@ const SCHEMA = `CREATE TABLE IF NOT EXISTS custom_items (
const items = new Map(KINDS.map(kind => [kind, new Map()])); // kind -> id -> entry
let made = 0; // entries in the order they were made (`seq`), for lists
let broadcast = () => {}; // (cmd, ...params) to every game playing; set by lib/world.js
// address key -> {at, clothing, den, names}: the version (defpacks
// customVersion) of the packs with custom items in that address last
// fetched, the oldest within PACKS_SEEN_MS (players behind one address
// fetch at different times). an entry's `changed` is the version of its last change.
const packsSeen = new Map();
const db = () => accounts.database();
const now = () => Math.floor(Date.now() / 1000);
const baseDef = (kind, id) => (kind === "den" ? defpacks.denItemDef(id) : defpacks.itemDef(id));
// the file name an uploaded music track is asked for by (lib/custommusic.js):
// a new upload is a new name, so no game plays an old copy from its cache.
const audioName = entry => `CustomMusic${entry.id}_${entry.audio}`;
let audioGone = () => {}; // (entry): an uploaded track's item was deleted; set by lib/custommusic.js
// the def row of an entry: its base's row with its own id, name, price and
// colours, always on sale and marked new.
const rowOf = entry => {
@@ -59,12 +85,34 @@ const rowOf = entry => {
combinedCost: "",
};
if (entry.kind === "den") {
// a music track uploaded by staff (lib/custommusic.js): the game plays
// "audio/<abbrName>.mp3", which the server answers with its file
if (entry.audio) {
own.abbrName = audioName(entry);
}
return {...base, ...own, nameStrId: String(STRING_BASE.den + entry.id - FIRST_ID), cost: String(entry.cost)};
}
return {...base, ...own, titleStrId: String(STRING_BASE.clothing + entry.id - FIRST_ID), value: String(entry.cost), colors: entry.colors.join(","), isGiftable: "1"};
};
const apply = entry => defpacks.setCustomItem(entry.kind, rowOf(entry), entry.name, entry.inShop);
const apply = entry => {
defpacks.setCustomItem(entry.kind, rowOf(entry), entry.name, entry.inShop);
entry.changed = defpacks.customVersion();
};
// what "xdi" carries of an entry: the fields the client reads, its name and
// picture. clothing goes through the clients' pack transform, so the wear
// rules reach custom items too.
const clientRow = entry => {
const row = entry.kind === "clothing" ? defpacks.clientItemRow(rowOf(entry)) : rowOf(entry);
const out = {};
for (const field of CLIENT_FIELDS[entry.kind]) {
if (row[field] !== undefined) {
out[field] = row[field];
}
}
return {...out, name: entry.name, art: entry.artPending ? "" : entry.art || "", artMode: entry.artMode || "sticker"};
};
// "xdi" [.., .., kind, json]: def rows with their names, as JSON. a field
// may not hold "%" (lib/sfs.js drops it), so a "%" in a name is written as
@@ -75,9 +123,7 @@ const messages = entries => {
const out = [];
for (const kind of KINDS) {
// a picture waiting for a moderator is not shown yet
const rows = entries.filter(entry => entry.kind === kind && !entry.pending)
.map(entry => ({...(kind === "clothing" ? defpacks.clientItemRow(rowOf(entry)) : rowOf(entry)), name: entry.name,
art: entry.artPending ? "" : entry.art || "", artMode: entry.artMode || "sticker"}));
const rows = entries.filter(entry => entry.kind === kind && !entry.pending).map(clientRow);
for (let at = 0; at < rows.length; at += CHUNK) {
out.push([kind, xtRows(rows.slice(at, at + CHUNK))]);
}
@@ -119,6 +165,7 @@ const fromRow = row => ({
artMode: LOOKS.includes(row.art_mode) ? row.art_mode : "sticker",
pending: row.pending === 1,
artPending: row.art_pending === 1,
audio: /^[0-9a-f]{8,64}$/.test(row.audio || "") ? row.audio : null,
});
// a player-made item (lib/playeritems.js) has the maker's account id;
@@ -143,6 +190,10 @@ const addOwnerColumn = () => {
if (!columns.includes("art_pending")) {
db().exec("ALTER TABLE custom_items ADD COLUMN art_pending INTEGER");
}
// a music track uploaded by staff (lib/custommusic.js): its file's version
if (!columns.includes("audio")) {
db().exec("ALTER TABLE custom_items ADD COLUMN audio TEXT");
}
};
const load = () => {
@@ -233,10 +284,12 @@ const create = (kind, fields, by, ownerId = null, pending = false) => {
return values;
}
const id = Math.max(FIRST_ID - 1, ...items.get(kind).keys()) + 1;
// `fields.audio`: an uploaded music track's version (lib/custommusic.js)
const audio = kind === "den" && /^[0-9a-f]{8,64}$/.test(String(fields.audio || "")) ? String(fields.audio) : null;
const entry = {kind, id, base: baseId, colors: [], ...values, createdBy: String(by), createdAt: now(), ownerId, artMode: "sticker", pending, artPending: false,
seq: made++};
db().prepare("INSERT INTO custom_items (kind, id, base, name, cost, members, colors, in_shop, created_by, created_at, owner_id, pending) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
.run(kind, id, baseId, entry.name, entry.cost, entry.members ? 1 : 0, entry.colors.join(","), entry.inShop ? 1 : 0, entry.createdBy, entry.createdAt, ownerId, pending ? 1 : 0);
audio, seq: made++};
db().prepare("INSERT INTO custom_items (kind, id, base, name, cost, members, colors, in_shop, created_by, created_at, owner_id, pending, audio) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
.run(kind, id, baseId, entry.name, entry.cost, entry.members ? 1 : 0, entry.colors.join(","), entry.inShop ? 1 : 0, entry.createdBy, entry.createdAt, ownerId, pending ? 1 : 0, audio);
items.get(kind).set(id, entry);
if (!pending) {
apply(entry);
@@ -281,6 +334,7 @@ const setArtMode = (kind, id, mode) => {
}
entry.artMode = mode;
db().prepare("UPDATE custom_items SET art_mode = ? WHERE kind = ? AND id = ?").run(mode, kind, entry.id);
entry.changed = defpacks.customChanged();
announce(entry);
return {item: entry};
};
@@ -295,6 +349,7 @@ const setArt = (kind, id, art, pending = false) => {
entry.art = art || null;
entry.artPending = Boolean(art && pending);
db().prepare("UPDATE custom_items SET art = ?, art_pending = ? WHERE kind = ? AND id = ?").run(entry.art, entry.artPending ? 1 : 0, kind, entry.id);
entry.changed = defpacks.customChanged();
announce(entry);
};
@@ -324,6 +379,9 @@ const remove = (kind, id) => {
db().prepare("DELETE FROM custom_items WHERE kind = ? AND id = ?").run(kind, entry.id);
items.get(kind).delete(entry.id);
defpacks.unsetCustomItem(kind, entry.id);
if (entry.audio) {
audioGone(entry);
}
return {item: entry};
};
@@ -333,6 +391,10 @@ const list = () => KINDS.flatMap(kind => [...items.get(kind).values()])
module.exports = {
KINDS,
FIRST_ID,
audioName,
onAudioGone: callback => {
audioGone = callback;
},
load,
create,
update,
@@ -362,9 +424,36 @@ module.exports = {
const def = baseDef(entry.kind, entry.base);
return def ? defpacks.string(entry.kind === "den" ? def.nameStrId : def.titleStrId) || String(def.abbrName || entry.base) : String(entry.base);
},
// every custom item, for a game logging in.
// an address was sent a pack with custom items in: "clothing", "den" or
// "names" (lib/defpacks.js customPackKind), made at `version`.
sawPack(key, packKind, version) {
const time = Date.now();
const seen = packsSeen.get(key);
if (seen && time - seen.at < PACKS_SEEN_MS) {
if (seen[packKind] === undefined) {
seen[packKind] = version;
}
return;
}
packsSeen.delete(key);
packsSeen.set(key, {at: time, [packKind]: version});
// the oldest are first
for (const [oldKey, old] of packsSeen) {
if (packsSeen.size <= MAX_PACKS_SEEN && time - old.at < PACKS_SEEN_MS) {
break;
}
packsSeen.delete(oldKey);
}
},
// the custom items a game logging in may not have: those changed since its
// address fetched the packs, and those with a picture (which the packs do
// not carry); every one when the address fetched none lately.
sendAll(session) {
for (const params of messages(list().reverse().filter(entry => !entry.pending))) {
const seen = packsSeen.get(limits.key(session.address));
const fresh = seen && Date.now() - seen.at < PACKS_SEEN_MS && seen.names !== undefined ? seen : null;
const since = kind => (fresh && fresh[kind] !== undefined ? Math.min(fresh[kind], fresh.names) : -1);
const needed = entry => !entry.pending && (entry.changed > since(entry.kind) || (entry.art && !entry.artPending));
for (const params of messages(list().reverse().filter(needed))) {
session.sendXt("xdi", -1, ...params);
}
},
+174
View File
@@ -0,0 +1,174 @@
"use strict";
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const {logText} = require("./logtext.js");
const cdn = require("./cdn.js");
const config = require("../config.js");
const customItems = require("./customitems.js");
const extraMusic = require("./extramusic.js");
// music tracks staff upload in the panels (permission "music.upload",
// lib/roles.js): an MP3 made a den music item while the server runs, as the
// extra tracks of lib/extramusic.js are. each is a custom den item
// (lib/customitems.js) made from the game's "Jam On", with an `audio`
// version of its own: games are sent its def row at once, players get it
// from the item finder (or the shop, if staff put it on sale), and deleting
// it takes it from everyone, as with any custom item.
//
// a den music item plays "audio/<abbrName>.mp3" from the content server
// (DenItemHolder); for these the server answers with the file uploaded, kept
// in data/custom-music/<item id>-<version>.mp3 (the data folder is the one
// place the server writes to).
const MAX_BYTES = 15 * 1024 * 1024;
const MIN_BYTES = 4 * 1024;
const VERSION_LENGTH = 12;
const FOLDER = () => path.join(config.dataDir, "custom-music");
const fileOf = entry => path.join(FOLDER(), `${entry.id}-${entry.audio}.mp3`);
// MPEG audio layer III, as the game's Flash plays it: an ID3v2 tag may come
// first; then a frame header whose next frame is where its length says.
const BITRATES = {
1: [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
2: [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
};
const SAMPLE_RATES = {3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000]};
// the frame at `at`: {length, sampleRate} or null.
const frameAt = (data, at) => {
if (at + 4 > data.length || data[at] !== 0xFF || (data[at + 1] & 0xE0) !== 0xE0) {
return null;
}
const version = (data[at + 1] >> 3) & 3; // 3 MPEG-1, 2 MPEG-2, 0 MPEG-2.5
const layer = (data[at + 1] >> 1) & 3; // 1 is layer III
const bitrateIndex = data[at + 2] >> 4;
const rateIndex = (data[at + 2] >> 2) & 3;
const padding = (data[at + 2] >> 1) & 1;
if (version === 1 || layer !== 1 || bitrateIndex === 0 || bitrateIndex === 15 || rateIndex === 3) {
return null;
}
const bitrate = BITRATES[version === 3 ? 1 : 2][bitrateIndex] * 1000;
const sampleRate = SAMPLE_RATES[version][rateIndex];
return {length: Math.floor(((version === 3 ? 144 : 72) * bitrate) / sampleRate) + padding, sampleRate};
};
// null for an MP3 the game can play, or what is wrong with it.
const problem = data => {
if (!Buffer.isBuffer(data) || data.length < MIN_BYTES) {
return "That file is too small to be a song.";
}
if (data.length > MAX_BYTES) {
return `That file is too big: ${MAX_BYTES / 1024 / 1024} MB at most.`;
}
let at = 0;
if (data.toString("latin1", 0, 3) === "ID3" && data.length > 10) {
at = 10 + (((data[6] & 0x7F) << 21) | ((data[7] & 0x7F) << 14) | ((data[8] & 0x7F) << 7) | (data[9] & 0x7F)) + (data[5] & 0x10 ? 10 : 0);
}
// the first frame: the header, then two more where their lengths say
for (const end = Math.min(data.length, at + 64 * 1024); at < end; at++) {
const first = frameAt(data, at);
const second = first && frameAt(data, at + first.length);
const third = second && frameAt(data, at + first.length + second.length);
if (third) {
return null;
}
}
return "That is not an MP3 file (MPEG audio layer III).";
};
const tracks = () => customItems.list().filter(entry => entry.kind === "den" && entry.audio);
// content path ("1830/audio/<hash>") -> entry, made again when the tracks change.
let paths = null;
const pathMap = () => {
if (!paths) {
paths = new Map(tracks().map(entry => [cdn.hashedPath(`audio/${customItems.audioName(entry)}.mp3`), entry]));
}
return paths;
};
// what to answer a content request with when it is for one of these
// tracks: {body, type}; undefined when it is not.
const asset = async relPath => {
const entry = pathMap().get(relPath);
if (!entry) {
return undefined;
}
const body = await fs.promises.readFile(fileOf(entry)).catch(() => null);
return {body, type: "audio/mpeg"};
};
// an upload made a track: {item} or {error}. `fields`: {name, cost, inShop, members}.
const add = (data, fields, by) => {
const wrong = problem(data);
if (wrong) {
return {error: wrong};
}
const audio = crypto.createHash("sha256").update(data).digest("hex").slice(0, VERSION_LENGTH);
fs.mkdirSync(FOLDER(), {recursive: true, mode: 0o700});
// written before the item exists, so no game asks for a file not there yet
const waiting = path.join(FOLDER(), `new-${audio}-${process.pid}.mp3`);
fs.writeFileSync(waiting, data, {mode: 0o600});
const result = customItems.create("den", {name: fields.name, cost: fields.cost, members: fields.members,
inShop: fields.inShop === true, base: extraMusic.TEMPLATE, audio}, by);
if (result.error) {
fs.rmSync(waiting, {force: true});
return result;
}
fs.renameSync(waiting, fileOf(result.item));
paths = null;
console.log(`[custom music] ${logText(by)} uploaded "${logText(result.item.name)}" (den item ${logText(result.item.id)}, ${logText(data.length)} bytes)`);
return result;
};
// the file of a track, for staff to listen to before or after: {data} or null.
const file = id => {
const entry = tracks().find(track => track.id === Number(id));
if (!entry) {
return null;
}
const data = (() => {
try {
return fs.readFileSync(fileOf(entry));
}
catch (err) {
return null;
}
})();
return data ? {data, entry} : null;
};
// for the panels: newest first
const list = () => tracks().map(entry => ({id: entry.id, name: entry.name, cost: entry.cost, inShop: entry.inShop,
createdBy: entry.createdBy, createdAt: entry.createdAt,
bytes: (() => {
try {
return fs.statSync(fileOf(entry)).size;
}
catch (err) {
return 0;
}
})()}));
// a track's item was deleted (lib/itemcontrol.js deleteCustom): its file goes too.
customItems.onAudioGone(entry => {
fs.rmSync(fileOf(entry), {force: true});
paths = null;
});
// at start: files of tracks no longer there (and of uploads cut short) go.
const load = () => {
const kept = new Set(tracks().map(entry => path.basename(fileOf(entry))));
let gone = 0;
for (const name of fs.existsSync(FOLDER()) ? fs.readdirSync(FOLDER()) : []) {
if (!kept.has(name)) {
fs.rmSync(path.join(FOLDER(), name), {force: true});
gone++;
}
}
console.log(`[custom music] ${logText(kept.size)} uploaded tracks${gone ? `, ${logText(gone)} stray files removed` : ""}`);
};
module.exports = {MAX_BYTES, problem, asset, add, file, list, load};
+91 -17
View File
@@ -44,8 +44,9 @@ const DEF_WORLD_ITEMS = 1064;
const DEF_NPC = 1025;
const DEF_NAMEBAR_BADGE = 1049;
const DEF_EMOTICON = 1036;
const DEF_NEWSPAPER = 1065; // the Jamaa Journal's pages (newspaper.NewspaperManager)
const OFFERED_SPECIAL_TYPES = ["0", "4"]; // den items: plain, mannequin
const OFFERED_SPECIAL_TYPES = ["0", "4", "6", "7"]; // den items: plain, mannequin, eco producer and consumer (lib/eco.js)
const DEN_ITEM_MASTERPIECE = 2725;
const packs = new Map();
@@ -181,6 +182,13 @@ const ADDED_STRINGS = {
9000004: "Crystal Palace (concept)",
// the buddy game the client's files call "fourGem"; no string says so.
9000005: "Four Gems",
// a shop's title when its room gives it none (lib/world.js SHOP_KIND_TITLES)
9000010: "Clothing Shop",
9000011: "Den Shop",
9000012: "Den Rooms",
9000013: "Shop",
9000014: "Exchange",
9000015: "Diamond Shop",
};
// the game under this server's name. its text says "Animal Jam", "Animal
@@ -239,6 +247,31 @@ const withCustomRows = id => pack => {
return pack;
};
// colours of clothing items from a dump of a beta-era inventory (art id,
// then the colour as 4 bytes, little-endian), added after each item's own
// so the colours already given keep their place. the shop shows a list's
// first 8 only, so these are had from the item givers.
const DUMP_COLOURS = new Map([
[231, [0x6929C069]], // Rare Eyeball Hat (Beta EyeBall; tried in the game)
[224, [0x67520169]], // Creature Mask (Beta Creature Mask)
[136, [0x2C083069, 0x55153131]], // Tiara (Beta Tiara, Milky Tiara)
[135, [0x83550505]], // Arctic Hood (Beta Hood)
[169, [0x937FF63B]], // Elf Helmet (Beta Elf)
[714, [0x00000069]], // Furry Hat (Real Magenta Furry Hat)
[649, [0x2E2D1906]], // Turquoise Ring (1st Glitched Ring)
]);
const withDumpColours = pack => {
for (const def of Object.values(pack)) {
const added = def && DUMP_COLOURS.get(Number(def.id));
if (added) {
const colours = String(def.colors).split(",").filter(Boolean);
def.colors = [...colours, ...added.map(String).filter(colour => !colours.includes(colour))].join(",");
}
}
return pack;
};
const withAddedStrings = pack => Object.assign(withLineBreaks(withOurName(Object.assign(pack, ADDED_STRINGS, extraMusic.strings()))), customStrings);
// the extra music tracks (lib/extramusic.js), as den items like the
@@ -301,7 +334,7 @@ const SHARED_CHANGES = new Map([
[DEF_PARTY, withRestoredParties],
[DEF_DEN_ROOM, withoutPrices(DEF_DEN_ROOM, withAddedDens)],
[DEF_DEN_ITEM, withoutPrices(DEF_DEN_ITEM, pack => withCustomRows(DEF_DEN_ITEM)(withExtraMusic(pack)))],
[DEF_ITEM, withoutPrices(DEF_ITEM, withCustomRows(DEF_ITEM))],
[DEF_ITEM, withoutPrices(DEF_ITEM, pack => withCustomRows(DEF_ITEM)(withDumpColours(pack)))],
[DEF_DIAMOND, withoutPrices(DEF_DIAMOND)],
[DEF_PET, withoutPrices(DEF_PET)],
[DEF_LOCALIZATION_EN, withAddedStrings],
@@ -370,24 +403,51 @@ const CLIENT_PACKS = new Map([
[DEF_NAMEBAR_BADGE, () => {}],
]);
const clientPackPaths = new Map([...CLIENT_PACKS.keys()].map(id => [cdn.hashedPath(`defPacks/${id}`), id]));
const clientPackBodies = new Map(); // id -> {day, allOnSale, body}
const clientPackBodies = new Map(); // id -> {day, allOnSale, body, version, madeAt}
const clientPacksChanged = new Set(); // ids whose body is older than a custom item change
const clientPacksMaking = new Map(); // id -> the promise of the body being made
// a pack is made again after a custom item change at most every
// config.packRemakeMs: the item pack takes ~70 ms of the one thread at 5000
// items (~300 ms at 50000), and players make items many times a minute.
// until then the body made before goes out, with the version it has; a
// game logging in is sent what changed after it (lib/customitems.js sendAll).
const deflateRaw = require("util").promisify(zlib.deflateRaw);
// the packs custom items are in: their rows, and their names
const CUSTOM_PACK_KINDS = new Map([[DEF_ITEM, "clothing"], [DEF_DEN_ITEM, "den"], [DEF_LOCALIZATION_EN, "names"]]);
// the pack at `relPath` as clients should get it, or null when it is not
// one of the above (and comes straight from the CDN).
const makeClientPack = async id => {
// the version before the rows are read: a change while it is made counts
// as after, and is sent at login (more than needed, never less)
const version = customVersion;
const pack = await loadChanged(id);
CLIENT_PACKS.get(id)(pack);
// deflated on libuv's threads, not this one
const body = await deflateRaw(amf3.encode(pack));
const made = {day: sales.today(), allOnSale: sales.everythingOnSale(), body, version, madeAt: Date.now()};
clientPackBodies.set(id, made);
if (customVersion === version) {
clientPacksChanged.delete(id);
}
return made;
};
// the pack at `relPath` as clients should get it, {body, version}, or null
// when it is not one of the above (and comes straight from the CDN).
// `version`: customVersion() of the custom items in it.
const clientPack = async relPath => {
const id = clientPackPaths.get(relPath);
if (id === undefined) {
return null;
}
const made = clientPackBodies.get(id);
if (made && made.day === sales.today() && made.allOnSale === sales.everythingOnSale()) {
return made.body;
if (made && made.day === sales.today() && made.allOnSale === sales.everythingOnSale()
&& (!clientPacksChanged.has(id) || Date.now() - made.madeAt < config.packRemakeMs)) {
return made;
}
const pack = await loadChanged(id);
CLIENT_PACKS.get(id)(pack);
const body = zlib.deflateRawSync(amf3.encode(pack));
clientPackBodies.set(id, {day: sales.today(), allOnSale: sales.everythingOnSale(), body});
return body;
if (!clientPacksMaking.has(id)) {
clientPacksMaking.set(id, makeClientPack(id).finally(() => clientPacksMaking.delete(id)));
}
return clientPacksMaking.get(id);
};
// most packs are tables: an object of rows keyed by row index.
@@ -428,6 +488,7 @@ let npcDefs = new Map(); // the characters of the adventures, see lib/disguises.
// An avatar attachment is named by its emoticon definition id on the wire,
// while AvatarWorldView needs the media id stored by that definition.
let emoticonMediaIds = new Map();
let journalPages = []; // the Jamaa Journal's pages: {id, page (media id), start (seconds)}
// A pack whose feature can be done without: missing (offline and never
// cached) just leaves that feature empty.
@@ -457,8 +518,9 @@ const init = async () => {
petIds = [...petDefs.keys()];
denItemDefs = new Map((await load(DEF_DEN_ITEM)).map(def => [Number(def.id), def]));
// special types carry extra state (a den portal's destination, a shop's
// stock, ...). of those only mannequins (4) are modelled, in lib/dens.js,
// so plain den items and mannequins are what is offered.
// stock, ...). of those mannequins (4) are modelled, in lib/dens.js, and
// the eco items (6, 7) in lib/eco.js, so those and plain den items are
// what is offered.
// the Masterpiece item is a painting's frame, made in the Art Studio and
// nowhere else (lib/masterpieces.js).
denItemIds = [...denItemDefs].filter(([id, def]) => OFFERED_SPECIAL_TYPES.includes(def.specialType) && id !== DEN_ITEM_MASTERPIECE).map(([id]) => id);
@@ -495,6 +557,8 @@ const init = async () => {
petToyDefs = await loadOptional(DEF_PET_TOY);
npcDefs = new Map((await loadOptional(DEF_NPC)).map(def => [Number(def.id), def]));
emoticonMediaIds = new Map((await loadOptional(DEF_EMOTICON)).map(def => [Number(def.id), Number(def.mediaRef)]));
journalPages = (await loadOptional(DEF_NEWSPAPER)).map(def => ({id: Number(def.id), page: Number(def.pageMediaRefId),
start: Number(def.availabilityStartTime) || 0})).filter(page => page.page > 0);
partyDefs = new Map((await loadOptional(DEF_PARTY)).map(def => {
const room = roomPathsById.get(Number(def.roomDefId));
return [Number(def.id), {
@@ -535,8 +599,8 @@ const setCustomItem = (kind, row, name, inShop = true) => {
clothingIds = clothingIds.includes(id) ? clothingIds : [...clothingIds, id];
}
customInShop[kind][inShop ? "add" : "delete"](id);
clientPackBodies.delete(pack);
clientPackBodies.delete(DEF_LOCALIZATION_EN);
clientPacksChanged.add(pack);
clientPacksChanged.add(DEF_LOCALIZATION_EN);
customVersion++;
};
@@ -558,7 +622,7 @@ const unsetCustomItem = (kind, id) => {
clothingIds = clothingIds.filter(one => one !== number);
}
customInShop[kind].delete(number);
clientPackBodies.delete(pack);
clientPacksChanged.add(pack);
customVersion++;
};
@@ -569,6 +633,13 @@ module.exports = {
// the custom items on sale, the newest first.
customShopIds: kind => [...customInShop[kind]].reverse(),
customVersion: () => customVersion,
// a change of a custom item that is not in the packs (its picture): one
// more version, for a game logging in to be told of it
customChanged: () => ++customVersion,
// the avatarUseFlags every clothing row has in the clients' pack (any animal)
EVERY_AVATAR,
// "clothing", "den" or "names" for a pack path with custom items in (lib/customitems.js sawPack), else null.
customPackKind: relPath => CUSTOM_PACK_KINDS.get(clientPackPaths.get(relPath)) || null,
load,
itemDef: id => itemDefs.get(Number(id)),
clothingIds: () => clothingIds,
@@ -599,6 +670,9 @@ module.exports = {
badgeIds: () => badgeIds,
npcDef: id => npcDefs.get(Number(id)),
emoticonMediaId: id => emoticonMediaIds.get(Number(id)) || 0,
// the media ids of the newest Jamaa Journal pages out by `now` (seconds), newest first
newestJournalPages: (count, now = Date.now() / 1000) => journalPages.filter(page => page.start <= now)
.sort((one, other) => other.start - one.start || other.id - one.id).slice(0, count).map(page => page.page),
oddDenItemIds: () => oddDenItemIds,
// den items that exist to be given by id and are in no shop.
unsoldDenItemIds: () => extraMusic.ids,
+1
View File
@@ -0,0 +1 @@
{"1":{"versions":[0,1,2,3,4,5,6,7],"colours":[["56c3d8","1078ff","4acaff","4876ba"],["8f48ff","3d00a7","5e1dff","5d0089"],["ff99f0","e150ff","ff6bf7","ff3dba"],["ac0912","ea004f","c40000","a10000"],["ff732b","dd3c4d","ff742d","e84138"],["f3ff86","d0ee19","e6ff3b","dfff05"],["63ff66","007917","23b700","035000"],["63565d","201219","551f4c","2f151f"]]},"9":{"versions":[0,1]},"13":{"versions":[0,1,2,3]},"19":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["7cbbff","2388ff","b9fffc","6bc1ff"],["be5bff","9348ff","42195b","ac43ff"],["e689c2","e45dad","fbfbfb","ea65c4"],["c8a0cd","cc434c","887e8e","ff4b4b"],["efcd34","e57712","ffffff","7bfff2"],["fff81a","fff81a","835c40","ff6bb3"],["4cbf00","43910b","ade53b","57de00"],["9e9e9e","5c5c7f","727c72","ffbf15"],["9e1616","3a3a3a","0f0f0f","ff1d1d"],["644b18","503000","e0b61f","7b4100"]]},"21":{"versions":[0,1,2]},"27":{"versions":[0,1,2,3]},"36":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["2b5eff","ffd646","56b8ff","b7ecff"],["ee58ff","5e0096","ffcf84","e3bcff"],["ff50d8","fbfbfb","ffbc1d","ffffef"],["ff3418","050505","ff9e53","ffffff"],["ff7323","ffa640","ffe42d","c7fcff"],["f8ff12","150f00","f3ff1a","050500"],["4caf00","adff3b","fff87e","c4ffe2"],["969696","ffdb5b","e0e5ff","809ca2"],["3d3d3d","830004","fafafa","0d0d0d"],["644b18","2b0c00","b9ab00","314800"]]},"37":{"versions":[0,1,3,4,5,6,7],"colours":[["a1daff","7bbfe8","b7eaff","4893ff"],["ceafff","a550ff","5d00b7","9c50ff"],["ff9999","990000","e95353","e11515"],["ffca94","f4a500","d07200","e37d48"],["dbe700","ecd743","ffff02","fff20a"],["afffa4","0a9100","75ff5e","30ff0d"],["727272","909090","f6f6f6","dedede"]]},"45":{"versions":[0,1,2,3,4,5,6,7]},"48":{"versions":[0,1,2,3,4,5,6,7]},"49":{"versions":[0,1,2,3,4,5,6,7]},"53":{"versions":[0,1,2,3,4,5,6,7]},"54":{"versions":[0,1,2,3,4,5,6,7]},"56":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["3e89d0","0d3673","b17400"],["9361ff","42195b","ff8ce4"],["f771a8","ff33a9","ffffff"],["d24743","ae3d59","434343"],["cf6227","e78100","ffe63d"],["ffea30","ff6d1a","bc7900"],["bde745","ff9400","dfaa00"],["969696","525252","ffffff"],["303030","f1f1f1","7d7d7d"],["91602d","ffe463","acb43e"]]},"83":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["c7f3ff","408aff","6bdaff"],["c976ff","5e0096","dcd4ff"],["ff89f3","ff4cac","f5d7ff"],["e43437","ffffff","ffffff"],["fd7500","ffcd63","fffbea"],["ffff3d","150f00","e2fff4"],["4caf00","adff3b","ffffff"],["969696","6b7c6b","dedede"],["212121","6b4496","030303"],["713700","ffffff","fffff2"]]},"91":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["3d5977","c47821","bc8000","ab6412"],["906fa5","705091","af8957","56486c"],["e5768c","f1f1da","e9b3c7","e2c1ce"],["bd483e","373736","7f5437","30312e"],["c37138","3a3539","c75524","474446"],["b46d00","ffe042","787878","525252"],["6b7e48","433422","a16951","58462c"],["8ca0a6","7b8f90","cc9d5d","dcdaa6"],["434342","4b4641","2b3331","212121"],["8a6341","78502a","dbab64","c3b39a"]]},"131":{"versions":[0,1,2,3,4,5]},"147":{"versions":[0,1,2,3,4,5,6,7],"colours":[["7bb8f7","fffedc","dcfcff","ffffff"],["9b4eff","ffeff5","eacaff","aa69ff"],["ff9efa","f33de9","ffd2fb","ca00c4"],["d20000","636363","e62525","616161"],["ef8454","e0ffdf","efe4ce","ffffff"],["fff802","af6f2b","faff58","1ecf00"],["3dc43d","7b7800","35ee45","31cc00"],["505050","ffffff","686868","494949"]]},"152":{"versions":[0,1,2,3,4,5,6,7],"colours":[["7bb8f7","ade0e6","e0db00"],["af37d7","3b0038","f0e579"],["e825e1","ff99f7","cfcfcf"],["d20000","ffacac","eddc6b"],["ff732b","ffda76","cecece"],["ede80a","a2a700","d1d1d1"],["3dc43d","afffa4","ffd938"],["484848","757575","fffaa4"]]},"226":{"versions":[0,1,2,3,4,5,6,7],"colours":[["060043","c4dbff","0015b4","3548ff"],["f5f5f5","42195b","8d00f2","ae74eb"],["ff71e3","ffeaf1","d400c9","ff3dba"],["ac0912","fffee7","fbffa7","ea0000"],["ede3a0","d8822e","fbdf9e","be4e33"],["fff812","639ac6","949400","dfd300"],["fffbca","008903","faffbc","008e3e"],["ffffff","505050","ffffff","343434"]]},"295":{"versions":[0,1,2,3,4,5,6,7],"colours":[["3458dd","4696ff"],["9a47d8","b875ff"],["ff8193","ffc4c6"],["ff2d2d","ff9c9c"],["f57a00","ffd47b"],["e7e700","ffffbb"],["05af00","daffa3"],["7d7d7d","d5d5d5"]]},"348":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["4589ff","fffbac","4086ff","7bc744"],["a640ff","fff986","6300c2","cbe26a"],["ffffff","00b999","ff35e5","bc910e"],["01000a","ff3333","bf0000","ffffff"],["ff7a00","d6d6af","ffffff","3a5000"],["fff800","73e3e0","f7f000","b1ea8c"],["4caf00","adff3b","7dd700","c4ffe2"],["727272","bebebe","e0e5ff","a6a6a6"],["404040","3d3d3d","828282","5e0000"],["644b18","d6c72b","664d00","506a16"]]},"350":{"versions":[0,1,2,3,4,5,6,7,8,9],"colours":[["48c5ff","ffff18","5bff35","0dff1e"],["a846ff","ff650d","ffff33","43f1ff"],["ff73d9","ff30c2","ffffff","00f2eb"],["ff2d2d","828282","ffe925","fdea00"],["e76a00","35f700","ffed10","fff930"],["ffff00","4bfaff","23f700","13ff02"],["76ff20","21ea00","ff7210","ffff02"],["ffffff","cfecff","0affff","fff928"],["717171","3c3c3c","00fdf6","02fff2"],["92663a","ffcfLine truncated
+14 -4
View File
@@ -8,6 +8,7 @@ const defpacks = require("./defpacks.js");
const wearRules = require("./wearrules.js");
const epicDens = require("./epicdens.js");
const masterpieces = require("./masterpieces.js");
const eco = require("./eco.js");
const {CURRENCIES, MAX_DEN_ITEMS, hasRoom, activeAvatar, resolvePurchase, isUint} = require("./player.js");
// den items: owning, placing and recycling furniture (client side:
@@ -119,9 +120,14 @@ const petsInDen = account => account.pets.filter(pet => pet.inDen && pet.inDen.d
// it is not placed there. the three after "approved" are a masterpiece's
// (lib/masterpieces.js); one not approved yet the client keeps out of dens,
// trades and the recycler.
// an item whose def is gone (a custom item deleted) is left out of both: the
// client skipped it without reading all its fields, and read every item after
// it wrong, placed ones as not placed and the den's floor and wallpaper lost.
const known = item => Boolean(defpacks.denItemDef(item.def));
const sendDenItems = session => {
const {account} = session;
const {denItems} = account;
const denItems = account.denItems.filter(known);
const pets = petsInDen(account);
session.sendXt("di", -1, account.activeDen, denItems.length, pets.length,
...denItems.flatMap(item => {
@@ -134,13 +140,13 @@ const sendDenItems = session => {
// DenXtCommManager.denStateResponse: [itemCount, petCount, forceReload,
// (invIdx, defId, placed, x, y, version, flipped, userNameLink, imageId,
// creatorDbId, creatorUuid, [mannequin], ?)..., (invIdx, lBits, uBits, eBits,
// creatorDbId, creatorUuid, [mannequin], eco state)..., (invIdx, lBits, uBits, eBits,
// category, x, y, flipped, createdTs, personality, toy, food, name)...].
// forceReload makes the client finish a pending room change, so it is set
// when the den has just been entered.
const sendDenState = (session, room, forceReload = true) => {
const owner = room.denOwner;
const placed = itemsInDen(owner).filter(item => masterpieces.itemApproved(item));
const placed = itemsInDen(owner).filter(item => known(item) && masterpieces.itemApproved(item));
const pets = petsInDen(owner);
session.sendXt("ds", room.id, placed.length, pets.length, forceReload ? 1 : 0,
...placed.flatMap(item => {
@@ -149,7 +155,7 @@ const sendDenState = (session, room, forceReload = true) => {
// object as category 1 made wall/floor items enter the wrong display
// layer when a den was reloaded or another player visited.
return [item.inv, item.def, spot.cat || 1, spot.x, spot.y, item.version, spot.flip, "", ...masterpieces.itemFields(item),
...mannequinShownFields(owner, item), 0];
...mannequinShownFields(owner, item), eco.consumerState(owner, item)];
}),
...pets.flatMap(pet => [pet.inv, pet.lBits, pet.uBits, pet.eBits, PET_CATEGORY, pet.inDen.x, pet.inDen.y, pet.inDen.flip,
pet.createdAt, pet.personality || 0, pet.toy || 0, pet.food || 0, pet.name]));
@@ -380,6 +386,10 @@ const handlers = ({others, findOnline}) => {
session.sendXt("dss", -1);
return;
}
// the eco credits earned at the den's rate until now (lib/eco.js)
if (account.eco) {
eco.accrue(account);
}
const applied = [];
const byInv = new Map(account.denItems.map(candidate => [candidate.inv, candidate]));
const mannequins = account.denItems.filter(candidate => candidate.mannequin);
+55 -40
View File
@@ -19,11 +19,13 @@ const config = require("../config.js");
// again with a secret of this server's (data/device-key), so what is kept
// is of no use anywhere else.
//
// any one of them is a match: someone who edits /etc/machine-id or deletes
// MachineGuid still has the same disks and the client's own id. the network
// card's address alone (MAC_KIND) is a weak match: it is easily changed and
// sometimes shared, so it bans nothing; it is written down for the
// moderators instead. values every cheap board or VM has ("To be filled by
// two computers are taken for one when they share at least MIN_MATCHING of
// these (owner, 2026-10-23: one or two in common was too often someone
// else's), for a ban and for an alt alike: someone who edits
// /etc/machine-id or deletes MachineGuid still has the same board, disks
// and the client's own id. the network card's address (MAC_KIND) does not
// count towards them: it is easily changed and sometimes shared, so it bans
// nothing; it is written down for the moderators instead. values every cheap board or VM has ("To be filled by
// O.E.M.", all zeros) are left out here, so that no ban falls on everyone
// who has one. what the client noticed was wrong (the system id missing, or
// not shaped as it always is) comes as notes, and is written down too.
@@ -56,6 +58,7 @@ const SCHEMA = `
const KINDS = ["os", "board", "disk", "install", "mac"];
const STRONG = ["os", "board", "disk", "install"];
const MAC_KIND = "mac";
const MIN_MATCHING = 3; // ids but a network card's two computers share to be taken for one
const LISTS = ["disk", "mac"]; // sent as lists; the rest one each
const MAX_IN_LIST = 8;
const MAX_KEPT = 60; // ids an account keeps, the latest
@@ -106,6 +109,7 @@ const idsOf = account => {
return account.hwids;
};
const tag = entry => `${entry.kind}:${entry.id}`;
const isStrong = id => STRONG.includes(id.split(":")[0]);
const banRow = row => ({id: row.id, ids: JSON.parse(row.ids), reason: row.reason, by: row.by, createdAt: row.created_at,
accountId: row.account_id, username: row.username});
@@ -161,27 +165,29 @@ const read = device => {
return ids.some(entry => STRONG.includes(entry.kind)) ? {ids, notes} : null;
};
// the ban that keeps this computer out, or null. a network card's address
// alone keeps nobody out (see the top).
const banOf = device => {
for (const entry of device.ids) {
if (STRONG.includes(entry.kind) && banned.has(tag(entry))) {
return banned.get(tag(entry));
// the ban that has at least MIN_MATCHING of these "kind:id" in it, or
// null. network cards' addresses are not counted (see the top).
const banMatching = ids => {
const strong = new Set(ids.filter(isStrong));
const looked = new Set();
for (const id of strong) {
const ban = banned.get(id);
if (ban && !looked.has(ban.id)) {
looked.add(ban.id);
if (ban.ids.filter(one => strong.has(one)).length >= MIN_MATCHING) {
return ban;
}
}
}
return null;
};
// the ban that keeps this computer out, or null.
const banOf = device => banMatching(device.ids.map(tag));
// the ban on any computer the account signed in from lately, or null: for
// the client asking why its game was stopped.
const banOfAccount = account => {
for (const entry of idsOf(account)) {
if (STRONG.includes(entry.kind) && entry.last > now() - DAYS_KEPT * 86400 && banned.has(tag(entry))) {
return banned.get(tag(entry));
}
}
return null;
};
const banOfAccount = account => banMatching(idsOf(account).filter(entry => entry.last > now() - DAYS_KEPT * 86400).map(tag));
const alert = (account, kind, detail) => {
const last = db().prepare("SELECT at FROM device_alerts WHERE account_id = ? AND kind = ? ORDER BY id DESC LIMIT 1").get(account.id, kind);
@@ -223,38 +229,47 @@ const seen = (account, device, isBanned) => {
if (nearBan) {
alert(account, "near_ban", `same network card as a hardware ban (${banned.get(tag(nearBan)).username || "no account"})`);
}
const sharers = new Set();
const shared = new Map(); // account id -> ids in common
for (const entry of device.ids.filter(one => STRONG.includes(one.kind))) {
for (const id of holders.get(tag(entry)) || []) {
const other = id === account.id ? null : accounts.byId(id);
if (other && isBanned(other)) {
sharers.add(other.username);
if (id !== account.id) {
shared.set(id, (shared.get(id) || 0) + 1);
}
}
}
const sharers = new Set();
for (const [id, count] of shared) {
const other = count >= MIN_MATCHING ? accounts.byId(id) : null;
if (other && isBanned(other)) {
sharers.add(other.username);
}
}
if (sharers.size) {
alert(account, "shares_banned", `same hardware as banned ${[...sharers].slice(0, 5).join(", ")}`);
}
};
// the other accounts that used any of this one's computers: [{username,
// kinds: [kind], weak: true when only a network card}], most in common first.
// the other accounts that used one of this one's computers, sharing at
// least MIN_MATCHING of its ids: [{username, kinds: [kind]}], most in
// common first.
const alts = account => {
const found = new Map(); // account id -> Set of kinds
const found = new Map(); // account id -> {kinds: Set, strong: ids in common but network cards}
for (const entry of idsOf(account)) {
for (const id of holders.get(tag(entry)) || []) {
if (id !== account.id) {
if (!found.has(id)) {
found.set(id, new Set());
found.set(id, {kinds: new Set(), strong: 0});
}
found.get(id).add(entry.kind);
found.get(id).kinds.add(entry.kind);
found.get(id).strong += STRONG.includes(entry.kind) ? 1 : 0;
}
}
}
return [...found].map(([id, kinds]) => ({account: accounts.byId(id), kinds: [...kinds]}))
return [...found].filter(([, shared]) => shared.strong >= MIN_MATCHING)
.map(([id, shared]) => ({account: accounts.byId(id), kinds: [...shared.kinds], strong: shared.strong}))
.filter(entry => entry.account)
.map(entry => ({username: entry.account.username, kinds: entry.kinds, weak: entry.kinds.every(kind => kind === MAC_KIND)}))
.sort((one, other) => Number(one.weak) - Number(other.weak) || other.kinds.length - one.kinds.length || one.username.localeCompare(other.username));
.sort((one, other) => other.strong - one.strong || other.kinds.length - one.kinds.length || one.account.username.localeCompare(other.account.username))
.map(entry => ({username: entry.account.username, kinds: entry.kinds}));
};
// how many computers' worth of ids an account has, for the panels.
@@ -265,10 +280,10 @@ const knownFor = account => ({ids: idsOf(account).length, lastAt: idsOf(account)
// one of them.
const banAccount = (account, reason, by) => {
const ids = [...new Set(idsOf(account).filter(entry => entry.last > now() - DAYS_KEPT * 86400).map(tag))];
if (!ids.some(id => STRONG.includes(id.split(":")[0]))) {
return {error: "No hardware IDs known for them."};
if (ids.filter(isStrong).length < MIN_MATCHING) {
return {error: `Fewer than ${MIN_MATCHING} hardware IDs known for them.`};
}
if (ids.filter(id => STRONG.includes(id.split(":")[0])).every(id => banned.has(id))) {
if (ids.filter(isStrong).every(id => banned.has(id))) {
return {error: "Their hardware is banned already."};
}
const text = clean(reason, MAX_REASON) || NO_REASON;
@@ -281,16 +296,16 @@ const banAccount = (account, reason, by) => {
return {ban};
};
// the accounts playing from one of a ban's computers, by their latest ids.
// the accounts playing from one of a ban's computers, by their latest ids:
// those with at least MIN_MATCHING of its ids.
const accountsUnder = ban => {
const ids = new Set(ban.ids.filter(id => STRONG.includes(id.split(":")[0])));
const found = new Set();
for (const id of ids) {
const found = new Map(); // account id -> ids in common
for (const id of new Set(ban.ids.filter(isStrong))) {
for (const accountId of holders.get(id) || []) {
found.add(accountId);
found.set(accountId, (found.get(accountId) || 0) + 1);
}
}
return [...found].map(id => accounts.byId(id)).filter(Boolean);
return [...found].filter(([, count]) => count >= MIN_MATCHING).map(([id]) => accounts.byId(id)).filter(Boolean);
};
const unban = id => {
+962
View File
@@ -0,0 +1,962 @@
"use strict";
// Burrow's Discord control surface. It is intentionally a thin client over
// lib/modpanel.js: Discord proves who clicked a command, and the panel then
// proves that their linked Burrow account is still active staff and applies
// its usual permission and rank rules. There is no Discord-only staff list.
// discord.js is loaded when the bot starts, not with the server: a server
// without the package installed (npm ci) runs as before, the bot off.
let ActionRowBuilder;
let ButtonBuilder;
let ButtonStyle;
let ChannelType;
let Client;
let GatewayIntentBits;
let PermissionFlagsBits;
let SlashCommandBuilder;
const loadDiscordJs = () => {
if (Client) return true;
try {
({ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelType, Client, GatewayIntentBits, PermissionFlagsBits, SlashCommandBuilder} = require("discord.js"));
return true;
}
catch (err) {
console.log(`[discord-bot] discord.js could not be loaded (run npm ci): ${logText(err.message)}`);
return false;
}
};
const crypto = require("crypto");
const accounts = require("./accounts.js");
const config = require("../config.js");
const modpanel = require("./modpanel.js");
const modlog = require("./modlog.js");
const reports = require("./reports.js");
const world = require("./world.js");
const {logText} = require("./logtext.js");
// discord.js's MessageFlags.IsComponentsV2 and MessageFlags.Ephemeral, which
// cards need before the package is loaded
const COMPONENTS_V2 = 1 << 15;
const EPHEMERAL = 1 << 6;
const STATUS_MESSAGE_SETTING = "discordBotStatusMessage";
const STATUS_TITLE_SETTING = "discordBotStatusTitle";
const STATUS_NOTE_SETTING = "discordBotStatusNote";
const STATUS_BANNER_SETTING = "discordBotStatusBanner";
const STATUS_EVERY_MS = 5 * 60000;
const REPORT_BUTTON_PREFIX = "burrow:report:";
const MAX_GITHUB_WEBHOOK_BYTES = 512 * 1024;
const CONFIG_SETTING_PREFIX = "discordBotConfig:";
const SECURITY_SETTING = "discordBotSecurity";
const COMMUNITY_SETTING = "discordBotCommunity";
const CHANNELS = [
["reportsChannelId", "Reports"],
["statusChannelId", "Public status"],
["gameLogsChannelId", "In-game activity"],
["moderationLogsChannelId", "Moderation audit"],
["botLogsChannelId", "Discord bot audit"],
["updatesChannelId", "GitHub updates"],
];
const MANAGED_CONFIG = [...CHANNELS.map(([key]) => key), "githubRepository"];
let loadedDashboardConfig = false;
let securityConfigLoaded = false;
let securityConfig = null;
let communityConfig = null;
let communityConfigLoaded = false;
const recentMessages = new Map();
const recentJoins = [];
let lastRaidAlertAt = 0;
// Text Displays accept markdown. Keep player-provided strings readable while
// ensuring a report cannot ping a Discord role or user.
const safe = (value, max = 1000) => String(value === undefined || value === null ? "" : value)
.replace(/@/g, "@\u200b").replace(/`/g, "'").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, max);
// Discord fetches the banner itself, so only absolute http(s) URLs work.
// Blank means the card has no banner; null means the URL was rejected.
const bannerUrl = value => {
const text = String(value || "").trim();
if (!text) return "";
try {
const url = new URL(text);
return /^https?:$/.test(url.protocol) && text.length <= 500 ? url.toString() : null;
}
catch {
return null;
}
};
const statusSettings = () => ({
title: safe(accounts.setting(STATUS_TITLE_SETTING) || "Burrow status", 80) || "Burrow status",
note: safe(accounts.setting(STATUS_NOTE_SETTING) || "", 500),
banner: bannerUrl(accounts.setting(STATUS_BANNER_SETTING)) || "",
});
const setStatusSettings = ({title, note, banner}) => {
const next = {
title: safe(title || "Burrow status", 80) || "Burrow status",
note: safe(note || "", 500),
banner: bannerUrl(banner),
};
if (next.banner === null) return {error: "Banner must be an http(s) image URL of 500 characters or fewer, or blank for none."};
accounts.setSetting(STATUS_TITLE_SETTING, next.title);
accounts.setSetting(STATUS_NOTE_SETTING, next.note);
accounts.setSetting(STATUS_BANNER_SETTING, next.banner);
return next;
};
const securitySettings = () => {
if (securityConfigLoaded) return {...securityConfig};
const defaults = {enabled: false, blockInvites: true, blockedWords: [], spamLimit: 6, raidJoinLimit: 12};
try {
const saved = JSON.parse(accounts.setting(SECURITY_SETTING) || "{}");
const words = Array.isArray(saved.blockedWords) ? saved.blockedWords.map(word => safe(word, 60).toLowerCase()).filter(Boolean).slice(0, 50) : [];
securityConfig = {
enabled: saved.enabled === true,
blockInvites: saved.blockInvites !== false,
blockedWords: [...new Set(words)],
spamLimit: Number.isInteger(saved.spamLimit) && saved.spamLimit >= 2 && saved.spamLimit <= 20 ? saved.spamLimit : defaults.spamLimit,
raidJoinLimit: Number.isInteger(saved.raidJoinLimit) && saved.raidJoinLimit >= 3 && saved.raidJoinLimit <= 100 ? saved.raidJoinLimit : defaults.raidJoinLimit,
};
}
catch {
securityConfig = defaults;
}
securityConfigLoaded = true;
return {...securityConfig};
};
const updateSecuritySettings = values => {
const words = String(values.blockedWords || "").split(/\r?\n|,/)
.map(word => safe(word, 60).toLowerCase()).filter(Boolean).slice(0, 50);
const spamLimit = Number(values.spamLimit);
const raidJoinLimit = Number(values.raidJoinLimit);
if (!Number.isInteger(spamLimit) || spamLimit < 2 || spamLimit > 20 || !Number.isInteger(raidJoinLimit) || raidJoinLimit < 3 || raidJoinLimit > 100) {
return {error: "Spam limit must be 2 to 20 and raid join limit must be 3 to 100."};
}
securityConfig = {enabled: values.enabled === true, blockInvites: values.blockInvites === true,
blockedWords: [...new Set(words)], spamLimit, raidJoinLimit};
securityConfigLoaded = true;
accounts.setSetting(SECURITY_SETTING, JSON.stringify(securityConfig));
return {ok: "Discord security settings saved. Reconnect the bot to apply message and join monitoring.", security: securitySettings()};
};
const communitySettings = () => {
if (communityConfigLoaded) return {...communityConfig};
try {
const saved = JSON.parse(accounts.setting(COMMUNITY_SETTING) || "{}");
communityConfig = {ticketCategoryId: channelId(saved.ticketCategoryId) || "", ticketStaffRoleId: channelId(saved.ticketStaffRoleId) || "",
welcomeChannelId: channelId(saved.welcomeChannelId) || "", welcomeMessage: safe(saved.welcomeMessage || "Welcome {user} to {server}!", 500),
goodbyeChannelId: channelId(saved.goodbyeChannelId) || "", goodbyeMessage: safe(saved.goodbyeMessage || "Goodbye {user}.", 500)};
}
catch { communityConfig = {ticketCategoryId: "", ticketStaffRoleId: "", welcomeChannelId: "", welcomeMessage: "Welcome {user} to {server}!", goodbyeChannelId: "", goodbyeMessage: "Goodbye {user}."}; }
communityConfigLoaded = true;
return {...communityConfig};
};
const updateCommunitySettings = values => {
const current = communitySettings();
const next = {...current};
for (const key of ["ticketCategoryId", "ticketStaffRoleId", "welcomeChannelId", "goodbyeChannelId"]) {
const id = channelId(values[key]);
if (id === null) return {error: "Discord channel, category, and role IDs must contain only 5 to 25 digits."};
next[key] = id;
}
next.welcomeMessage = safe(values.welcomeMessage || "", 500);
next.goodbyeMessage = safe(values.goodbyeMessage || "", 500);
communityConfig = next;
communityConfigLoaded = true;
accounts.setSetting(COMMUNITY_SETTING, JSON.stringify(next));
return {ok: "Community and ticket settings saved.", community: communitySettings()};
};
// Non-secret routing settings are owner-controlled in the dashboard. The bot
// token and webhook secret deliberately remain environment-only, so a copied
// database or dashboard session cannot disclose them.
const loadDashboardConfig = () => {
if (loadedDashboardConfig) return;
for (const key of MANAGED_CONFIG) {
const saved = accounts.setting(`${CONFIG_SETTING_PREFIX}${key}`);
if (saved !== null) config.discord[key] = saved;
}
loadedDashboardConfig = true;
};
const channelId = value => {
const id = String(value === undefined || value === null ? "" : value).trim();
return id === "" || /^\d{5,25}$/.test(id) ? id : null;
};
const updateDashboardConfig = values => {
loadDashboardConfig();
const previousStatusChannelId = config.discord.statusChannelId || "";
const next = {};
for (const [key] of CHANNELS) {
const id = channelId(values[key]);
if (id === null) return {error: "Discord channel IDs must contain only 5 to 25 digits."};
next[key] = id;
}
const repository = String(values.githubRepository === undefined || values.githubRepository === null ? "" : values.githubRepository).trim();
if (repository && !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\/[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/.test(repository)) {
return {error: "GitHub repository must use the form owner/repository."};
}
next.githubRepository = repository;
for (const key of MANAGED_CONFIG) {
config.discord[key] = next[key];
accounts.setSetting(`${CONFIG_SETTING_PREFIX}${key}`, next[key]);
}
if (next.statusChannelId !== previousStatusChannelId) {
accounts.setSetting(STATUS_MESSAGE_SETTING, "");
}
return {ok: "Discord routing settings saved.", configuration: dashboardStatus()};
};
const duration = seconds => {
if (seconds === -1) return "permanent";
if (!seconds) return "none";
const hours = Math.ceil(Number(seconds) / 3600);
return `${hours} hour${hours === 1 ? "" : "s"}`;
};
// Components V2 means every visible response—success, refusal, report alert
// and status card—uses a Container and Text Displays. Never add `content` or
// `embeds` to these payloads: Discord ignores them for Components V2.
const card = ({title, sections = [], tone = 0x5865f2, ephemeral = false, components = []}) => ({
flags: COMPONENTS_V2 | (ephemeral ? EPHEMERAL : 0),
allowedMentions: {parse: []},
components: [{
type: 17, // Container
accent_color: tone,
components: [
{type: 10, content: `## ${safe(title, 160)}`}, // Text Display
...sections.filter(Boolean).slice(0, 8).flatMap((section, index) => [
...(index ? [{type: 14, divider: true, spacing: 1}] : []), // Separator
{type: 10, content: safe(section, 1800)},
]),
...components,
],
}],
});
const success = (title, sections, ephemeral = true) => card({title, sections, tone: 0x57f287, ephemeral});
const warning = (message, ephemeral = true) => card({title: "Burrow", sections: [message], tone: 0xfee75c, ephemeral});
const failure = (message, ephemeral = true) => card({title: "Burrow", sections: [message], tone: 0xed4245, ephemeral});
// Staff audit streams use the same compact Components V2 pattern as SRP-Bot:
// a brief summary, structured fields, and a durable log timestamp.
const logCard = ({title, description = "", fields = [], tone = 0x5865f2}) => {
const shown = fields.filter(field => field && field.name && field.value !== undefined && field.value !== null).slice(0, 12);
const components = [{type: 10, content: [
`## ${safe(title, 160)}`,
description ? safe(description, 900) : "",
].filter(Boolean).join("\n")}];
if (shown.length) {
components.push({type: 14, divider: true, spacing: 1});
components.push({type: 10, content: shown
.map(field => `• **${safe(field.name, 80)}:** ${safe(field.value, 500)}`)
.join("\n")
.slice(0, 1800)});
}
const now = Math.floor(Date.now() / 1000);
components.push({type: 14, divider: false, spacing: 1});
components.push({type: 10, content: `_Logged <t:${now}:F> (<t:${now}:R>)_`});
return {
flags: COMPONENTS_V2,
allowedMentions: {parse: []},
components: [{type: 17, accent_color: tone, components}],
};
};
const commandDefinitions = () => [
new SlashCommandBuilder().setName("burrow").setDescription("View Burrow server and player information")
.addSubcommand(command => command.setName("status").setDescription("Show the live Burrow server status"))
.addSubcommand(command => command.setName("player").setDescription("Look up a Burrow player")
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true)))
.addSubcommand(command => command.setName("reports").setDescription("Show open player reports"))
.addSubcommand(command => command.setName("staff").setDescription("Show Burrow staff"))
.addSubcommand(command => command.setName("announce").setDescription("Send an announcement to everyone playing")
.addStringOption(option => option.setName("message").setDescription("Announcement shown in-game").setRequired(true).setMaxLength(300))),
new SlashCommandBuilder().setName("moderate").setDescription("Moderate Burrow through your linked staff account")
.addSubcommand(command => command.setName("warn").setDescription("Warn a player")
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true))
.addStringOption(option => option.setName("reason").setDescription("Warning reason, e.g. behavior or custom").setRequired(true))
.addStringOption(option => option.setName("note").setDescription("Required explanation for a custom warning")))
.addSubcommand(command => command.setName("silence").setDescription("Stop a player from chatting")
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true))
.addIntegerOption(option => option.setName("hours").setDescription("Whole hours; 0 means until lifted").setRequired(true).setMinValue(0).setMaxValue(87600)))
.addSubcommand(command => command.setName("unsilence").setDescription("Let a player chat again")
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true)))
.addSubcommand(command => command.setName("kick").setDescription("Disconnect an online player")
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true)))
.addSubcommand(command => command.setName("ban").setDescription("Ban a player")
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true))
.addIntegerOption(option => option.setName("hours").setDescription("Whole hours; 0 means permanent").setRequired(true).setMinValue(0).setMaxValue(87600))
.addStringOption(option => option.setName("reason").setDescription("Why this player is being banned").setRequired(true)))
.addSubcommand(command => command.setName("unban").setDescription("Lift a player's Burrow ban")
.addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true))),
new SlashCommandBuilder().setName("discord").setDescription("Moderate this Discord server through Burrow staff permissions")
.addSubcommand(command => command.setName("timeout").setDescription("Temporarily silence a Discord member")
.addUserOption(option => option.setName("member").setDescription("Discord member").setRequired(true))
.addIntegerOption(option => option.setName("hours").setDescription("Whole hours, up to 28 days").setRequired(true).setMinValue(1).setMaxValue(672))
.addStringOption(option => option.setName("reason").setDescription("Why this member is being timed out").setMaxLength(300)))
.addSubcommand(command => command.setName("untimeout").setDescription("Remove a Discord member timeout")
.addUserOption(option => option.setName("member").setDescription("Discord member").setRequired(true))
.addStringOption(option => option.setName("reason").setDescription("Why the timeout is being removed").setMaxLength(300)))
.addSubcommand(command => command.setName("kick").setDescription("Remove a Discord member from this server")
.addUserOption(option => option.setName("member").setDescription("Discord member").setRequired(true))
.addStringOption(option => option.setName("reason").setDescription("Why this member is being removed").setMaxLength(300)))
.addSubcommand(command => command.setName("ban").setDescription("Ban a Discord member from this server")
.addUserOption(option => option.setName("member").setDescription("Discord member").setRequired(true))
.addStringOption(option => option.setName("reason").setDescription("Why this member is being banned").setMaxLength(300)))
.addSubcommand(command => command.setName("unban").setDescription("Lift a Discord server ban")
.addStringOption(option => option.setName("user_id").setDescription("Discord user ID").setRequired(true).setMinLength(5).setMaxLength(25))
.addStringOption(option => option.setName("reason").setDescription("Why the ban is being removed").setMaxLength(300)))
.addSubcommand(command => command.setName("purge").setDescription("Delete recent messages in this channel")
.addIntegerOption(option => option.setName("amount").setDescription("Messages to delete (1 to 100)").setRequired(true).setMinValue(1).setMaxValue(100))
.addStringOption(option => option.setName("reason").setDescription("Why messages are being removed").setMaxLength(300))),
new SlashCommandBuilder().setName("ticket").setDescription("Open or manage a private support ticket")
.addSubcommand(command => command.setName("open").setDescription("Open a private support ticket")
.addStringOption(option => option.setName("subject").setDescription("What you need help with").setRequired(true).setMaxLength(80)))
.addSubcommand(command => command.setName("close").setDescription("Close this support ticket")),
].map(command => command.toJSON());
// a command or button counts for a staff member signed in to the panel with
// their 2FA code (modpanel.discordBot.commandActor): Discord alone is not them.
const actorFor = interaction => modpanel.discordBot.commandActor(interaction.user.id);
const reportButton = report => new ActionRowBuilder().addComponents(
new ButtonBuilder().setCustomId(`${REPORT_BUTTON_PREFIX}${report.id}:handled`).setLabel("Mark handled").setStyle(ButtonStyle.Success),
).toJSON();
const reportCard = (report, {handled = false, ephemeral = false} = {}) => card({
title: handled ? `Report #${report.id} handled` : `Report #${report.id}`,
tone: handled ? 0x57f287 : 0xfee75c,
ephemeral,
sections: [
`**${safe(report.reporter, 40)}** reported **${safe(report.target, 40)}**\n${safe(report.reason, 200)}`,
report.detail ? `**Details**\n${safe(report.detail, 500)}` : "*No additional details.*",
report.room ? `Room: \`${safe(report.room, 100)}\`` : "",
],
components: handled ? [] : [{type: 14, divider: true, spacing: 1}, reportButton(report)],
});
const playerCard = player => success(`Player: ${player.username}`, [
`**Status**\n${player.online ? `Online${player.room ? ` in ${safe(player.room, 100)}` : ""}` : "Offline"}\nRole: ${player.role || "Player"}`,
`**Moderation**\nBan: ${duration(player.banned)}\nSilence: ${duration(player.silenced)}\nWarnings: ${player.warnings}\nOpen reports: ${player.openReports}`,
player.discord ? `**Discord**\n${safe(player.discord, 80)}` : "",
]);
const statusCard = status => {
const settings = statusSettings();
const now = Math.floor(Date.now() / 1000);
const startedAt = now - status.uptimeSeconds;
const rooms = `${status.rooms} room${status.rooms === 1 ? "" : "s"}`;
const playUrl = new URL("gameClient/game/index.html", config.siteUrl).toString();
// This is intentionally public-only: moderation reports and queue depth are
// staff data and do not belong in a community-facing server-status post.
return {
flags: COMPONENTS_V2,
allowedMentions: {parse: []},
components: [{
type: 17,
accent_color: 0x7c5ce7,
components: [
{type: 10, content: `## ${safe(settings.title, 80)}`},
{type: 14, divider: true, spacing: 1},
{type: 10, content: ["### STATUS", "🟢 **Online**", settings.note ? `\n${safe(settings.note, 500)}` : ""].filter(Boolean).join("\n")},
{type: 14, divider: true, spacing: 1},
{type: 10, content: `### PLAYERS\n\`${status.players} online\` • \`${rooms}\``},
{type: 14, divider: true, spacing: 1},
{type: 10, content: `### UPTIME\nStarted <t:${startedAt}:R> • ${status.memoryMb} MB memory`},
...settings.banner ? [{type: 12, items: [{media: {url: settings.banner}}]}] : [],
{type: 1, components: [{type: 2, style: 5, label: "Play Burrow", url: playUrl}]},
{type: 10, content: `_Last updated <t:${now}:R>_`},
],
}],
};
};
const staffCard = staff => success("Burrow staff", staff.length
? [staff.map(member => `**${safe(member.username, 40)}** — ${safe(member.role, 30)}${member.twoStep ? " · 2FA" : ""}`).join("\n")]
: ["No active Burrow staff accounts."]);
const inConfiguredGuild = interaction => interaction.guildId === config.discord.guildId;
const replyResult = async (interaction, result, title = "Burrow") => {
if (result.error) {
await interaction.editReply(failure(result.error));
return;
}
await interaction.editReply(success(title, [result.ok, result.detail].filter(Boolean)));
};
const handleBurrow = async interaction => {
const actor = actorFor(interaction);
const subcommand = interaction.options.getSubcommand();
if (subcommand === "status") {
const result = modpanel.discordBot.status(actor);
await interaction.editReply(result.error ? failure(result.error) : {...statusCard(result), flags: COMPONENTS_V2 | EPHEMERAL});
return;
}
if (subcommand === "player") {
const result = modpanel.discordBot.player(actor, interaction.options.getString("username", true));
await interaction.editReply(result.error ? failure(result.error) : {...playerCard(result.player), flags: COMPONENTS_V2 | EPHEMERAL});
return;
}
if (subcommand === "staff") {
const result = modpanel.discordBot.staff(actor);
await interaction.editReply(result.error ? failure(result.error) : staffCard(result.staff));
return;
}
if (subcommand === "announce") {
await replyResult(interaction, modpanel.discordBot.announce(actor, interaction.options.getString("message", true)), "In-game announcement");
return;
}
const result = modpanel.discordBot.reports(actor);
if (result.error) {
await interaction.editReply(failure(result.error));
return;
}
const shown = result.reports.slice(0, 5);
await interaction.editReply(success("Open reports", [
`${result.open} open report${result.open === 1 ? "" : "s"}.`,
shown.length ? shown.map(report => `#${report.id} — **${safe(report.target, 40)}** — ${safe(report.reason, 100)}`).join("\n") : "No reports are waiting.",
]));
};
const handleModerate = async interaction => {
const actor = actorFor(interaction);
const subcommand = interaction.options.getSubcommand();
const username = interaction.options.getString("username", true);
const fields = {action: subcommand};
if (subcommand === "warn") {
fields.reason = interaction.options.getString("reason", true);
fields.note = interaction.options.getString("note") || "";
}
if (subcommand === "silence" || subcommand === "ban") {
fields.hours = interaction.options.getInteger("hours", true);
}
if (subcommand === "ban") {
fields.reason = interaction.options.getString("reason", true);
}
await replyResult(interaction, modpanel.discordBot.act(actor, username, fields), `Moderation: ${subcommand}`);
};
const nativeDiscordPermission = action => ({
timeout: "chat.silence",
untimeout: "chat.silence",
kick: "player.kick",
ban: "player.ban",
unban: "player.ban",
purge: "player.kick",
})[action] || "";
const handleDiscordModeration = async interaction => {
const actor = actorFor(interaction);
const action = interaction.options.getSubcommand();
const refused = modpanel.discordBot.authorize(actor, nativeDiscordPermission(action));
if (refused) {
await interaction.editReply(failure(refused.error));
return;
}
const reason = safe(interaction.options.getString("reason") || `Burrow staff action by ${actor.username}`, 300);
const user = action === "unban" ? null : interaction.options.getUser("member", true);
if (user && modpanel.discordBot.actor(user.id)) {
await interaction.editReply(failure("Discord-native moderation cannot target an active linked Burrow staff account."));
return;
}
try {
let detail = "";
let target = user ? user.username : interaction.options.getString("user_id", true);
if (action === "timeout" || action === "untimeout" || action === "kick") {
const member = await interaction.guild.members.fetch(user.id);
if (action === "timeout") {
const hours = interaction.options.getInteger("hours", true);
await member.timeout(hours * 3600000, reason);
detail = `${hours} hour${hours === 1 ? "" : "s"}`;
}
else if (action === "untimeout") {
await member.timeout(null, reason);
}
else {
await member.kick(reason);
}
}
else if (action === "ban") {
await interaction.guild.members.ban(user.id, {reason, deleteMessageSeconds: 0});
}
else if (action === "unban") {
if (!/^\d{5,25}$/.test(target)) throw new Error("bad_user_id");
await interaction.guild.members.unban(target, reason);
}
else if (action === "purge") {
const amount = interaction.options.getInteger("amount", true);
if (!interaction.channel || !interaction.channel.isTextBased() || typeof interaction.channel.bulkDelete !== "function") throw new Error("not_text_channel");
const deleted = await interaction.channel.bulkDelete(amount, true);
detail = `${deleted.size} message${deleted.size === 1 ? "" : "s"}`;
target = "this channel";
}
else throw new Error("unknown_action");
modlog.record(actor.username, `Discord ${action}`, target, detail || reason);
await interaction.editReply(success(`Discord ${action}`, [`${safe(target, 80)} — ${detail || "completed"}.`].concat(reason ? [`Reason: ${reason}`] : [])));
}
catch (err) {
if (err.message === "bad_user_id") {
await interaction.editReply(failure("Enter a valid Discord user ID."));
return;
}
console.log(`[discord-bot] Discord ${action} failed: ${logText(err.message)}`);
await interaction.editReply(failure("Discord could not complete that action. Check the bot permission and role position."));
}
};
const ticketOwner = channel => (channel && /^burrow-ticket:(\d{5,25})$/.exec(channel.topic || "") || [])[1] || "";
const handleTicket = async interaction => {
const action = interaction.options.getSubcommand();
const settings = communitySettings();
if (action === "open") {
if (!settings.ticketCategoryId || !settings.ticketStaffRoleId) {
await interaction.editReply(failure("Tickets are not configured. Ask an owner to set the ticket category and staff role in the Discord dashboard."));
return;
}
const subject = safe(interaction.options.getString("subject", true), 80);
const channel = await interaction.guild.channels.create({
name: `ticket-${interaction.user.id}`,
type: ChannelType.GuildText,
parent: settings.ticketCategoryId,
topic: `burrow-ticket:${interaction.user.id}`,
permissionOverwrites: [
{id: interaction.guild.roles.everyone.id, deny: [PermissionFlagsBits.ViewChannel]},
{id: interaction.user.id, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory]},
{id: settings.ticketStaffRoleId, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory]},
{id: client.user.id, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ManageChannels, PermissionFlagsBits.ReadMessageHistory]},
],
}).catch(() => null);
if (!channel) {
await interaction.editReply(failure("Discord could not open the ticket. Check the category, staff role, and bot channel permissions."));
return;
}
await channel.send(card({title: "Support ticket", tone: 0x5865f2, sections: [`Opened by **${safe(interaction.user.username, 80)}**\nSubject: ${subject}`, "A staff member will reply here. Use `/ticket close` when this is resolved."]}));
await interaction.editReply(success("Ticket opened", [`Your private ticket: ${channel}`]));
return;
}
const owner = ticketOwner(interaction.channel);
const staff = modpanel.discordBot.actor(interaction.user.id);
if (!owner || (owner !== interaction.user.id && !staff)) {
await interaction.editReply(failure("Only the ticket opener or linked Burrow staff can close this ticket."));
return;
}
await interaction.channel.setName(`closed-${interaction.channel.name}`.slice(0, 100)).catch(() => {});
if (owner) await interaction.channel.permissionOverwrites.edit(owner, {ViewChannel: false}).catch(() => {});
modlog.record(staff ? staff.username : interaction.user.username, "Discord ticket closed", interaction.channel.name);
await interaction.editReply(success("Ticket closed", ["The opener can no longer view this channel. Staff retain it for the support record."]));
};
const handleButton = async interaction => {
const match = new RegExp(`^${REPORT_BUTTON_PREFIX.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(\\d+):handled$`).exec(interaction.customId);
if (!match) {
return false;
}
if (!inConfiguredGuild(interaction)) {
await interaction.reply(failure("This control belongs to another Discord server.")).catch(() => {});
return true;
}
const result = modpanel.discordBot.handleReport(actorFor(interaction), Number(match[1]));
if (result.error) {
await interaction.reply(failure(result.error)).catch(() => {});
return true;
}
await interaction.update(success(`Report #${Number(match[1])} handled`, [result.ok], false)).catch(() => {});
return true;
};
let client = null;
let statusTimer = null;
let unsubscribeReports = null;
let unsubscribeGameActivity = null;
let unsubscribeModeration = null;
let securityGatewayOn = false;
const channelFor = async id => {
if (!id || !client || !client.isReady()) return null;
const channel = await client.channels.fetch(id).catch(() => null);
return channel && channel.isTextBased() ? channel : null;
};
const postCard = async (channelId, payload, label) => {
const channel = await channelFor(channelId);
if (channel) {
await channel.send(payload).catch(err => console.log(`[discord-bot] ${label} failed: ${logText(err.message)}`));
}
};
const publishStatus = async () => {
const channel = await channelFor(config.discord.statusChannelId);
if (!channel) return {error: "The public status channel is not configured or the Discord bot is not connected."};
const players = world.players();
const payload = statusCard({players: players.length, rooms: new Set(players.map(player => player.room).filter(Boolean)).size,
reports: reports.openCount(), uptimeSeconds: Math.floor(process.uptime()), memoryMb: Math.round(process.memoryUsage().rss / 1048576)});
// The public status card needs no staff actor; it exposes only aggregate
// counts. Store its message id in the server database so restarts edit it.
const saved = accounts.setting(STATUS_MESSAGE_SETTING);
const existing = saved && await channel.messages.fetch(saved).catch(() => null);
if (existing) {
const updated = await existing.edit(payload).then(() => true).catch(err => {
console.log(`[discord-bot] status update failed: ${logText(err.message)}`);
return false;
});
return updated ? {ok: "The public status card was updated."} : {error: "Discord could not update the public status card."};
}
const message = await channel.send(payload).catch(err => {
console.log(`[discord-bot] status post failed: ${logText(err.message)}`);
return null;
});
if (!message) return {error: "Discord could not post the public status card."};
accounts.setSetting(STATUS_MESSAGE_SETTING, message.id);
return {ok: "The public status card was posted."};
};
const notifyReport = async report => {
await postCard(config.discord.reportsChannelId, reportCard(report), "report notification");
};
const notifyGameActivity = async entry => {
const minutes = Math.max(1, Math.ceil((entry.playedSeconds || 0) / 60));
const signedIn = entry.type === "login";
await postCard(config.discord.gameLogsChannelId, logCard({
title: "In-game activity",
description: signedIn ? "A player signed in." : "A player signed out.",
tone: signedIn ? 0x57f287 : 0x5865f2,
fields: [
{name: "Player", value: entry.username},
{name: "Event", value: signedIn ? "Signed in" : "Signed out"},
...(!signedIn ? [{name: "Session", value: `${minutes} minute${minutes === 1 ? "" : "s"}`}] : []),
],
}), "game activity log");
};
const notifyModeration = async entry => {
await postCard(config.discord.moderationLogsChannelId, logCard({
title: "Moderation audit",
description: "A Burrow staff action was recorded.",
tone: 0xfee75c,
fields: [
{name: "Staff", value: entry.by},
{name: "Action", value: entry.action},
...(entry.target ? [{name: "Player", value: entry.target}] : []),
...(entry.detail ? [{name: "Details", value: entry.detail}] : []),
],
}), "moderation log");
};
const notifyBot = async (interaction, action) => {
const actor = modpanel.discordBot.actor(interaction.user.id);
await postCard(config.discord.botLogsChannelId, logCard({
title: "Discord bot audit",
description: "A Discord command or control was used.",
tone: actor ? 0x5865f2 : 0xed4245,
fields: [
{name: "Discord user", value: `${interaction.user.username} (${interaction.user.id})`},
{name: "Action", value: action},
{name: "Linked staff account", value: actor ? actor.username : "No active linked Burrow staff account."},
],
}), "Discord bot audit log");
};
const securityIncident = async (title, sections, detail = "") => {
await postCard(config.discord.moderationLogsChannelId, logCard({
title,
description: "Discord security activity detected.",
tone: 0xed4245,
fields: [{name: "Details", value: sections.filter(Boolean).join("\n")}],
}), "Discord security log");
modlog.record("discord security", title.toLowerCase(), "", detail);
};
const isConfiguredGuild = guild => Boolean(guild && guild.id === config.discord.guildId);
const inspectDiscordMessage = async message => {
const settings = securitySettings();
if (!settings.enabled || message.author?.bot || !isConfiguredGuild(message.guild)) return;
const at = Date.now();
const key = message.author.id;
const times = (recentMessages.get(key) || []).filter(time => time > at - 10000);
times.push(at);
recentMessages.set(key, times);
const text = String(message.content || "").toLowerCase();
const hasInvite = settings.blockInvites && /(?:discord\.gg|discord(?:app)?\.com\/invite)\//i.test(text);
const word = settings.blockedWords.find(entry => text.includes(entry));
const reason = times.length > settings.spamLimit ? "message spam" : hasInvite ? "Discord invite" : word ? "blocked word" : "";
if (!reason) return;
if (message.deletable) await message.delete().catch(() => {});
await securityIncident("Discord AutoMod", [
`Member: **${safe(message.author.username, 80)}**`,
`Action: deleted message for ${reason}.`,
], `${safe(message.author.username, 80)}: ${reason}`);
};
const inspectDiscordJoin = async member => {
const settings = securitySettings();
if (!settings.enabled || !isConfiguredGuild(member.guild)) return;
const at = Date.now();
recentJoins.push(at);
while (recentJoins.length && recentJoins[0] <= at - 60000) recentJoins.shift();
if (recentJoins.length < settings.raidJoinLimit || lastRaidAlertAt > at - 60000) return;
lastRaidAlertAt = at;
await securityIncident("Discord anti-raid alert", [
`${recentJoins.length} members joined in the last minute.`,
"Review recent joins and use the dashboard or Discord moderation controls if action is needed.",
], `${recentJoins.length} joins in one minute`);
};
const communityNotice = async (member, kind) => {
const settings = communitySettings();
const channelId = kind === "welcome" ? settings.welcomeChannelId : settings.goodbyeChannelId;
const template = kind === "welcome" ? settings.welcomeMessage : settings.goodbyeMessage;
if (!channelId || !isConfiguredGuild(member.guild)) return;
const message = safe(template.replace(/\{user\}/gi, member.user.username).replace(/\{server\}/gi, member.guild.name), 500);
if (message) await postCard(channelId, card({title: kind === "welcome" ? "Welcome" : "Goodbye", tone: kind === "welcome" ? 0x57f287 : 0x5865f2, sections: [message]}), `${kind} notice`);
};
const githubUpdatesOn = () => {
loadDashboardConfig();
return Boolean(config.discord.githubRepository && config.discord.githubWebhookSecret && config.discord.updatesChannelId);
};
// Safe to expose to the owner dashboard: it deliberately contains state and
// channel ids only, never the bot token or GitHub webhook secret.
const dashboardStatus = () => {
loadDashboardConfig();
return {
botTokenConfigured: Boolean(config.discord.botToken),
guildId: config.discord.guildId || "",
connected: Boolean(client && client.isReady()),
commands: ["/burrow status", "/burrow player", "/burrow reports", "/burrow staff", "/burrow announce", "/moderate warn", "/moderate silence", "/moderate unsilence", "/moderate kick", "/moderate ban", "/moderate unban", "/discord timeout", "/discord untimeout", "/discord kick", "/discord ban", "/discord unban", "/discord purge"],
channels: CHANNELS.map(([key, name]) => ({key, name, id: config.discord[key] || "", configured: Boolean(config.discord[key])})),
github: {
repository: config.discord.githubRepository || "",
webhookSecretConfigured: Boolean(config.discord.githubWebhookSecret),
updatesEnabled: githubUpdatesOn(),
endpoint: "/discord/github",
},
statusCard: statusSettings(),
security: {...securitySettings(), monitoring: securityGatewayOn},
community: communitySettings(),
modules: [
{name: "Burrow staff tools", detail: "Player lookup, reports, staff list, in-game announcements, and game moderation", enabled: Boolean(config.discord.botToken && config.discord.guildId)},
{name: "Discord moderation", detail: "Timeout, kick, ban, unban, and purge; gated by linked Burrow staff permissions", enabled: Boolean(config.discord.botToken && config.discord.guildId)},
{name: "Activity and audit logs", detail: "In-game activity, reports, moderation, and bot command audit streams", enabled: CHANNELS.some(([key]) => key !== "updatesChannelId" && Boolean(config.discord[key]))},
{name: "GitHub updates", detail: "Signed commit cards, with client changes marked as game updates", enabled: githubUpdatesOn()},
{name: "AutoMod and anti-raid", detail: "Blocked words, invite blocking, anti-spam, and join-rate alerts", enabled: securitySettings().enabled},
{name: "Tickets and member notices", detail: "Private support tickets plus configurable welcome and goodbye cards", enabled: Boolean(communitySettings().ticketCategoryId && communitySettings().ticketStaffRoleId)},
],
};
};
const githubBody = req => new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
req.on("data", chunk => {
size += chunk.length;
if (size > MAX_GITHUB_WEBHOOK_BYTES) {
req.destroy();
reject(new Error("too_large"));
return;
}
chunks.push(chunk);
});
req.on("end", () => resolve(Buffer.concat(chunks)));
req.on("error", reject);
});
const githubSignatureMatches = (body, signature) => {
if (!/^sha256=[0-9a-f]{64}$/i.test(String(signature || ""))) return false;
const expected = `sha256=${crypto.createHmac("sha256", config.discord.githubWebhookSecret).update(body).digest("hex")}`;
return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(String(signature)));
};
const changedFiles = commit => [commit.added, commit.modified, commit.removed].flat().filter(file => typeof file === "string");
const gameChange = payload => (payload.commits || []).some(commit => changedFiles(commit)
.some(file => /^(swf\/|swf-src\/|client-updates\/|public\/(?:badges|music|fonts)\/)/.test(file)));
const githubUpdateCard = payload => {
const commits = Array.isArray(payload.commits) ? payload.commits.slice(-5) : [];
const isGameUpdate = gameChange(payload);
const compare = config.githubUrl ? `${config.githubUrl.replace(/\/$/, "")}/compare/${safe(payload.before, 40)}...${safe(payload.after, 40)}` : "";
const branch = String(payload.ref || "").replace(/^refs\/heads\//, "") || "default branch";
return card({
title: isGameUpdate ? "Game update" : "Server update",
tone: isGameUpdate ? 0x57f287 : 0x5865f2,
sections: [
`**${safe(config.discord.githubRepository, 100)}** · ${safe(branch, 100)}\n${commits.length} new commit${commits.length === 1 ? "" : "s"}`,
commits.length ? commits.map(commit => `\`${safe(String(commit.id || "").slice(0, 7), 7)}\` ${safe(String(commit.message || "").split("\n")[0], 180)} — ${safe(commit.author && commit.author.name, 80)}`).join("\n") : "No commit details were supplied.",
],
components: compare ? [{type: 1, components: [{type: 2, style: 5, label: "View on GitHub", url: compare}]}] : [],
});
};
// GitHub calls this public endpoint. It is intentionally signature-first:
// an untrusted request never reaches Discord or becomes a log entry.
const handleGithubWebhook = async (req, res) => {
const answer = status => { res.writeHead(status, {"Content-Length": 0}); res.end(); };
if (!githubUpdatesOn()) {
answer(404);
return;
}
if (req.method !== "POST") {
answer(405);
return;
}
let body;
try {
body = await githubBody(req);
}
catch {
answer(413);
return;
}
if (!githubSignatureMatches(body, req.headers["x-hub-signature-256"])) {
answer(401);
return;
}
if (req.headers["x-github-event"] === "ping") {
answer(204);
return;
}
if (req.headers["x-github-event"] !== "push") {
answer(204);
return;
}
let payload;
try {
payload = JSON.parse(body.toString("utf8"));
}
catch {
answer(400);
return;
}
if (payload.repository?.full_name !== config.discord.githubRepository || payload.deleted === true) {
answer(204);
return;
}
const channel = await channelFor(config.discord.updatesChannelId);
if (!channel) {
answer(503); // GitHub retries after the bot finishes reconnecting.
return;
}
const posted = await channel.send(githubUpdateCard(payload)).then(() => true).catch(err => {
console.log(`[discord-bot] GitHub update post failed: ${logText(err.message)}`);
return false;
});
answer(posted ? 204 : 503);
};
const syncCommands = async () => {
if (!client || !client.isReady()) return {error: "The Discord bot is not connected."};
const guild = await client.guilds.fetch(config.discord.guildId).catch(() => null);
if (!guild) return {error: "The configured Discord server could not be found."};
const synced = await guild.commands.set(commandDefinitions()).then(() => true).catch(err => {
console.log(`[discord-bot] command registration failed: ${logText(err.message)}`);
return false;
});
return synced ? {ok: "Discord slash commands are synchronized."} : {error: "Discord could not synchronize slash commands."};
};
const startup = () => {
loadDashboardConfig();
const security = securitySettings();
const community = communitySettings();
if (!config.discord.botToken || !config.discord.guildId) {
return false;
}
if (client) return true;
if (!loadDiscordJs()) return false;
securityGatewayOn = security.enabled;
const memberEvents = securityGatewayOn || Boolean(community.welcomeChannelId || community.goodbyeChannelId);
client = new Client({intents: securityGatewayOn
? [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers]
: memberEvents ? [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers] : [GatewayIntentBits.Guilds]});
client.once("ready", async () => {
console.log(`[discord-bot] signed in as ${logText(client.user.tag)}`);
const synced = await syncCommands();
console.log(`[discord-bot] ${synced.ok || synced.error}`);
await publishStatus();
});
client.on("interactionCreate", async interaction => {
if (interaction.user.bot) return;
if (interaction.isButton()) {
await notifyBot(interaction, `button ${interaction.customId}`).catch(() => {});
await handleButton(interaction);
return;
}
if (!interaction.isChatInputCommand() || !inConfiguredGuild(interaction)) return;
await notifyBot(interaction, `/${interaction.commandName} ${interaction.options.getSubcommand(false) || ""}`.trim()).catch(() => {});
await interaction.deferReply({flags: EPHEMERAL}).catch(() => {});
if (!interaction.deferred) return;
try {
if (interaction.commandName === "burrow") await handleBurrow(interaction);
else if (interaction.commandName === "moderate") await handleModerate(interaction);
else if (interaction.commandName === "discord") await handleDiscordModeration(interaction);
else if (interaction.commandName === "ticket") await handleTicket(interaction);
}
catch (err) {
console.error(`[discord-bot] interaction failed: ${err.stack || err.message}`);
await interaction.editReply(failure("The command could not be completed.")).catch(() => {});
}
});
client.on("error", err => console.error(`[discord-bot] client error: ${err.message}`));
if (securityGatewayOn) {
client.on("messageCreate", message => { inspectDiscordMessage(message).catch(err => console.error(`[discord-bot] AutoMod failed: ${err.message}`)); });
client.on("guildMemberAdd", member => { inspectDiscordJoin(member).catch(err => console.error(`[discord-bot] anti-raid check failed: ${err.message}`)); });
}
if (memberEvents) {
client.on("guildMemberAdd", member => { communityNotice(member, "welcome").catch(err => console.error(`[discord-bot] welcome notice failed: ${err.message}`)); });
client.on("guildMemberRemove", member => { communityNotice(member, "goodbye").catch(err => console.error(`[discord-bot] goodbye notice failed: ${err.message}`)); });
}
unsubscribeReports = reports.onFile(notifyReport);
unsubscribeGameActivity = world.onGameActivity(notifyGameActivity);
unsubscribeModeration = modlog.onRecord(notifyModeration);
statusTimer = setInterval(() => { publishStatus().catch(err => console.error(`[discord-bot] status failed: ${err.message}`)); }, STATUS_EVERY_MS);
statusTimer.unref();
client.login(config.discord.botToken).catch(err => console.error(`[discord-bot] login failed: ${err.message}`));
return true;
};
const shutdown = () => {
if (statusTimer) clearInterval(statusTimer);
statusTimer = null;
if (unsubscribeReports) unsubscribeReports();
unsubscribeReports = null;
if (unsubscribeGameActivity) unsubscribeGameActivity();
unsubscribeGameActivity = null;
if (unsubscribeModeration) unsubscribeModeration();
unsubscribeModeration = null;
if (client) client.destroy();
client = null;
securityGatewayOn = false;
recentMessages.clear();
recentJoins.length = 0;
};
const control = async action => {
if (action === "stop") {
if (!client) return {error: "The Discord bot is already stopped."};
shutdown();
return {ok: "Discord bot stopped. Game and panel services remain online."};
}
if (action === "start") {
return startup() ? {ok: "Discord bot is starting."} : {error: "Set AJ_DISCORD_BOT_TOKEN and AJ_DISCORD_GUILD_ID, and install discord.js (npm ci), before starting the bot."};
}
if (action === "reconnect") {
shutdown();
return startup() ? {ok: "Discord bot is reconnecting."} : {error: "Set AJ_DISCORD_BOT_TOKEN and AJ_DISCORD_GUILD_ID, and install discord.js (npm ci), before reconnecting the bot."};
}
if (action === "sync") return syncCommands();
return {error: "Unknown Discord bot control."};
};
module.exports = {startup, shutdown, control, card, COMPONENTS_V2, dashboardStatus, updateDashboardConfig, updateSecuritySettings, updateCommunitySettings, setStatusSettings, publishStatus, handleGithubWebhook};
+1 -1
View File
@@ -1,4 +1,4 @@
{
"cards": [1,2,3,4,5,7,8,86,118,119,124,128,152,154,155,201,283,284,329,346,355,356,361,380,382,384,385,387,388,389,390,391,1188,1206,1211,1222,1228,1242,1249,1250,1251,1354,1426,1520,1627,1768,1933,2235,2649,2697,2700,2702,2703,2704,2705,2706,2707,2708,2709,2711,2712,2713,2714,2715,2716,2717,2720,2723,2762,2763,2805,2806,2807,2808,2809,2810,2811,2812,2813,2814,2815,2816,2817,2818,2819,2820,2821,2822,2823,2824,2825,2826,2827,2828,3749,4393,4410,4411,4434,4435,4451,4452,4453,4454,4455,4457,4460,4461,4462,4464,4465,4466,4467,4468,4469,4470,4477,4478,4479,4538,4539,4540,4541,4542,4543,4544,4545,4546,4547,4548,4549,4777,4778,4779,4780,4855,4856,4946,5023,5024,5026,5066,5067,5068,5069,5070,5071,5073,5074,5075,5076,5077,5078,5079,5080,5081,5082,5083,5084,5085,5086,5087,5088,5089,5090,5091,5092,5093,5094,5095,5099,5100,5738,5980,5981,6130,6138,9013,9014,9015,9016,9017,9167,9170,9172,9174,9175,9326,9327,9328,9329,9330,9331,9332],
"stamps": [10,11,12,13,15,16,17,18,19,20,21,22,23]
"stamps": [13,11,2889,2896,1602,2886,1604,12,2877,2885,1603,2894,10,2899,2891,2876,376,2878,2879,2880,2881,2882,2884,2888,2898,2887,2890,377,2892,2893,2895,2900,378,2901,2902]
}
+51 -13
View File
@@ -17,9 +17,12 @@ const {CURRENCIES, hasRoom, addClothing, sendClothingAdded, sendClothingRemoved}
// ECardXtCommManager): a card, a stamp, a short message and perhaps a gift,
// kept in the receiver's inbox (account.ecards) until they delete it.
//
// which cards and stamps exist was a list on the official servers. the ones
// which cards and stamps exist was a list on the official servers. the cards
// offered here were found by looking through the CDN's media files for card
// artwork (tools/find-art.py found what is in lib/ecard-art.json).
// artwork (tools/find-art.py found what is in lib/ecard-art.json); the
// stamps are the official list itself, as a recording of the official game
// has it (lib/official-lists.json, list 44): the ones guessed before were
// partly not stamps at all, and showed nothing.
// ECard.type: what, if anything, comes with the card
const TYPE_PLAIN = 0;
@@ -51,10 +54,15 @@ const INBOX_FULL = -1;
const NOT_ACCEPTING = -2;
const FAILED = 0;
// who may send to a player (ECardInbox's settings popup).
// who may send to a player, as kept (account.ecardPrivacy).
const FROM_EVERYONE = 0;
const FROM_BUDDIES = 1;
const FROM_NOBODY = 2;
// ECardInbox's settings popup sends the place of the option picked, and its
// artwork has Nobody first and Everyone last: the other way round from the
// above. turned over both ways between the two (buddies is in the middle).
const SETTING_COUNT = 3;
const turnedOver = value => SETTING_COUNT - 1 - value;
const LIST_CARDS = 10;
const LIST_STAMPS = 44;
@@ -69,8 +77,23 @@ const now = () => Math.floor(Date.now() / 1000);
const clean = text => String(text).replace(/[\u0000-\u001f\u007f%]/g, " ").trim().slice(0, MAX_MESSAGE);
module.exports = ({findOnline, blocks}) => {
// a gift the game can show and take: its item still exists (a custom item
// may have been deleted since), or an amount that makes sense. any other
// left the gift windows stuck; it is treated as no gift at all.
const MAX_GIFT_AMOUNT = 10000000;
const giftUsable = gift => {
if (gift.type === TYPE_CLOTHING) {
return Boolean(defpacks.itemDef(gift.def)) && Number.isFinite(Number(gift.color));
}
if (gift.type === TYPE_DEN_ITEM) {
return Boolean(defpacks.denItemDef(gift.def));
}
const amount = Number(gift.def);
return Object.hasOwn(CURRENCY_OF, gift.type) && Number.isInteger(amount) && amount > 0 && amount <= MAX_GIFT_AMOUNT;
};
// A card from the server carrying gems or diamonds: one of the popups.
const isRedemption = card => Boolean(card.hq && card.gift && Object.hasOwn(CURRENCY_OF, card.gift.type));
const isRedemption = card => Boolean(card.hq && card.gift && giftUsable(card.gift) && Object.hasOwn(CURRENCY_OF, card.gift.type));
// who sent a card: by account id, and for cards from before ids were
// kept by the name on them.
@@ -90,9 +113,10 @@ module.exports = ({findOnline, blocks}) => {
const sender = card.hq ? null : senderOf(card);
const senderType = isRedemption(card) ? FROM_REDEMPTION : card.hq ? FROM_HQ : FROM_PLAYER;
const name = card.secret ? "" : senderType === FROM_HQ ? HQ_NAME_STRING : card.hq ? HQ_NAME : card.from;
const gift = card.gift && giftUsable(card.gift) ? card.gift : null;
return [
card.id, name, card.card, card.stamp, card.read ? 1 : 0, card.msg, card.gift ? card.gift.type : TYPE_PLAIN,
card.gift ? giftId(card.gift) : 0, card.gift ? card.gift.color : 0, card.gift ? card.gift.name : 0,
card.id, name, card.card, card.stamp, card.read ? 1 : 0, card.msg, gift ? gift.type : TYPE_PLAIN,
gift ? giftId(gift) : 0, gift ? gift.color : 0, gift ? gift.name : 0,
card.hq || card.secret ? MEMBER : sender ? sender.accountType : 0,
0, // name bar data
0, // secondary type
@@ -102,7 +126,7 @@ module.exports = ({findOnline, blocks}) => {
// patched client (ECardInbox) can show a custom item as itself (its
// own picture and name) and not as the art it was made from. (the
// "|" keeps the game from taking it for an HQ gift's own message.)
card.gift && card.gift.type === TYPE_CLOTHING ? `item|${card.gift.def}` : "",
gift && gift.type === TYPE_CLOTHING ? `item|${gift.def}` : "",
card.secret ? SECRET_VALENTINE : 0,
];
};
@@ -155,7 +179,11 @@ module.exports = ({findOnline, blocks}) => {
}
else {
// for these the card's "gift id" and "gift name" are both the amount.
attached = {type: gift.kind === "gems" ? TYPE_GEMS : TYPE_DIAMONDS, def: gift.amount, color: 0, name: gift.amount};
const amount = Number(gift.amount);
if (!Number.isInteger(amount) || amount < 1 || amount > MAX_GIFT_AMOUNT) {
return "An amount from 1 to 10,000,000";
}
attached = {type: gift.kind === "gems" ? TYPE_GEMS : TYPE_DIAMONDS, def: amount, color: 0, name: amount};
}
// the gift popup takes a message that starts with a number for the id of
// a localization string (StartupPopups.setupGiftPopup).
@@ -218,8 +246,8 @@ module.exports = ({findOnline, blocks}) => {
}
else if (Object.hasOwn(CURRENCY_OF, gift.type)) {
const currency = CURRENCIES[CURRENCY_OF[gift.type]];
account.currency[currency] = (account.currency[currency] || 0) + gift.def;
achievements.currencyChanged(account, currency, gift.def);
account.currency[currency] = (account.currency[currency] || 0) + Number(gift.def);
achievements.currencyChanged(account, currency, Number(gift.def));
// ItemXtCommManager.currencyUpdateResponse: [currencyType, newAmount, reason]
session.sendXt("cu", -1, CURRENCY_OF[gift.type], account.currency[currency], 0);
}
@@ -251,7 +279,8 @@ module.exports = ({findOnline, blocks}) => {
// silenced: no words of their own reach anyone, in a card either.
if (!to || to === account || !art.cards.includes(Number(card)) || !art.stamps.includes(Number(stamp))
|| !accounts.featureOn(account, "jamagrams") || (isSilenced(account) && clean(message || "") !== "")
|| !sendsPerTenMinutes.allow(account.id)) {
// The client also skips its per-recipient cap for moderators.
|| (!account.isModerator && !sendsPerTenMinutes.allow(account.id))) {
reply(FAILED);
return;
}
@@ -324,6 +353,13 @@ module.exports = ({findOnline, blocks}) => {
return;
}
const {gift} = card;
// a gift that cannot be had (above): gone, and the window let go
if (!giftUsable(gift)) {
card.gift = null;
accounts.save(session.account);
session.sendXt("eg", -1, msgId, 1);
return;
}
// no room for it: it stays in the card until there is.
if (accept === "1" && ((gift.type === TYPE_CLOTHING && !hasRoom(session.account, "items"))
|| (gift.type === TYPE_DEN_ITEM && !hasRoom(session.account, "denItems")))) {
@@ -344,7 +380,7 @@ module.exports = ({findOnline, blocks}) => {
// [setting] -> eCardIsolationHandler: [success]
ei(session, roomId, [setting]) {
const value = Number(setting);
const value = turnedOver(Number(setting));
const valid = [FROM_EVERYONE, FROM_BUDDIES, FROM_NOBODY].includes(value);
if (valid) {
session.account.ecardPrivacy = value;
@@ -373,5 +409,7 @@ module.exports = ({findOnline, blocks}) => {
return card ? senderOf(card) : null;
};
return {handlers, list, unread, redemptions, sendFromHq, noteFromHq, secretSender, SECRET_NAME: "Secret Valentine"};
// the setting as the inbox's settings popup shows it (above)
const privacyShown = account => turnedOver(account.ecardPrivacy || FROM_EVERYONE);
return {handlers, list, unread, redemptions, privacyShown, sendFromHq, noteFromHq, secretSender, SECRET_NAME: "Secret Valentine"};
};
+227
View File
@@ -0,0 +1,227 @@
"use strict";
const accounts = require("./accounts.js");
const achievements = require("./achievements.js");
const config = require("../config.js");
const defpacks = require("./defpacks.js");
// the eco den items: producers (special type 6, the Eco Solar Panel and
// Eco Wind Turbine) and consumers (7, the eco lamps and fan), sold for eco
// credits in the Eco Shop (list 778). client side: gui.EcoScorePopup (a
// producer clicked), gui.EcoPointsPopup (a consumer clicked),
// DenItemHolder.updateConsumers. the official server's rules were never
// recorded; these are this server's:
//
// - a den's generation is the eco power of the producers placed in its
// owner's den in use; consumers switched on take theirs from it, in
// inventory order, and one that no longer fits is "offline" (state 2)
// until there is power for it again. its switch stays on.
// - generation turns into credits, config.ecoCreditsPerPointHour a point
// an hour, waiting to be collected ("Get Your Credits") up to the
// meter's full 240. an account's first look (an eco window, or the
// Eco Shop) gets it config.ecoStartCredits, enough for its first producer.
// - the eco score (generation less use) earns the three eco plaques, one
// at a time, through user var 465 (a bit each).
const SPECIAL_PRODUCER = "6";
const SPECIAL_CONSUMER = "7";
const WIND_TURBINE = 4541;
const SOLAR_PANEL = 4540;
const CURRENCY_ECO = 11;
const ECO_SHOP_LIST = 778;
const MAX_WAITING = 240; // EcoScorePopup.updateCreditProgressMeter: the meter is full at 240
const USER_VAR_REWARDS = 465;
const REWARDS = [
{bit: 0, score: 5, def: 4611}, // Wood Eco Plaque
{bit: 1, score: 15, def: 4610}, // Silver Eco Plaque
{bit: 2, score: 30, def: 4609}, // Gold Eco Plaque
];
const HOUR_MS = 3600000;
const OFF = 0;
const ON = 1;
const OFFLINE = 2;
const special = item => {
const def = defpacks.denItemDef(item.def);
return def ? String(def.specialType) : "";
};
const power = item => Number((defpacks.denItemDef(item.def) || {}).ecoPower) || 0;
const placedInUse = account => account.denItems.filter(item => item.spots && item.spots[account.activeDen]);
// the den in use as the eco windows see it: {generation, consumption,
// turbines, panels, consumers: [item], states: Map(inv -> 0 off, 1 on, 2 offline)}
const stateOf = account => {
const placed = placedInUse(account);
const producers = placed.filter(item => special(item) === SPECIAL_PRODUCER);
const consumers = placed.filter(item => special(item) === SPECIAL_CONSUMER).sort((one, other) => one.inv - other.inv);
const generation = producers.reduce((sum, item) => sum + power(item), 0);
let consumption = 0;
const states = new Map();
for (const item of consumers) {
if (!item.ecoOn) {
states.set(item.inv, OFF);
}
else if (consumption + power(item) <= generation) {
consumption += power(item);
states.set(item.inv, ON);
}
else {
states.set(item.inv, OFFLINE);
}
}
return {
generation,
consumption,
turbines: producers.filter(item => item.def === WIND_TURBINE).length,
panels: producers.filter(item => item.def === SOLAR_PANEL).length,
consumers,
states,
};
};
// a den item's eco field in the den's state (DenStateItem's last): 0 for
// all but consumers
const consumerState = (account, item) => (special(item) === SPECIAL_CONSUMER ? stateOf(account).states.get(item.inv) || OFF : OFF);
const perHour = generation => generation * (Number(config.ecoCreditsPerPointHour) || 0);
// brings the waiting credits up to now, at the rate the den has now. the
// caller saves.
const accrue = account => {
const now = Date.now();
if (!account.eco) {
account.eco = {waiting: 0, at: now};
const start = Math.max(0, Math.floor(Number(config.ecoStartCredits) || 0));
account.currency.ecoCredits = (account.currency.ecoCredits || 0) + start;
return;
}
const rate = perHour(stateOf(account).generation);
const hours = Math.max(0, now - account.eco.at) / HOUR_MS;
account.eco.waiting = Math.min(MAX_WAITING, (Number(account.eco.waiting) || 0) + rate * hours);
account.eco.at = now;
};
// seconds until one more whole credit waits, 0 when none will
const secondsToNext = account => {
const rate = perHour(stateOf(account).generation);
if (rate <= 0 || account.eco.waiting >= MAX_WAITING) {
return 0;
}
const short = 1 - (account.eco.waiting % 1);
return Math.max(1, Math.ceil(short / rate * 3600));
};
const nextReward = account => {
const bits = Number(account.userVars[USER_VAR_REWARDS]) || 0;
return REWARDS.find(reward => !(bits & (1 << reward.bit))) || null;
};
module.exports = ({others, ecards}) => {
const sendCredits = session => session.sendXt("cu", -1, CURRENCY_ECO, session.account.currency.ecoCredits || 0, 0);
// the consumers' states to the owner and, when they are in it, everyone
// else in the den: DenXtCommManager.denEcoConsumerResponse [consumption,
// generation, count, (invIdx, state)...].
const sendConsumers = session => {
const {account} = session;
const state = stateOf(account);
const fields = [state.consumption, state.generation, state.consumers.length,
...state.consumers.flatMap(item => [item.inv, state.states.get(item.inv)])];
session.sendXt("dEc", -1, ...fields);
if (session.room && session.room.denOwner === account) {
for (const other of others(session)) {
other.sendXt("dEc", -1, ...fields);
}
}
};
const handlers = {
// requestDenEcoCreditRefresh -> EcoStateResponse: [turbines, panels,
// consumers, generation, consumption, score required, next reward bit,
// credits waiting, seconds to the next].
dEf(session) {
const {account} = session;
const firstLook = !account.eco;
accrue(account);
accounts.save(account);
if (firstLook) {
sendCredits(session);
}
const state = stateOf(account);
const reward = nextReward(account);
session.sendXt("dEf", -1, state.turbines, state.panels, state.consumers.length, state.generation, state.consumption,
reward ? reward.score : REWARDS[REWARDS.length - 1].score, reward ? reward.bit : -1,
Math.floor(account.eco.waiting), secondsToNext(account));
},
// requestDenEcoCreditRedeem: the waiting credits collected -> [success,
// seconds to the next].
dEr(session) {
const {account} = session;
accrue(account);
const credits = Math.floor(account.eco.waiting);
if (credits < 1) {
accounts.save(account);
session.sendXt("dEr", -1, 0, secondsToNext(account));
return;
}
account.eco.waiting -= credits;
account.currency.ecoCredits = (account.currency.ecoCredits || 0) + credits;
achievements.currencyChanged(account, "ecoCredits", credits);
accounts.save(account);
sendCredits(session);
session.sendXt("dEr", -1, 1, secondsToNext(account));
},
// requestDenEcoConsumer: [invIdx, "1" on | "0" off]
dEc(session, roomId, [invIdx, on]) {
const {account} = session;
const item = account.denItems.find(candidate => candidate.inv === Number(invIdx));
if (item && special(item) === SPECIAL_CONSUMER) {
accrue(account);
item.ecoOn = on === "1";
accounts.save(account);
}
sendConsumers(session);
},
};
// user var 465, set by the eco score window's gift: the value is the bit
// of the reward asked for. given when it is the next one and the score is
// there; the plaque comes as a gift from HQ. true when the var was this.
const userVar = (session, id, bit) => {
if (Number(id) !== USER_VAR_REWARDS) {
return false;
}
const {account} = session;
const reward = nextReward(account);
const state = stateOf(account);
if (reward && reward.bit === Number(bit) && state.generation - state.consumption >= reward.score
&& !ecards.sendFromHq(account, "Eco Reward", {kind: "den", id: reward.def})) {
account.userVars[USER_VAR_REWARDS] = (Number(account.userVars[USER_VAR_REWARDS]) || 0) | (1 << reward.bit);
accounts.save(account);
}
if (account.userVars[USER_VAR_REWARDS] === undefined) {
account.userVars[USER_VAR_REWARDS] = 0;
}
achievements.sendVar(session, USER_VAR_REWARDS);
return true;
};
// the Eco Shop opened: an account that never had eco credits is given
// its first, to buy its first producer with.
const shopOpened = session => {
if (!session.account.eco) {
accrue(session.account);
accounts.save(session.account);
sendCredits(session);
}
};
return {handlers, userVar, shopOpened, SHOP_LIST: ECO_SHOP_LIST};
};
module.exports.accrue = accrue;
module.exports.consumerState = consumerState;
module.exports.SPECIAL_TYPES = [SPECIAL_PRODUCER, SPECIAL_CONSUMER];
+101 -70
View File
@@ -1,84 +1,118 @@
[
{"id": 4, "swf": "Pachinko", "title": "Gem Ball", "type": 1, "vars": [16, 17, 0], "icon": 4295},
{"id": 5, "swf": "MiniGame_Memory", "title": "Double Up", "type": 1, "vars": [6, 7, 83], "icon": 4291},
{"id": 6, "swf": "MoatMadness", "title": "Overflow", "type": 1, "vars": [8, 9, 80], "icon": 4300},
{"id": 10, "swf": "ParachuteGlider", "title": "Wind Rider", "type": 1, "vars": [12, 13, 79], "start": "seed", "icon": 4311},
{"id": 11, "swf": "Trivia", "title": "Temple of Trivia", "type": 1, "vars": [10, 11, 0], "ready": false, "icon": 4309},
{"id": 12, "swf": "RiverRace", "title": "River Race", "type": 1, "vars": [22, 23, 0], "start": "seed"},
{"id": 13, "swf": "PhantomFighter", "title": "Phantom Fighter", "type": 1, "vars": [14, 15, 84], "icon": 4312},
{"id": 14, "swf": "SpiderShooter", "title": "Spider Zapper", "type": 1, "vars": [18, 19, 82], "start": "seed", "icon": 4305},
{"id": 1, "swf": "PVP_TicTacToe", "title": "Tic Tac Toe", "type": 0, "vars": [63,0,0], "icon": 5063, "card": 5055, "buddy": true},
{"id": 4, "swf": "Pachinko", "title": "Gem Ball", "type": 1, "vars": [16,17,0], "icon": 4295, "card": 58},
{"id": 5, "swf": "MiniGame_Memory", "title": "Double Up", "type": 1, "vars": [6,7,0], "icon": 4291, "card": 61},
{"id": 6, "swf": "MoatMadness", "title": "Overflow", "type": 1, "vars": [8,9,9], "icon": 4300, "card": 59},
{"id": 10, "swf": "ParachuteGlider", "title": "Wind Rider", "type": 1, "vars": [12,13,0], "start": "seedAndCrosshairs", "icon": 4311, "card": 65},
{"id": 11, "swf": "Trivia", "title": "Temple of Trivia", "type": 1, "vars": [10,11,0], "icon": 4309, "card": 64, "ready": false},
{"id": 12, "swf": "RiverRace", "title": "River Race", "type": 1, "vars": [22,23,0], "start": "seed", "card": 62},
{"id": 13, "swf": "PhantomFighter", "title": "Phantom Fighter", "type": 1, "vars": [14,15,0], "icon": 4312, "card": 60},
{"id": 14, "swf": "SpiderShooter", "title": "Spider Zapper", "type": 1, "vars": [18,19,0], "start": "seedAndCrosshairs", "icon": 4305, "card": 63},
{"id": 15, "swf": "MicroPopcorn", "title": "Popcorn Machine", "type": 0},
{"id": 16, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 17, "swf": "MicroSmoothie", "title": "Smoothie Machine", "type": 0},
{"id": 19, "swf": "WindRider", "title": "Sky High", "type": 1, "vars": [26, 27, 0], "icon": 4304},
{"id": 20, "swf": "Twister", "title": "Twister", "type": 1, "vars": [24, 25, 81], "icon": 4310},
{"id": 22, "swf": "DistanceChallenge", "title": "Long Shot", "type": 1, "vars": [20, 21, 0], "icon": 4298},
{"id": 23, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1},
{"id": 26, "swf": "ArtStudioPottery", "title": "Pottery", "type": 1},
{"id": 27, "swf": "MicroPhantom", "title": "Phantom Vortex", "type": 0},
{"id": 28, "swf": "TowerDefense", "title": "Pest Control", "type": 1, "vars": [130, 131, 132], "icon": 4301},
{"id": 30, "swf": "GemBreaker", "title": "Gem Breaker", "type": 1, "vars": [91, 93, 92], "start": "seedAndPlayers", "icon": 4313},
{"id": 34, "swf": "MicroMiraSays", "title": "Mira Says", "type": 1, "vars": [77, 76, 0], "icon": 4299},
{"id": 35, "swf": "FortSmasher", "title": "Fruit Slinger", "type": 1, "vars": [143, 144, 145], "ready": false, "icon": 4294},
{"id": 36, "swf": "MicroHotCocoa", "title": "Hot Cocoa Machine", "type": 0},
{"id": 37, "swf": "SuperSort", "title": "Super Sort", "type": 1, "vars": [31, 32, 37], "icon": 4307},
{"id": 39, "swf": "PillBugs", "title": "Pill Bugs", "type": 1, "vars": [277, 278, 279], "icon": 4303},
{"id": 40, "swf": "BradyExpeditions", "title": "Brady Expeditions", "type": 1},
{"id": 41, "swf": "PhantomsTreasure", "title": "Phantom's Treasure", "type": 1, "vars": [281, 283, 282], "icon": 4302},
{"id": 42, "swf": "FeedingFrenzy", "title": "Eat 'Em Up", "type": 1, "vars": [284, 285, 0], "icon": 4292},
{"id": 43, "swf": "MicroPetWash", "title": "Pet Wash", "type": 0},
{"id": 48, "swf": "FashionShow", "title": "Best Dressed", "type": 1, "vars": [292, 293, 294], "ready": false, "icon": 4288},
{"id": 51, "swf": "ArtStudioPainting", "title": "Painting", "type": 1},
{"id": 52, "swf": "MicroPetSalon", "title": "Pet Stop", "type": 0},
{"id": 55, "swf": "MicroGameInvasion", "title": "Phantom Invasion", "type": 0},
{"id": 18, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 19, "swf": "WindRider", "title": "Sky High", "type": 1, "vars": [26,27,0], "icon": 4304, "card": 78},
{"id": 20, "swf": "Twister", "title": "Twister", "type": 1, "vars": [24,25,0], "icon": 4310, "card": 79},
{"id": 21, "swf": "FrogFlyer", "title": "Long Shot", "type": 1, "ready": false},
{"id": 22, "swf": "DistanceChallenge", "title": "Long Shot", "type": 1, "vars": [20,21,21], "icon": 4298, "card": 80},
{"id": 23, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1, "card": 58},
{"id": 24, "swf": "ArtStudioColor", "title": "Coloring", "type": 1, "card": 58, "ready": false},
{"id": 25, "swf": "ParachuteGliderTest", "title": "Wind Rider", "type": 1, "card": 65, "ready": false},
{"id": 26, "swf": "ArtStudioPottery", "title": "Pottery", "type": 1, "card": 58},
{"id": 27, "swf": "MicroPhantom", "title": "Phantom Vortex", "type": 0, "card": 69},
{"id": 28, "swf": "TowerDefense", "title": "Pest Control", "type": 1, "vars": [130,131,132], "icon": 4301, "card": 456},
{"id": 29, "swf": "GemBreaker", "title": "Gem Breaker", "type": 1, "start": "seedAndPlayers", "card": 58},
{"id": 30, "swf": "GemBreaker", "title": "Gem Breaker", "type": 1, "vars": [91,32,0], "start": "seedAndPlayers", "icon": 4313, "card": 354},
{"id": 31, "swf": "PVP_ConnectFour", "title": "Four Gems", "type": 0, "icon": 5057, "card": 5049, "buddy": true},
{"id": 32, "swf": "PVP_RockPaperScissor", "title": "Rock Paper Scissors", "type": 0, "icon": 5060, "card": 5052, "buddy": true},
{"id": 34, "swf": "MicroMiraSays", "title": "Mira Says", "type": 1, "vars": [77,76,0], "icon": 4299, "card": 288},
{"id": 35, "swf": "FortSmasher", "title": "Fruit Slinger", "type": 1, "vars": [74,75,0], "icon": 4294, "card": 541, "ready": false},
{"id": 36, "swf": "MicroHotCocoa", "title": "Hot Cocoa Machine", "type": 0, "vars": [95,0,0]},
{"id": 37, "swf": "SuperSort", "title": "Super Sort", "type": 1, "vars": [31,32,37], "icon": 4307, "card": 353},
{"id": 38, "swf": "PVP_ShellGame", "title": "Shell Game", "type": 0, "icon": 5062, "card": 5054, "buddy": true},
{"id": 39, "swf": "PillBugs", "title": "Pill Bugs", "type": 1, "vars": [277,278,279], "icon": 4303, "card": 1098},
{"id": 40, "swf": "BradyChemistrySet", "title": "Brady's Lab", "type": 0, "vars": [115,0,0]},
{"id": 41, "swf": "PhantomsTreasure", "title": "Phantom's Treasure", "type": 1, "vars": [281,283,282], "icon": 4302, "card": 1140},
{"id": 42, "swf": "FeedingFrenzy", "title": "Eat 'Em Up", "type": 1, "vars": [284,0,0], "icon": 4292, "card": 1170},
{"id": 43, "swf": "MicroPetWash", "title": "Pet Wash", "type": 0, "vars": [51,0,0]},
{"id": 45, "swf": "PVP_Marbles", "title": "Marbles", "type": 0, "icon": 5058, "card": 5050, "buddy": true},
{"id": 46, "swf": "OffTheHook", "title": "Off the Hook", "type": 1, "card": 79, "ready": false},
{"id": 47, "swf": "Pinball", "title": "Double Up", "type": 1, "card": 61, "ready": false},
{"id": 48, "swf": "FashionShow", "title": "Best Dressed", "type": 1, "vars": [292,293,294], "icon": 4288, "card": 1205, "ready": false},
{"id": 49, "swf": "Geography", "title": "Geography", "type": 1, "card": 79, "ready": false},
{"id": 51, "swf": "ArtStudioPainting", "title": "Painting", "type": 1, "vars": [78,0,0], "card": 4849},
{"id": 52, "swf": "MicroPetSalon", "title": "Pet Stop", "type": 0, "vars": [280,0,0], "card": 1205},
{"id": 53, "swf": "PVP_Scooped", "title": "Scooped", "type": 0, "icon": 5061, "card": 5053, "buddy": true},
{"id": 54, "swf": "Glide", "title": "Glide", "type": 1, "card": 79, "ready": false},
{"id": 55, "swf": "MicroGameInvasion", "title": "Phantom Invasion", "type": 0, "card": 1205},
{"id": 56, "swf": "ActivityGeography", "title": "Eat 'Em Up", "type": 1, "card": 1205, "ready": false},
{"id": 57, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 58, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 59, "swf": "MicroCrane", "title": "The Claw", "type": 0, "icon": 4290},
{"id": 60, "swf": "TouchPool", "title": "Touch Pool", "type": 1, "vars": [310, 308, 309], "icon": 5229},
{"id": 61, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 62, "swf": "HorseRace", "title": "Jamaa Derby", "type": 1, "vars": [327, 328, 330], "ready": false, "icon": 4297},
{"id": 63, "swf": "MicroPuppy", "title": "Disc Toss", "type": 0, "vars": [313, 314, 315], "pet": 4},
{"id": 64, "swf": "MicroDucky", "title": "Ducky Dash", "type": 0, "vars": [316, 317, 318], "pet": 3},
{"id": 65, "swf": "MicroSnake", "title": "Sssssnake", "type": 0, "vars": [321, 322, 323], "pet": 11},
{"id": 66, "swf": "FashionShow", "title": "Best Dressed", "type": 1, "vars": [292, 293, 294], "ready": false, "icon": 4289},
{"id": 68, "swf": "Skeeball", "title": "Phantom Ball", "type": 1, "tickets": 10},
{"id": 69, "swf": "WhackPhantom", "title": "Whack-A-Phantom", "type": 1, "tickets": 10},
{"id": 70, "swf": "CandyCatcher", "title": "Candy Catch", "type": 1, "tickets": 10},
{"id": 60, "swf": "TouchPool", "title": "Touch Pool", "type": 1, "vars": [310,308,309], "icon": 5229, "card": 5228},
{"id": 61, "swf": "MicroCrane", "title": "The Claw", "type": 0, "card": 65},
{"id": 62, "swf": "HorseRace", "title": "Jamaa Derby", "type": 1, "vars": [327,328,330], "icon": 4297, "card": 1510, "ready": false},
{"id": 63, "swf": "MicroPuppy", "title": "Disc Toss", "type": 0, "vars": [313,314,315], "pet": 4},
{"id": 64, "swf": "MicroDucky", "title": "Ducky Dash", "type": 0, "vars": [316,317,318], "pet": 3},
{"id": 65, "swf": "MicroSnake", "title": "Sssssnake", "type": 0, "vars": [321,322,323], "pet": 11},
{"id": 66, "swf": "FashionShow", "title": "Best Dressed", "type": 1, "vars": [292,293,294], "icon": 4289, "card": 1482, "ready": false},
{"id": 67, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 68, "swf": "Skeeball", "title": "Phantom Ball", "type": 0, "tickets": 10},
{"id": 69, "swf": "WhackPhantom", "title": "Whack-A-Phantom", "type": 0, "vars": [78,0,0], "tickets": 10, "card": 300},
{"id": 70, "swf": "CandyCatcher", "title": "Candy Catch", "type": 0, "tickets": 10, "card": 300},
{"id": 71, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 72, "swf": "MicroGameInvasion", "title": "Phantom Invasion", "type": 0},
{"id": 73, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 1},
{"id": 74, "swf": "CottonCandy", "title": "Cotton Candy Machine", "type": 0},
{"id": 75, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 76, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1},
{"id": 77, "swf": "FallingPhantoms", "title": "Falling Phantoms", "type": 1, "vars": [344, 345, 346], "ready": false, "icon": 4293},
{"id": 78, "swf": "DolphinRace", "title": "Splash and Dash", "type": 1, "vars": [357, 358, 360], "ready": false, "icon": 4306},
{"id": 80, "swf": "ShootingGallery", "title": "Carnival Darts", "type": 1, "tickets": 100},
{"id": 81, "swf": "MicroPetSalon", "title": "Pet Stop", "type": 0},
{"id": 82, "swf": "FastFoodies", "title": "Fast Foodies", "type": 1, "vars": [445, 444, 446], "icon": 5727},
{"id": 83, "swf": "HedgeHog", "title": "Hedge Hog", "type": 1, "vars": [349, 350, 351], "icon": 4296},
{"id": 72, "swf": "MicroGameInvasion", "title": "Phantom Invasion", "type": 0, "card": 259},
{"id": 73, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 1, "vars": [78,0,0], "card": 1205},
{"id": 74, "swf": "CottonCandy", "title": "Cotton Candy Machine", "type": 0, "vars": [78,0,0]},
{"id": 75, "swf": "MicroCrane", "title": "The Claw", "type": 0, "card": 300},
{"id": 76, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 77, "swf": "FallingPhantoms", "title": "Falling Phantoms", "type": 1, "vars": [344,345,346], "icon": 4293, "card": 1622, "ready": false},
{"id": 78, "swf": "DolphinRace", "title": "Splash and Dash", "type": 1, "vars": [357,358,360], "icon": 4306, "card": 1804, "ready": false},
{"id": 80, "swf": "ShootingGallery", "title": "Carnival Darts", "type": 0, "tickets": 100},
{"id": 81, "swf": "MicroPetSalon", "title": "Pet Stop", "type": 0, "vars": [57,0,0], "card": 259},
{"id": 82, "swf": "FastFoodies", "title": "Fast Foodies", "type": 1, "vars": [445,444,446], "icon": 5727},
{"id": 83, "swf": "HedgeHog", "title": "Hedge Hog", "type": 1, "vars": [349,350,351], "icon": 4296, "card": 1713},
{"id": 85, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 86, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1},
{"id": 87, "swf": "BradyChemistrySet", "title": "Brady's Lab", "type": 0},
{"id": 86, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 87, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 88, "swf": "SafetyQuiz", "title": "Safety Quiz", "type": 0},
{"id": 94, "swf": "EagleFlap", "title": "Swoopy Eagle", "type": 1, "vars": [378, 377, 0], "icon": 4308},
{"id": 96, "swf": "DunkAPhantom", "title": "Dunk-A-Phantom", "type": 1, "tickets": 10},
{"id": 97, "swf": "SpotOn", "title": "Spot On", "type": 1, "vars": [386, 387, 388], "icon": 4321},
{"id": 89, "swf": "ArtStudioPrint", "title": "Coloring", "type": 0},
{"id": 90, "swf": "BradyExpeditions", "title": "Brady Expeditions", "type": 1},
{"id": 91, "swf": "MicroSmoothie", "title": "Smoothie Machine", "type": 0},
{"id": 92, "swf": "ParachuteGlider2", "title": "Wind Rider", "type": 1, "card": 65, "ready": false},
{"id": 93, "swf": "QuestParachuteGlider", "title": "Wind Rider", "type": 1, "vars": [12,13,0], "card": 65, "ready": false},
{"id": 94, "swf": "EagleFlap", "title": "Swoopy Eagle", "type": 1, "vars": [378,377,0], "icon": 4308, "card": 2647},
{"id": 95, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 96, "swf": "DunkAPhantom", "title": "Dunk-A-Phantom", "type": 0, "tickets": 10, "card": 300},
{"id": 97, "swf": "SpotOn", "title": "Spot On", "type": 1, "vars": [386,387,388], "icon": 4321, "card": 3561},
{"id": 98, "swf": "MicroCrane", "title": "The Claw", "type": 0, "vars": [5,0,0]},
{"id": 99, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 100, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 102, "swf": "TrueFalse", "title": "Best Guess", "type": 1, "vars": [403, 405, 0], "ready": false},
{"id": 101, "swf": "PVP_Memory", "title": "Pairs", "type": 0, "icon": 5059, "card": 5051, "buddy": true},
{"id": 102, "swf": "TrueFalse", "title": "Best Guess", "type": 1, "vars": [403,0,0], "card": 3748, "ready": false},
{"id": 103, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 104, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 105, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 106, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 104, "swf": "MicroCrane", "title": "The Claw", "type": 0, "card": 300},
{"id": 105, "swf": "MicroCrane", "title": "The Claw", "type": 0, "card": 61},
{"id": 106, "swf": "MicroCrane", "title": "The Claw", "type": 0, "card": 61},
{"id": 107, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 108, "swf": "PVP_Bowling", "title": "Bowling", "type": 0, "icon": 5056, "card": 5048, "buddy": true},
{"id": 109, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 110, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 111, "swf": "MicroGoldPanning", "title": "Long Shot", "type": 0, "vars": [415,0,0], "ready": false},
{"id": 112, "swf": "MicroOatHarvest", "title": "Slingshot", "type": 0, "vars": [415,0,0], "ready": false},
{"id": 113, "swf": "MicroWoodGather", "title": "Slingshot", "type": 0, "vars": [415,0,0], "ready": false},
{"id": 114, "swf": "MicroStoneMining", "title": "Slingshot", "type": 0, "vars": [415,0,0], "ready": false},
{"id": 115, "swf": "MicroBambooHarvest", "title": "Slingshot", "type": 0, "vars": [415,0,0], "ready": false},
{"id": 116, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 117, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 118, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 119, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 120, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 121, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 122, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 123, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 124, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 125, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 126, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 127, "swf": "MicroCrane", "title": "The Claw", "type": 0},
@@ -89,9 +123,11 @@
{"id": 132, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 133, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 134, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 136, "swf": "ArtStudioPrint", "title": "Coloring", "type": 1},
{"id": 138, "swf": "FastFoodies", "title": "Fast Foodies", "type": 1, "vars": [445, 444, 446]},
{"id": 139, "swf": "ArtStudioGridDrawing", "title": "Pixel Painting", "type": 1},
{"id": 135, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 136, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 137, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 0},
{"id": 138, "swf": "FastFoodies", "title": "Fast Foodies", "type": 1, "vars": [445,444,446], "icon": 5727, "card": 5723},
{"id": 139, "swf": "ArtStudioGridDrawing", "title": "Pixel Painting", "type": 1, "card": 5958},
{"id": 140, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 141, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 142, "swf": "MicroCrane", "title": "The Claw", "type": 0},
@@ -103,16 +139,11 @@
{"id": 148, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 149, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 150, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 151, "swf": "ArtStudioGridDrawing", "title": "Pixel Painting", "type": 1, "vars": [78,0,0], "card": 5958},
{"id": 152, "swf": "ArtStudioPrint", "title": "Coloring", "type": 0},
{"id": 153, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 154, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 155, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 156, "swf": "MicroCrane", "title": "The Claw", "type": 0},
{"id": 89, "swf": "PVP_TicTacToe", "title": "Tic Tac Toe", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5063},
{"id": 90, "swf": "PVP_ConnectFour", "title": "Four Gems", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5057},
{"id": 91, "swf": "PVP_RockPaperScissor", "title": "Rock Paper Scissors", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5060},
{"id": 92, "swf": "PVP_ShellGame", "title": "Shell Game", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5062},
{"id": 93, "swf": "PVP_Memory", "title": "Pairs", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5059},
{"id": 95, "swf": "PVP_Scooped", "title": "Scooped", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5061},
{"id": 98, "swf": "PVP_Bowling", "title": "Bowling", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5056},
{"id": 101, "swf": "PVP_Marbles", "title": "Marbles", "type": 0, "vars": [86, 87, 0], "buddy": true, "card": 5058}
{"id": 158, "swf": "ArtPrintPlayPortrait", "title": "Painting", "type": 1, "vars": [78,0,0], "card": 1205}
]
+144 -8
View File
@@ -22,9 +22,13 @@ const defpacks = require("./defpacks.js");
const limits = require("./limits.js");
const manage = require("./manage.js");
const modpanel = require("./modpanel.js");
const discordBot = require("./discordbot.js");
const badges = require("./badges.js");
const extraMusic = require("./extramusic.js");
const customMusic = require("./custommusic.js");
const itemControl = require("./itemcontrol.js");
const masterpieces = require("./masterpieces.js");
const themeRooms = require("./themerooms.js");
const panel = require("./panel.js");
const totp = require("./totp.js");
const world = require("./world.js");
@@ -230,6 +234,75 @@ const itemArtUpload = async (req, res, url, from, signedIn = null, adminSignedIn
send(res, 200, result);
};
// music tracks uploaded in the panels (lib/custommusic.js), at
// /mod/api/music (staff with "music.upload") and /admin/api/music:
// GET: the tracks; GET ?play=<id>: one's file, to listen to;
// POST ?name=&cost=&inShop=1, the MP3 as the body: a new track;
// POST ?delete=<id>: the track deleted, and taken from every player.
// `signedIn` (req) -> account: the moderator panel's session;
// `adminSignedIn` (req) -> boolean: the admin panel's, written down as "admin".
const musicUploads = limits.limiter(30, 3600000); // tracks an hour, per staff member
const musicRoute = async (req, res, url, from, signedIn = null, adminSignedIn = null) => {
res.setHeader("Cache-Control", "no-store");
const asAdmin = Boolean(adminSignedIn && adminSignedIn(req));
const account = asAdmin ? null : signedIn ? signedIn(req) : null;
if (!asAdmin && !(account && roles.can(account, "music.upload"))) {
send(res, 403, {error: "Your role cannot upload music."});
return;
}
const by = asAdmin ? "admin" : account.username;
if (req.method === "GET" || req.method === "HEAD") {
if (url.searchParams.has("play")) {
const track = customMusic.file(url.searchParams.get("play"));
if (!track) {
send(res, 404, "Not found", "text/plain");
return;
}
res.setHeader("Content-Security-Policy", "default-src 'none'; sandbox");
res.setHeader("X-Content-Type-Options", "nosniff");
send(res, 200, track.data, "audio/mpeg");
return;
}
send(res, 200, {tracks: customMusic.list(), maxBytes: customMusic.MAX_BYTES});
return;
}
if (req.method !== "POST" || !limits.originAllowed(req)) {
send(res, 403, {error: "forbidden"});
return;
}
if (url.searchParams.has("delete")) {
const entry = customItems.get("den", url.searchParams.get("delete"));
if (!entry || !entry.audio) {
send(res, 404, {error: "No such uploaded track."});
return;
}
const result = itemControl.deleteCustom("den", entry.id, world);
if (result.ok) {
modlog.record(by, "music deleted", "", `den ${entry.id} ${entry.name}`);
}
send(res, result.ok ? 200 : 400, result);
return;
}
if (!asAdmin && !musicUploads.allow(account.id)) {
send(res, 429, {error: "Too many uploads. Try again later."});
return;
}
const data = await readBody(req, customMusic.MAX_BYTES + 1).catch(() => null);
if (!data) {
send(res, 413, {error: `That file is too big: ${customMusic.MAX_BYTES / 1024 / 1024} MB at most.`});
return;
}
const result = customMusic.add(data, {name: url.searchParams.get("name"), cost: url.searchParams.get("cost") || 0,
inShop: url.searchParams.get("inShop") === "1"}, by);
if (result.error) {
send(res, 400, result);
return;
}
modlog.record(by, "music uploaded", "", `den ${result.item.id} ${result.item.name}`);
send(res, 200, {ok: `"${result.item.name}" is den item ${result.item.id}. Players can get it from the item finder now${result.item.inShop ? ", and the shop" : ""}.`,
item: {id: result.item.id, name: result.item.name}});
};
// a picture still waiting for a moderator, which /itemart/ does not serve:
// to its maker (the account page) and to staff who review or make items.
const itemArtView = (req, res, url, signedIn, adminSignedIn) => {
@@ -361,6 +434,7 @@ const CAPTCHA_PAGE_HEADERS = {...PAGE_HEADERS, "Content-Security-Policy": captch
// write, from config.js.
const LEGAL_VALUES = {legalEmail: config.legalEmail, adminEmail: config.adminEmail, operator: config.operator, hostedIn: config.hostedIn,
version: config.termsVersion, site: new URL(config.siteUrl).host};
const MAX_RULES_LENGTH = 65536; // characters of data/rules.txt the game is sent
const escapeHtml = text => String(text).replace(/[&<>"]/g, sign => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;"})[sign]);
const sendLegalPage = async (res, file) => {
for (const [name, value] of Object.entries(PAGE_HEADERS)) {
@@ -686,6 +760,12 @@ const handle = async (req, res) => {
from.local = false;
}
// GitHub sends signed push events here for optional Discord update cards.
if (url.pathname === "/discord/github") {
await discordBot.handleGithubWebhook(req, res);
return;
}
// One entry point for the owner and staff dashboards. The old addresses
// stay as bookmark-friendly redirects; their APIs remain available for
// installed tools and are not redirected.
@@ -731,6 +811,10 @@ const handle = async (req, res) => {
await itemArtUpload(req, res, url, from, null, panel.signedIn);
return;
}
if (url.pathname === "/admin/api/music") {
await musicRoute(req, res, url, from, null, panel.signedIn);
return;
}
await panel.handle(req, res, url, from, {send, readJson});
return;
}
@@ -757,6 +841,10 @@ const handle = async (req, res) => {
await itemArtUpload(req, res, url, from, modpanel.signedInAs);
return;
}
if (isMod && url.pathname === "/mod/api/music") {
await musicRoute(req, res, url, from, modpanel.signedInAs);
return;
}
if (isMod) {
await modpanel.handle(req, res, url, from, {send, readJson});
return;
@@ -921,6 +1009,10 @@ const handle = async (req, res) => {
res.setHeader("Cache-Control", "public, max-age=86400");
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "ban-icon.png")), MIME[".png"]);
return;
case "GET /burrow-status-banner.png": // public banner used by the Discord status card
res.setHeader("Cache-Control", "public, max-age=86400");
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "burrow-status-banner.png")), MIME[".png"]);
return;
case "GET /bio-icon.png": // the button of the card's Bio tab
res.setHeader("Cache-Control", "public, max-age=86400");
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "bio-icon.png")), MIME[".png"]);
@@ -981,18 +1073,45 @@ const handle = async (req, res) => {
return;
}
const parts = formParts(req.headers["content-type"], await readBody(req, masterpieces.MAX_IMAGE_BYTES + 16 * 1024));
const uuid = await masterpieces.upload(String(parts.get("authToken") || ""), parts.get("image"));
const {uuid, refusal, maker} = await masterpieces.upload(String(parts.get("authToken") || ""), parts.get("image"));
// the game only says it could not be sent: HQ says why
if (refusal && maker) {
world.tellAccount(maker, refusal);
}
send(res, 200, uuid ? {success: true, uuid} : {success: false});
return;
}
case "GET /crossdomain.xml":
send(res, 200, CROSS_DOMAIN, "text/xml");
return;
// the game's rules window (AJClient.showRules) shows this file, read
// again on every ask so it can be changed on a running server; made
// with a placeholder when there is none.
case "GET /rules.txt": {
const file = path.join(config.dataDir, "rules.txt");
let text;
try {
text = await fs.promises.readFile(file, "utf8");
}
catch (err) {
if (err.code !== "ENOENT") {
throw err;
}
text = "Example\n";
await fs.promises.writeFile(file, text, {flag: "wx"}).catch(() => {});
}
res.setHeader("Cache-Control", "no-cache");
res.setHeader("X-Content-Type-Options", "nosniff");
send(res, 200, text.slice(0, MAX_RULES_LENGTH), "text/plain; charset=utf-8");
return;
}
case "GET /gameClient/game/index.html":
// not to be put in a frame of anyone's; the client shows it in a view of its own.
res.setHeader("X-Frame-Options", "DENY");
res.setHeader("Referrer-Policy", "no-referrer");
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "game.html")), MIME[".html"]);
// the admin's switch for the theatre browser (lib/panel.js), for the page to read
send(res, 200, String(await fs.promises.readFile(path.join(config.publicDir, "game.html")))
.replace("<html>", panel.theatreBrowserOn() ? '<html data-theatre-browser="on">' : "<html>"), MIME[".html"]);
return;
}
@@ -1027,7 +1146,15 @@ const handle = async (req, res) => {
return session ? limits.key(session.address) : null;
};
const picture = masterpieces.mayView(painting[1], from.key, playingFrom) || from.local ? masterpieces.image(painting[1]) : null;
send(res, picture ? 200 : 404, picture || "Not found", picture ? MIME[".jpg"] : "text/plain");
if (picture) {
send(res, 200, picture, MIME[".jpg"]);
return;
}
// one that cannot be shown (waiting to be looked at, seen from an
// address not its maker's game's, or its file gone) is the Burrow logo:
// given nothing, the game waited for it for good, behind its spinner.
res.setHeader("Cache-Control", "no-store");
send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "logo-square.png")), MIME[".png"]);
return;
}
@@ -1043,15 +1170,21 @@ const handle = async (req, res) => {
send(res, body ? 200 : 404, body || "Not found", body ? MIME[".swf"] : "text/plain");
return;
}
// the extra den music tracks, which the CDN does not have as files.
const extra = await extraMusic.asset(relPath);
// the extra den music tracks, which the CDN does not have as files, and
// those uploaded by staff.
const extra = await extraMusic.asset(relPath) || await customMusic.asset(relPath);
if (extra) {
send(res, extra.body ? 200 : 404, extra.body || "Not found", extra.body ? extra.type : "text/plain");
return;
}
const clientPack = await defpacks.clientPack(relPath);
if (clientPack) {
send(res, 200, clientPack, "application/octet-stream");
// what custom items this game has from its packs (customItems.sendAll)
const packKind = defpacks.customPackKind(relPath);
if (packKind) {
customItems.sawPack(from.key, packKind, clientPack.version);
}
send(res, 200, clientPack.body, "application/octet-stream");
return;
}
// A room file in a seasonal theme ("<build>/roomDefs/theme_<other
@@ -1059,8 +1192,11 @@ const handle = async (req, res) => {
// or from the current one when the room did not exist yet back then.
const themed = THEMED_ROOM.exec(relPath);
const mayFetch = () => from.local || cacheMisses.allow(from.key);
const body = (themed && Object.values(config.themes).some(theme => theme.build === Number(themed[2])) && await cdn.get(`${themed[2]}/roomDefs/${themed[3]}`, mayFetch))
|| await cdn.get(themed ? `${themed[1]}/roomDefs/${themed[3]}` : relPath, mayFetch);
const currentPath = themed ? `${themed[1]}/roomDefs/${themed[3]}` : relPath;
const oldBody = themed && themed[2] !== themed[1] && Object.values(config.themes).some(theme => theme.build === Number(themed[2]))
&& await cdn.get(`${themed[2]}/roomDefs/${themed[3]}`, mayFetch);
// its shops and other spots as today's room has them (lib/themerooms.js)
const body = oldBody ? await themeRooms.fix(relPath, oldBody, () => cdn.get(currentPath, mayFetch)) : await cdn.get(currentPath, mayFetch);
if (!body) {
// one the CDN does not have is asked for again and again (the same few
// hundred, by every client that meets them): its client may keep the
+2 -2
View File
@@ -22,9 +22,9 @@ const imageModeration = require("./image-moderation.js");
// kept as data/itemart/<kind>-<id>.<png|jpg|gif>; its version, a hash, is on
// the item (customItems.setArt), so a new picture is a new address.
const MAX_BYTES = 300 * 1024; // a picture kept
const MAX_BYTES = 100 * 1024; // a picture kept: every player who sees the item downloads it
const MAX_UPLOAD = 2 * 1024 * 1024; // one sent (a BMP is bigger than the PNG it becomes)
const MAX_SIDE = 512;
const MAX_SIDE = 256; // drawn fitted to the item anyway (a den item's place is 160)
const MIN_SIDE = 8;
const DIR = path.join(config.dataDir, "itemart");
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
+76
View File
@@ -0,0 +1,76 @@
"use strict";
// pictures of items for the web item giver (public/items.html), from the
// game's own files on the CDN:
//
// - clothing: the icon the game shows in a closet (item.SimpleIcon), a
// paletted bitmap the page colours itself as the game does
// (LayerBitmap.paintFrame), so any four colours show without asking again.
// - den items: their art, a SWF, which public/item-preview.html plays with
// Ruffle through public/item-preview.swf (tools/preview-host).
//
// both are the same for everyone, so no sign-in is asked for them.
const zlib = require("zlib");
const amf3 = require("./amf3.js");
const cdn = require("./cdn.js");
const customItems = require("./customitems.js");
const defpacks = require("./defpacks.js");
const ICON_AVATAR = 1; // the avatar every closet icon is drawn for (Item.makeSmallIcon)
const ICON_LARGE = 25; // SimpleIcon.AN_ICON_L
const ICON_SMALL = 26; // SimpleIcon.AN_ICON_S
const IMAGE_VERSION = 0x7080900; // what ImageServerURL accepts
// DenItem.getIconId: which of an item's pictures the den shows, by its sort category.
const iconId = sortCat => ([0, 99, 6, 5].includes(sortCat) ? 1 : sortCat === 1 ? 2 : [2, 3, 4].includes(sortCat) ? 3 : sortCat + 1);
// a custom item is drawn as the game's item it was made from.
const baseIdOf = (kind, id) => {
const entry = customItems.get(kind, id);
return entry ? entry.base : Number(id);
};
// a clothing item's closet icon, large if there is one: {w, h, b} with b the
// first frame's run-length bytes, base64 (LayerBitmap.paintFrame reads them).
// null when it has none.
const clothingIcon = async id => {
const def = defpacks.itemDef(id);
if (!def || !Number.isInteger(Number(def.layerDefId))) {
return null;
}
for (const size of [ICON_LARGE, ICON_SMALL]) {
const file = await cdn.get(cdn.hashedPath(`imageArrays/${((ICON_AVATAR << 24) | (size << 16) | Number(def.layerDefId)) >>> 0}`));
try {
const image = file && amf3.decode(zlib.inflateSync(file));
const frame = image && image.v === IMAGE_VERSION && Array.isArray(image.f) && image.f[0];
if (frame && Buffer.isBuffer(frame.b) && frame.w > 0 && frame.h > 0) {
return {w: frame.w, h: frame.h, b: frame.b.toString("base64")};
}
}
catch (err) {
// not an icon this can read: the next size, or none.
}
}
return null;
};
// a den item's art as the SWF it holds, or null.
const denArt = async id => {
const def = defpacks.denItemDef(id);
const baseId = baseIdOf("den", id);
const baseDef = defpacks.denItemDef(baseId);
if (!def || !baseDef) {
return null;
}
const file = await cdn.get(cdn.hashedPath(`items/${((baseId << 16) | iconId(Number(baseDef.sortCat))) >>> 0}`));
try {
const wrapped = file && amf3.decode(file);
return wrapped && wrapped.ba ? Buffer.from(wrapped.ba) : null;
}
catch (err) {
return null;
}
};
module.exports = {clothingIcon, denArt};
+39
View File
@@ -19,6 +19,8 @@ const LAYER_EYES = "3";
const MAX_RECYCLED_AT_ONCE = 500;
const MAX_USED_AT_ONCE = 200; // pieces put on or taken off in one message
const RECYCLE_FRACTION = 0.3; // matches recyclePercentage sent at login
const CURRENCY_GEMS = 0; // ItemXtCommManager.currencyUpdateResponse's currency type
const PHOTO_GEMS = 50; // what the photo booth says a picture costs (string 14789)
module.exports = ({others, sendItemList}) => {
// ItemXtCommManager.itemBuyResponse: [status, shopId, newAmount, currencyType]
@@ -141,6 +143,43 @@ module.exports = ({others, sendItemList}) => {
session.sendXt("ce", -1, 1, account.currency[paid]);
},
// gui.MuseumDonation: [amount], gems given to the museum's causes. the
// reply (currencyDonationResponse) is [1] or [0]; the gems go, and the
// account keeps count of what it has given.
cd(session, roomId, [amount]) {
const {account} = session;
const gems = /^\d{1,9}$/.test(String(amount)) ? Number(amount) : 0;
if (gems < 1 || (account.currency.gems || 0) < gems) {
session.sendXt("cd", -1, 0);
return;
}
account.currency.gems -= gems;
account.gemsDonated = (account.gemsDonated || 0) + gems;
achievements.currencyChanged(account, "gems", -gems);
accounts.save(account);
session.sendXt("cu", -1, CURRENCY_GEMS, account.currency.gems, 0);
session.sendXt("cd", -1, 1);
},
// the photo booth's picture (gui.PhotoBooth), PHOTO_GEMS gems. "apc"
// asks first: [gems after, or -1 for too few]; "apb", once the player
// keeps the picture, pays: [gem total]. neither was answered, and the
// booth waited behind its spinner for good.
apc(session) {
const gems = session.account.currency.gems || 0;
session.sendXt("apc", -1, gems >= PHOTO_GEMS ? gems - PHOTO_GEMS : -1);
},
apb(session) {
const {account} = session;
if ((account.currency.gems || 0) >= PHOTO_GEMS) {
account.currency.gems -= PHOTO_GEMS;
achievements.currencyChanged(account, "gems", -PHOTO_GEMS);
accounts.save(account);
}
session.sendXt("apb", -1, account.currency.gems || 0);
},
// ItemXtCommManager.requestItemRecycle: [invIdx, ...]. the reply
// (itemRecycleResponse) is [count, newGemTotal, ...recycledInvIdx], and
// the recycling window then waits, behind its spinner, for the item
+212
View File
@@ -0,0 +1,212 @@
"use strict";
// a picture's fingerprint, to know a masterpiece again when it comes back
// re-encoded (lib/masterpieces.js): the Art Studio paints a saved .ajart
// again a little differently, so the JPEG's bytes differ while every 8 by 8
// block's average stays within a fraction of a step.
//
// the fingerprint is the average of each block, per component, read from
// the JPEG's DC coefficients alone (no inverse DCT): a baseline JPEG (what
// the Art Studio writes) with no subsampling and no restart markers. any
// other JPEG has none, and only its exact bytes are known again.
//
// layout: [width (uint16), height (uint16), components (uint8)], then a byte
// per block and component, block by block in rows.
const HEADER = 5;
const SAME_WITHIN = 2; // of 255, per block: a mark of a few pixels moves its block by more
const THUMB = 16; // the thumbnail's side, for finding candidates quickly
// a Huffman table as JPEG decoders keep it: per code length the smallest
// and largest code and where its values start.
const huffmanTable = (counts, values) => {
const minCode = new Int32Array(17);
const maxCode = new Int32Array(18).fill(-1);
const valPtr = new Int32Array(17);
let code = 0;
let k = 0;
for (let length = 1; length <= 16; length++) {
valPtr[length] = k;
minCode[length] = code;
code += counts[length - 1];
k += counts[length - 1];
maxCode[length] = counts[length - 1] ? code - 1 : -1;
code <<= 1;
}
maxCode[17] = 0x7FFFFFFF;
return {minCode, maxCode, valPtr, values};
};
// the fingerprint of a JPEG, or null.
const fingerprint = buf => {
try {
return read(buf);
}
catch (err) {
return null;
}
};
const read = buf => {
const tables = {};
const quant = {};
let frame = null;
let scan = null;
let at = 2;
while (!scan) {
if (at + 4 > buf.length || buf[at] !== 0xFF) {
return null;
}
const marker = buf[at + 1];
const length = buf.readUInt16BE(at + 2);
const body = buf.subarray(at + 4, at + 2 + length);
if (marker === 0xDB) {
for (let p = 0; p + 65 <= body.length; p += 65) {
if (body[p] >> 4) {
return null; // 16-bit tables: not the Art Studio's
}
quant[body[p] & 15] = body[p + 1];
}
}
else if (marker === 0xC4) {
for (let p = 0; p + 17 <= body.length;) {
const counts = body.subarray(p + 1, p + 17);
const total = counts.reduce((sum, count) => sum + count, 0);
tables[(body[p] >> 4 ? "ac" : "dc") + (body[p] & 15)] = huffmanTable(counts, body.subarray(p + 17, p + 17 + total));
p += 17 + total;
}
}
else if (marker === 0xC0 || marker === 0xC1) {
const comps = body[5];
frame = {height: body.readUInt16BE(1), width: body.readUInt16BE(3), comps: []};
for (let c = 0; c < comps; c++) {
if (body[7 + c * 3] !== 0x11) {
return null; // subsampled
}
frame.comps.push(body[8 + c * 3]);
}
}
else if (marker === 0xDD || (marker >= 0xC2 && marker <= 0xCF && marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC)) {
return null; // restart markers, progressive, lossless or arithmetic
}
else if (marker === 0xDA) {
scan = [];
for (let c = 0; c < body[0]; c++) {
scan.push({dc: tables[`dc${body[2 + c * 2] >> 4}`], ac: tables[`ac${body[2 + c * 2] & 15}`]});
}
}
at += 2 + length;
}
if (!frame || frame.width < 1 || frame.height < 1 || scan.length !== frame.comps.length || scan.length < 1 || scan.length > 3
|| scan.some(table => !table.dc || !table.ac) || frame.comps.some(id => quant[id] === undefined)) {
return null;
}
// the entropy-coded data, its 0xFF bytes followed by a stuffed 0x00
let pos = at;
let bits = 0;
let left = 0;
const bit = () => {
if (left === 0) {
if (pos >= buf.length) {
throw new Error("ran out");
}
bits = buf[pos++];
if (bits === 0xFF) {
if (buf[pos] !== 0) {
throw new Error("marker in the data");
}
pos++;
}
left = 8;
}
left--;
return (bits >> left) & 1;
};
const decode = table => {
let code = bit();
let length = 1;
while (code > table.maxCode[length]) {
code = (code << 1) | bit();
if (++length > 16) {
throw new Error("bad code");
}
}
return table.values[table.valPtr[length] + code - table.minCode[length]];
};
const receive = size => {
let value = 0;
for (let i = 0; i < size; i++) {
value = (value << 1) | bit();
}
return value < 1 << (size - 1) ? value - (1 << size) + 1 : value;
};
const across = Math.ceil(frame.width / 8);
const down = Math.ceil(frame.height / 8);
const comps = scan.length;
const out = Buffer.alloc(HEADER + across * down * comps);
out.writeUInt16BE(frame.width, 0);
out.writeUInt16BE(frame.height, 2);
out[4] = comps;
const predicted = new Int32Array(comps);
for (let block = 0; block < across * down; block++) {
for (let c = 0; c < comps; c++) {
const size = decode(scan[c].dc);
predicted[c] += size ? receive(size) : 0;
// the DC coefficient is eight times the block's average, less 128
const average = Math.round(predicted[c] * quant[frame.comps[c]] / 8 + 128);
out[HEADER + block * comps + c] = Math.max(0, Math.min(255, average));
for (let k = 1; k < 64;) {
const runSize = decode(scan[c].ac);
if ((runSize & 15) === 0) {
if (runSize >> 4 !== 15) {
break; // end of block
}
k += 16;
continue;
}
k += runSize >> 4;
receive(runSize & 15);
k++;
}
}
}
return out;
};
// the first component (brightness) in THUMB by THUMB, to find candidates
// among many fingerprints before comparing whole ones.
const thumbnail = print => {
const across = Math.ceil(print.readUInt16BE(0) / 8);
const down = Math.ceil(print.readUInt16BE(2) / 8);
const comps = print[4];
const sums = new Float64Array(THUMB * THUMB);
const counts = new Float64Array(THUMB * THUMB);
for (let y = 0; y < down; y++) {
for (let x = 0; x < across; x++) {
const cell = Math.floor(y * THUMB / down) * THUMB + Math.floor(x * THUMB / across);
sums[cell] += print[HEADER + (y * across + x) * comps];
counts[cell]++;
}
}
return Buffer.from(sums.map((sum, cell) => (counts[cell] ? Math.round(sum / counts[cell]) : 0)));
};
// could these two be the same picture? (thumbnails: a cheap first look)
const thumbnailsClose = (one, other) => one.length === other.length && one.every((value, i) => Math.abs(value - other[i]) <= SAME_WITHIN);
// the same picture: the same size, and no block further apart than a step or two.
const samePicture = (one, other) => {
if (!one || !other || one.length !== other.length || one.compare(other, 0, HEADER, 0, HEADER) !== 0) {
return false;
}
for (let i = HEADER; i < one.length; i++) {
if (Math.abs(one[i] - other[i]) > SAME_WITHIN) {
return false;
}
}
return true;
};
module.exports = {fingerprint, thumbnail, thumbnailsClose, samePicture};
+31 -1
View File
@@ -1,5 +1,6 @@
"use strict";
const net = require("net");
const config = require("../config.js");
// small in-memory rate limits for the parts of the server that strangers can
@@ -28,6 +29,25 @@ const key = address => {
const isLoopback = address => LOOPBACK.includes(String(address || "").replace(/^::ffff:/i, ""));
// the addresses Cloudflare's edge connects from, as it publishes them at
// https://www.cloudflare.com/ips/ (they seldom change; add any new range here).
const CLOUDFLARE = new net.BlockList();
for (const range of ["173.245.48.0/20", "103.21.244.0/22", "103.22.200.0/22", "103.31.4.0/22", "141.101.64.0/18",
"108.162.192.0/18", "190.93.240.0/20", "188.114.96.0/20", "197.234.240.0/22", "198.41.128.0/17", "162.158.0.0/15",
"104.16.0.0/13", "104.24.0.0/14", "172.64.0.0/13", "131.0.72.0/22"]) {
const [prefix, bits] = range.split("/");
CLOUDFLARE.addSubnet(prefix, Number(bits), "ipv4");
}
for (const range of ["2400:cb00::/32", "2606:4700::/32", "2803:f800::/32", "2405:b500::/32", "2405:8100::/32",
"2a06:98c0::/29", "2c0f:f248::/32"]) {
const [prefix, bits] = range.split("/");
CLOUDFLARE.addSubnet(prefix, Number(bits), "ipv6");
}
const fromCloudflare = address => {
const family = net.isIP(address);
return family !== 0 && CLOUDFLARE.check(address, family === 4 ? "ipv4" : "ipv6");
};
// is this address the server's own machine, and does that count for
// anything here? (It must not when a local reverse proxy forwards everyone.)
const isTrustedLocal = address => config.trustLocalRequests && isLoopback(address);
@@ -45,7 +65,17 @@ const clientOf = req => {
const own = String(req.socket.remoteAddress || "").replace(/^::ffff:/i, "");
const forwarded = req.headers["x-forwarded-for"] || req.headers.forwarded || req.headers["cf-connecting-ip"] || req.headers["x-real-ip"];
const hops = String(req.headers["x-forwarded-for"] || "").split(",").map(hop => hop.trim()).filter(Boolean);
const address = config.trustedProxy && isLoopback(own) && hops.length ? hops[hops.length - 1].replace(/^::ffff:/i, "").slice(0, 60) : own;
// the last X-Forwarded-For entry is the one the local proxy appended: who
// connected to it (the first is whatever the visitor sent, so it is never
// used). Behind Cloudflare that is Cloudflare's own edge, which made every
// visitor one address (and left remoteip out of the Turnstile check), so
// then CF-Connecting-IP is the visitor. Only when that hop is Cloudflare:
// anyone who reaches the server directly can send the header too. Neither
// header counts unless the local reverse proxy has been trusted.
const lastHop = (hops.at(-1) || "").replace(/^::ffff:/i, "");
const cloudflareAddress = String(req.headers["cf-connecting-ip"] || "").trim().replace(/^::ffff:/i, "");
const reported = net.isIP(cloudflareAddress) && fromCloudflare(lastHop) ? cloudflareAddress : lastHop;
const address = config.trustedProxy && isLoopback(own) && reported ? reported.replace(/^::ffff:/i, "").slice(0, 60) : own;
const direct = isLoopback(own) && !forwarded;
return {address, key: key(address), direct, local: direct && config.trustLocalRequests};
};
+223 -5
View File
@@ -24,6 +24,10 @@ const support = require("./support.js");
const totp = require("./totp.js");
const recoveryMail = require("./recoverymail.js");
const world = require("./world.js");
const chatStyles = require("./chatstyles.js");
const roles = require("./roles.js");
const admin = require("./admin.js");
const itemPreview = require("./itempreview.js");
// the account page at /account: what a player can do about their own
// account from a browser. they sign in with the game's username and
@@ -50,6 +54,29 @@ const discordCookie = (value, maxAgeSeconds) =>
`${DISCORD_COOKIE}=${value}; Path=/account/discord; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const SESSION_HOURS = 12;
const TEN_MINUTES_MS = 600000;
// "Sign in with the Burrow client": the page starts it, and keeps this
// cookie; the link it opens (burrow://account?n=<nonce>) has the client ask
// for a ticket with its own login token, which it then opens in the
// browser at /account/client. the ticket signs in only the browser that
// holds the nonce it was asked for, so a burrow:// link from anywhere else
// signs nobody in, and a ticket sent to someone else opens nothing for them.
const CLIENT_COOKIE = "ajc_clink";
const clientCookie = (value, maxAgeSeconds) =>
`${CLIENT_COOKIE}=${value}; Path=/account/client; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const CLIENT_START_MS = 5 * 60 * 1000;
const CLIENT_TICKET_MS = 2 * 60 * 1000;
const MAX_CLIENT_STARTS = 10000;
const clientStarts = new Map(); // SHA-256 of a nonce -> expiry (ms)
const clientTickets = new Map(); // SHA-256 of a ticket -> {id: account id, nonce: SHA-256 of its nonce, expiry: ms}
const clientStartsByAddress = limits.limiter(20, TEN_MINUTES_MS);
const clientTicketsByAccount = limits.limiter(10, TEN_MINUTES_MS);
const dropExpired = map => {
for (const [hash, entry] of map) {
if ((typeof entry === "number" ? entry : entry.expiry) < Date.now()) {
map.delete(hash);
}
}
};
const MAX_NOTE = 120;
const RECOVERY_TOKEN_MS = 30 * 60 * 1000;
const recoveryHash = token => crypto.createHash("sha256").update(token).digest("hex");
@@ -63,6 +90,20 @@ const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_M
const WRONG_PASSWORDS_ALLOWED = 5;
const wrongPasswords = limits.limiter(WRONG_PASSWORDS_ALLOWED, TEN_MINUTES_MS);
const recoveryRequests = limits.limiter(5, TEN_MINUTES_MS);
// recovery mail sent for one account, from any address: a few an hour.
const recoveryMailsPerAccount = limits.limiter(3, 3600000);
// a 2FA reset by email waits this long after a password reset by email, so
// that someone who has only the mailbox cannot do one after the other.
const EMAIL_RESET_GAP_MS = 7 * 24 * 3600000;
// why a 2FA reset by email cannot be done for this account now, or null.
// it also needs the account's password (recover/complete). staff ask the
// admin (lib/panel.js), whose 2FA reset ends their role's use until they
// turn it on again: a mailbox must not make someone staff.
const twoStepResetProblem = account => roles.roleOf(account)
? "Staff accounts cannot remove 2FA by email. Ask the admin."
: account.emailPasswordResetAt && Date.now() - account.emailPasswordResetAt < EMAIL_RESET_GAP_MS
? "2FA cannot be removed by email within 7 days of a password reset by email."
: null;
// what may be done from the page of a ban (above).
const BANNED_MAY = ["password", "twoStepStart", "twoStepConfirm", "twoStepOff", "forgetDevices", "delete", "appeal"];
// and from the page of a rejected username: the same, with a new name in
@@ -168,6 +209,7 @@ const profile = (account, from) => {
logins: account.numLogins || 0,
playtime: account.playtime,
playtimePublic: account.playtimePublic,
chatStyle: chatStyles.normalize(account.chatStyle),
animals: account.avatars.length,
animalType: avatar ? avatar.type : null,
items: account.items.length,
@@ -428,6 +470,17 @@ const act = (account, body, req, from, res) => {
account.playtimePublic = body.on === true;
accounts.save(account);
return {ok: account.playtimePublic ? "Others can see your playtime on your card." : "Your playtime is private."};
// A player can choose every colour, opacity, animation and animation
// speed. Validation is deliberately here as well as in the page: saved
// state is not trusted just because it came from our own browser UI.
case "chatStyle": {
if (!chatStyles.valid(body.style)) {
return {error: "Choose valid chat colours and animation settings."};
}
account.chatStyle = chatStyles.normalize(body.style);
accounts.save(account);
return {ok: "Chat style saved. Your next message will use it."};
}
// their Discord account, for their card in the game: it is linked by
// signing in to Discord (GET /account/discord/link), and only taken off
// here, with the booster badge it brought.
@@ -515,6 +568,16 @@ const PAGE_HEADERS = {
+ "form-action 'none'; frame-ancestors 'none'; base-uri 'none'"),
};
// the web item giver shows den items in frames of public/item-preview.html,
// which plays them with Ruffle (a Flash player, from jsDelivr).
const ITEMS_PAGE_POLICY = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; "
+ "frame-src 'self'; form-action 'none'; frame-ancestors 'none'; base-uri 'none'";
const RUFFLE = "https://cdn.jsdelivr.net/npm/@ruffle-rs/[email protected]/";
const PREVIEW_POLICY = `default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval' ${RUFFLE}; connect-src 'self' ${RUFFLE}; `
+ "style-src 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' data: blob:; worker-src blob:; "
+ "form-action 'none'; frame-ancestors 'self'; base-uri 'none'; sandbox allow-scripts";
const artFetches = limits.limiter(600, 600000); // item pictures for the web item giver, per address in ten minutes
// A request that changes something must come from this server's own page.
const sameOrigin = limits.originAllowed;
@@ -530,6 +593,41 @@ const handle = async (req, res, url, from, web) => {
web.send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, "account.html"))), "text/html; charset=utf-8");
return;
}
// the item giver on the web (public/items.html), with this page's sign-in.
if (route === "GET /account/items") {
res.setHeader("Content-Security-Policy", ITEMS_PAGE_POLICY);
web.send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "items.html")), "text/html; charset=utf-8");
return;
}
// its den item previews (lib/itempreview.js): a page of their own in a
// frame, sandboxed, as they run a Flash player from elsewhere (Ruffle).
if (route === "GET /account/item-preview") {
res.setHeader("Content-Security-Policy", PREVIEW_POLICY);
res.setHeader("X-Frame-Options", "SAMEORIGIN");
web.send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "item-preview.html")), "text/html; charset=utf-8");
return;
}
const art = /^GET \/account\/(item-preview\.swf|art\/(clothing|den)\/(\d{1,9}))$/.exec(route);
if (art) {
// fetched from the preview's sandbox, which has no origin of its own
res.setHeader("Access-Control-Allow-Origin", "*");
if (art[1] === "item-preview.swf") {
web.send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "item-preview.swf")), "application/x-shockwave-flash");
return;
}
if (!artFetches.allow(from.address)) {
reply(429, {error: "Too many at once. Try again in a minute."});
return;
}
const found = art[2] === "den" ? await itemPreview.denArt(Number(art[3])) : await itemPreview.clothingIcon(Number(art[3]));
if (!found) {
reply(404, {error: "No picture."});
return;
}
res.setHeader("Cache-Control", "public, max-age=3600");
web.send(res, 200, found, art[2] === "den" ? "application/x-shockwave-flash" : "application/json");
return;
}
if (route === "GET /account/recover") {
web.send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, "recover.html"))), "text/html; charset=utf-8");
return;
@@ -551,7 +649,8 @@ const handle = async (req, res, url, from, web) => {
const account = accounts.byName(String(body.username || ""));
const email = String(body.email || "").trim().toLowerCase();
const kind = body.kind === "twoStep" ? "twoStep" : "password";
if (account && account.recoveryEmail && account.recoveryEmail === email && recoveryMail.available()) {
if (account && account.recoveryEmail && account.recoveryEmail === email && recoveryMail.available()
&& recoveryMailsPerAccount.allow(account.id)) {
const token = crypto.randomBytes(32).toString("hex");
account.recoveryTokens = (account.recoveryTokens || []).filter(entry => entry.expires > Date.now());
account.recoveryTokens.push({hash: recoveryHash(token), kind, expires: Date.now() + RECOVERY_TOKEN_MS});
@@ -571,7 +670,8 @@ const handle = async (req, res, url, from, web) => {
const token = String(body.token || "");
const account = [...accounts.all()].find(candidate => (candidate.recoveryTokens || []).some(entry => entry.hash === recoveryHash(token) && entry.expires > Date.now()));
const entry = account && account.recoveryTokens.find(candidate => candidate.hash === recoveryHash(token) && candidate.expires > Date.now());
reply(entry ? 200 : 400, entry ? {kind: entry.kind} : {error: "This recovery link is invalid or expired."});
const refused = entry && entry.kind === "twoStep" ? twoStepResetProblem(account) : null;
reply(entry && !refused ? 200 : 400, entry && !refused ? {kind: entry.kind} : {error: refused || "This recovery link is invalid or expired."});
return;
}
case "POST /account/api/recover/complete": {
@@ -588,10 +688,28 @@ const handle = async (req, res, url, from, web) => {
reply(400, {error: problem === "weak_password" ? "That password is too easy to guess." : "Use 10+ characters with an uppercase letter, lowercase letter and digit."});
return;
}
account.emailPasswordResetAt = Date.now();
}
else if (totp.isOn(account)) {
totp.turnOff(account);
accounts.revokeTokens(account);
else {
const refused = twoStepResetProblem(account);
if (refused) {
reply(400, {error: refused});
return;
}
// the mailbox and the password: the link alone does not remove 2FA.
if (!from.local && failuresByAddress.blocked(from.key)) {
reply(429, {error: "Too many attempts. Try later."});
return;
}
if (await accounts.authenticateAsync(account.username, body.password) !== account) {
failuresByAddress.record(from.key);
reply(401, {error: "Wrong password."});
return;
}
if (totp.isOn(account)) {
totp.turnOff(account);
accounts.revokeTokens(account);
}
}
account.recoveryTokens = [];
accounts.save(account);
@@ -659,6 +777,84 @@ const handle = async (req, res, url, from, web) => {
reply(200, {ok: true});
return;
}
// "Sign in with the Burrow client" (above), from the page: the nonce for
// the burrow:// link, which this browser keeps as a cookie too.
case "POST /account/api/client-start": {
if (!from.local && !clientStartsByAddress.allow(from.key)) {
reply(429, {error: "Too many attempts. Try later."});
return;
}
dropExpired(clientStarts);
if (clientStarts.size >= MAX_CLIENT_STARTS) {
reply(503, {error: "Try again in a few minutes."});
return;
}
const nonce = crypto.randomBytes(24).toString("hex");
clientStarts.set(sha256(nonce), Date.now() + CLIENT_START_MS);
res.setHeader("Set-Cookie", clientCookie(nonce, CLIENT_START_MS / 1000));
reply(200, {nonce});
return;
}
// ... from the client, with its login token (no Origin: the client's main
// process): where to send the browser, which signs in there. a token is
// only given after a whole sign-in, 2FA code included (lib/http.js).
case "POST /account/api/client-ticket": {
const nonce = typeof body.nonce === "string" && /^[0-9a-f]{48}$/.test(body.nonce) ? body.nonce : "";
const started = nonce && clientStarts.get(sha256(nonce));
if (!started || started < Date.now()) {
reply(400, {error: "Start again from the account page."});
return;
}
if (!from.local && failuresByAddress.blocked(from.key)) {
reply(429, {error: "Too many attempts. Try later."});
return;
}
const account = accounts.byToken(body.token);
if (!account) {
failuresByAddress.record(from.key);
reply(401, {error: "Log in to Burrow again first."});
return;
}
if (!clientTicketsByAccount.allow(account.id)) {
reply(429, {error: "Too many attempts. Try later."});
return;
}
dropExpired(clientTickets);
const ticket = crypto.randomBytes(24).toString("hex");
clientTickets.set(sha256(ticket), {id: account.id, nonce: sha256(nonce), expiry: Date.now() + CLIENT_TICKET_MS});
reply(200, {url: new URL(`/account/client?ticket=${ticket}`, config.siteUrl).href, username: account.username});
return;
}
}
// ... and the ticket, opened by the client in the browser: signed in when
// this browser started it (its cookie). a ticket is good once, whatever
// happens. the page that follows says how it went.
if (route === "GET /account/client") {
const given = String(url.searchParams.get("ticket") || "");
const ticket = /^[0-9a-f]{48}$/.test(given) ? clientTickets.get(sha256(given)) : null;
if (ticket) {
clientTickets.delete(sha256(given));
}
const nonce = (new RegExp(`(?:^|;\\s*)${CLIENT_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1];
const account = ticket && ticket.expiry > Date.now() ? accounts.byId(ticket.id) : null;
const result = !account ? "expired" : !nonce || sha256(nonce) !== ticket.nonce ? "elsewhere" : "ok";
const cookies = [clientCookie("", 0)];
if (result === "ok") {
clientStarts.delete(ticket.nonce);
accounts.recordLogin(account, "web", from.address);
accounts.save(account);
signIn(res, account, cookies);
}
else {
res.setHeader("Set-Cookie", cookies);
}
// a page of this site's own that goes on to the account page, rather than
// a redirect: the (SameSite=Strict) cookie then surely goes with it.
res.setHeader("Cache-Control", "no-store");
web.send(res, 200, `<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=/account?client=${result}"><title>Burrow</title>`,
"text/html; charset=utf-8");
return;
}
// back from Discord (lib/discord.js): the state and the nonce must be the
@@ -705,6 +901,28 @@ const handle = async (req, res, url, from, web) => {
case "GET /account/api/me":
reply(200, profile(account, from));
return;
// the item giver (above, and lib/admin.js): for the account signed in
// here only, as the in-game one is for the one playing; not while banned.
case "GET /account/api/giver":
case "GET /account/api/colour":
case "POST /account/api/give": {
if (banFor(account, from) || account.nameRejected) {
reply(403, {error: "Not now."});
return;
}
if (route === "GET /account/api/colour") {
const result = await admin.colourLookup(url.searchParams);
reply(result.status, result.body);
return;
}
if (req.method === "GET") {
reply(200, await admin.searchFor(account, url.searchParams));
return;
}
const result = admin.giveAs(account, body);
reply(result.status, result.body);
return;
}
// for the trade offer form: what the player could give, and what
// another player has up for trade.
case "GET /account/api/tradable": {
+215 -21
View File
@@ -7,6 +7,7 @@ const config = require("../config.js");
const accounts = require("./accounts.js");
const limits = require("./limits.js");
const imageModeration = require("./image-moderation.js");
const jpegPrint = require("./jpegprint.js");
// masterpieces: paintings from the Art Studio, framed and hung in a den
// (client side: game.artStudioPainting.ArtStudioPainting, the same in
@@ -45,6 +46,23 @@ const SCHEMA = `
likes TEXT NOT NULL,
image BLOB NOT NULL
);
-- every picture taken in, for the daily limit (pictures thrown away
-- unframed count too)
CREATE TABLE IF NOT EXISTS masterpiece_uploads (
creator_id INTEGER NOT NULL,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS masterpiece_uploads_by ON masterpiece_uploads (creator_id, created_at);
-- pictures a moderator or the admin approved once: the same picture
-- again, the same file (SHA-256) or the same painting saved and painted
-- again (its fingerprint, lib/jpegprint.js), is approved as it is framed
CREATE TABLE IF NOT EXISTS masterpiece_approved_pictures (
hash TEXT PRIMARY KEY,
approved_at INTEGER NOT NULL,
approved_by TEXT NOT NULL,
fingerprint BLOB,
thumb BLOB
);
`;
const UPLOADED = 0; // posted, not made into an item yet
@@ -79,19 +97,35 @@ const fileOf = id => path.join(folder(), `${id}.jpg`);
const GALLERY_SPOTS = 12; // PartyManager.setupMasterpiecesInRoom
const uploadsPerHour = limits.limiter(30, 3600000);
const DAY = 86400;
const AUTO_APPROVER = "auto"; // reviewedBy of a painting approved for a picture approved before
const now = () => Math.floor(Date.now() / 1000);
const db = () => accounts.database();
const known = new Map(); // id -> {id, creator, createdAt, status, frame, reviewedAt, reviewedBy, likes: [account ids]}
const known = new Map(); // id -> {id, creator, createdAt, status, frame, reviewedAt, reviewedBy, likes: [account ids], hash}
const approvedPictures = new Map(); // hash -> thumbnail of its fingerprint, or null: masterpiece_approved_pictures
const tokens = new Map(); // upload token -> {account id, expires (ms)}
const load = () => {
db().exec(SCHEMA);
// who approved it: a moderator's username, "admin", or null when nobody
// looked (review was off, or it was approved before this was kept).
if (!db().prepare("PRAGMA table_info(masterpieces)").all().some(column => column.name === "reviewed_by")) {
const columns = db().prepare("PRAGMA table_info(masterpieces)").all().map(column => column.name);
if (!columns.includes("reviewed_by")) {
db().exec("ALTER TABLE masterpieces ADD COLUMN reviewed_by TEXT");
}
// the picture's SHA-256 (hashOf) and fingerprint (lib/jpegprint.js), to know it again
if (!columns.includes("hash")) {
db().exec("ALTER TABLE masterpieces ADD COLUMN hash TEXT");
}
if (!columns.includes("fingerprint")) {
db().exec("ALTER TABLE masterpieces ADD COLUMN fingerprint BLOB");
}
const pictureColumns = db().prepare("PRAGMA table_info(masterpiece_approved_pictures)").all().map(column => column.name);
if (!pictureColumns.includes("fingerprint")) {
db().exec("ALTER TABLE masterpiece_approved_pictures ADD COLUMN fingerprint BLOB");
db().exec("ALTER TABLE masterpiece_approved_pictures ADD COLUMN thumb BLOB");
}
fs.mkdirSync(folder(), {recursive: true});
// pictures still in the table move out into files, once.
for (const row of db().prepare("SELECT id FROM masterpieces WHERE length(image) > 0").all()) {
@@ -99,16 +133,138 @@ const load = () => {
fs.writeFileSync(fileOf(row.id), Buffer.from(picture));
db().prepare("UPDATE masterpieces SET image = ? WHERE id = ?").run(NO_IMAGE, row.id);
}
for (const row of db().prepare("SELECT id, creator_id, created_at, status, frame, reviewed_at, reviewed_by, likes FROM masterpieces").all()) {
for (const row of db().prepare("SELECT id, creator_id, created_at, status, frame, reviewed_at, reviewed_by, likes, hash FROM masterpieces").all()) {
known.set(row.id, {id: row.id, creator: row.creator_id, createdAt: row.created_at, status: row.status, frame: row.frame,
reviewedAt: row.reviewed_at, reviewedBy: row.reviewed_by, likes: JSON.parse(row.likes)});
reviewedAt: row.reviewed_at, reviewedBy: row.reviewed_by, likes: JSON.parse(row.likes), hash: row.hash || null});
}
for (const row of db().prepare("SELECT hash, thumb FROM masterpiece_approved_pictures").all()) {
approvedPictures.set(row.hash, row.thumb ? Buffer.from(row.thumb) : null);
}
backfill();
};
const hashOf = image => crypto.createHash("sha256").update(image).digest("hex");
const printOf = painting => {
const row = db().prepare("SELECT fingerprint FROM masterpieces WHERE id = ?").get(painting.id);
return row && row.fingerprint ? Buffer.from(row.fingerprint) : null;
};
// the approved pictures (their hashes) that this picture is: the same file,
// or the same painting by its fingerprint.
const approvedMatches = (hash, print) => {
const found = approvedPictures.has(hash) ? [hash] : [];
if (print) {
const thumb = jpegPrint.thumbnail(print);
for (const [other, otherThumb] of approvedPictures) {
if (other !== hash && otherThumb && jpegPrint.thumbnailsClose(thumb, otherThumb)) {
const row = db().prepare("SELECT fingerprint FROM masterpiece_approved_pictures WHERE hash = ?").get(other);
if (row && row.fingerprint && jpegPrint.samePicture(print, Buffer.from(row.fingerprint))) {
found.push(other);
}
}
}
}
return found;
};
const pictureApproved = (hash, print) => Boolean(hash) && approvedMatches(hash, print).length > 0;
const notePictureApproved = (painting, print) => {
const thumb = print ? jpegPrint.thumbnail(print) : null;
db().prepare("INSERT OR IGNORE INTO masterpiece_approved_pictures (hash, approved_at, approved_by, fingerprint, thumb) VALUES (?, ?, ?, ?, ?)")
.run(painting.hash, painting.reviewedAt || now(), painting.reviewedBy, print, thumb);
if (!approvedPictures.has(painting.hash)) {
approvedPictures.set(painting.hash, thumb);
}
};
// paintings from before pictures were known again get their hash and
// fingerprint, a few at a time after start (each is a file read and some
// milliseconds of decoding, on the thread the game shares); those a person
// approved make their pictures approved ones.
const BACKFILL_BATCH = 20;
const backfill = () => {
const missing = db().prepare("SELECT id FROM masterpieces WHERE fingerprint IS NULL OR hash IS NULL").all().map(row => row.id);
const notedAgain = db().prepare("SELECT hash FROM masterpiece_approved_pictures WHERE fingerprint IS NULL").all().map(row => row.hash);
const step = () => {
for (const id of missing.splice(0, BACKFILL_BATCH)) {
const painting = known.get(id);
let image = null;
try {
image = painting ? fs.readFileSync(fileOf(id)) : null;
}
catch (err) {
image = null;
}
if (!image) {
continue;
}
painting.hash = hashOf(image);
const print = jpegPrint.fingerprint(image);
db().prepare("UPDATE masterpieces SET hash = ?, fingerprint = ? WHERE id = ?").run(painting.hash, print, id);
if (painting.status === APPROVED && painting.reviewedBy && painting.reviewedBy !== AUTO_APPROVER) {
notePictureApproved(painting, print);
}
}
// pictures approved before fingerprints were kept: from a painting of
// theirs, once every painting has its own
for (const hash of missing.length ? [] : notedAgain.splice(0, BACKFILL_BATCH)) {
const row = db().prepare("SELECT fingerprint FROM masterpieces WHERE hash = ? AND fingerprint IS NOT NULL").get(hash);
if (row) {
const print = Buffer.from(row.fingerprint);
const thumb = jpegPrint.thumbnail(print);
db().prepare("UPDATE masterpiece_approved_pictures SET fingerprint = ?, thumb = ? WHERE hash = ?").run(print, thumb, hash);
approvedPictures.set(hash, thumb);
}
}
if (missing.length || notedAgain.length) {
setTimeout(step, 200).unref();
}
};
if (missing.length || notedAgain.length) {
setTimeout(step, 1000).unref();
}
};
// why this account may not paint for a frame now, as words for the player,
// or null when it may: too new an account (asked at the easel, step 1), or
// as many new pictures in the last 24 hours as a day allows (asked of a
// picture not approved before, step 2). `whenFree` speaks of the wait.
const whenFree = seconds => {
const hours = Math.ceil(seconds / 3600);
return hours > 1 ? `in ${hours} hours` : `in ${Math.max(1, Math.ceil(seconds / 60))} minutes`;
};
const tooNew = account => {
const age = now() - (Number(account.createdAt) || 0);
if (age < config.masterpieceMinAccountAge) {
return `Accounts can make Masterpieces once they are a day old. Try again ${whenFree(config.masterpieceMinAccountAge - age)}.`;
}
return null;
};
const tooMany = account => {
const recent = db().prepare("SELECT created_at FROM masterpiece_uploads WHERE creator_id = ? AND created_at > ? ORDER BY created_at")
.all(account.id, now() - DAY);
const perDay = config.masterpiecesPerDay;
if (recent.length >= perDay) {
return `You can make ${perDay} new Masterpieces a day. Try again ${whenFree(recent[recent.length - perDay].created_at + DAY - now())}.`;
}
return null;
};
const needsReview = () => accounts.setting(REVIEW_SETTING) !== "0";
const setNeedsReview = on => accounts.setSetting(REVIEW_SETTING, on ? "1" : "0");
const forget = id => {
// `unapprove`: it was taken back by staff, so its picture is no longer one
// approved before (a painting thrown away unframed leaves it alone).
const forget = (id, unapprove = false) => {
const painting = known.get(id);
if (unapprove && painting && painting.hash) {
for (const hash of approvedMatches(painting.hash, printOf(painting))) {
db().prepare("DELETE FROM masterpiece_approved_pictures WHERE hash = ?").run(hash);
approvedPictures.delete(hash);
}
}
known.delete(id);
db().prepare("DELETE FROM masterpieces WHERE id = ?").run(id);
fs.rmSync(fileOf(id), {force: true});
@@ -126,6 +282,7 @@ const sweep = () => {
forget(painting.id);
}
}
db().prepare("DELETE FROM masterpiece_uploads WHERE created_at <= ?").run(now() - DAY);
};
setInterval(() => {
try {
@@ -136,8 +293,12 @@ setInterval(() => {
}
}, 600000).unref();
// A token for one upload by this account (step 1).
// A token for one upload by this account (step 1), or null when it is
// `tooNew`, which says why.
const issueToken = account => {
if (tooNew(account)) {
return null;
}
for (const [token, entry] of tokens) {
if (entry.account === account.id) {
tokens.delete(token);
@@ -189,20 +350,33 @@ const looksLikeJpeg = image => {
return false;
};
// step 2. resolves to the new painting's id, or null when the token is not
// good, the picture is not a JPEG of a sane size, or the account has posted
// too many.
// step 2. resolves to {uuid}, the new painting's id, or {uuid: null} when
// the token is not good, the picture is not a JPEG of a sane size, or the
// account has posted too many; with `refusal` and `maker` when the player
// should be told why.
const upload = async (token, image) => {
const entry = typeof token === "string" ? tokens.get(token) : null;
tokens.delete(token);
if (!entry || entry.expires < Date.now() || !Buffer.isBuffer(image) || image.length > MAX_IMAGE_BYTES || !looksLikeJpeg(image)
|| !uploadsPerHour.allow(entry.account)) {
return null;
return {uuid: null};
}
// a picture approved before is not a new one and does not count
const hash = hashOf(image);
const print = jpegPrint.fingerprint(image);
const approvedBefore = pictureApproved(hash, print);
const maker = accounts.byId(entry.account);
const refusal = maker && !approvedBefore ? tooNew(maker) || tooMany(maker) : null;
if (!maker || refusal) {
return {uuid: null, refusal, maker};
}
const safety = await imageModeration.scan(image);
if (safety.blocked) {
console.log(`[masterpieces] rejected unsafe upload from account ${entry.account}`);
return null;
return {uuid: null};
}
if (!approvedBefore) {
db().prepare("INSERT INTO masterpiece_uploads (creator_id, created_at) VALUES (?, ?)").run(entry.account, now());
}
// one painting at a time is between the easel and the frame.
for (const painting of [...known.values()]) {
@@ -210,12 +384,12 @@ const upload = async (token, image) => {
forget(painting.id);
}
}
const painting = {id: crypto.randomUUID(), creator: entry.account, createdAt: now(), status: UPLOADED, frame: 0, reviewedAt: null, reviewedBy: null, likes: []};
const painting = {id: crypto.randomUUID(), creator: entry.account, createdAt: now(), status: UPLOADED, frame: 0, reviewedAt: null, reviewedBy: null, likes: [], hash};
fs.writeFileSync(fileOf(painting.id), image);
db().prepare("INSERT INTO masterpieces (id, creator_id, created_at, status, frame, likes, image) VALUES (?, ?, ?, ?, ?, '[]', ?)")
.run(painting.id, painting.creator, painting.createdAt, painting.status, painting.frame, NO_IMAGE);
db().prepare("INSERT INTO masterpieces (id, creator_id, created_at, status, frame, likes, image, hash, fingerprint) VALUES (?, ?, ?, ?, ?, '[]', ?, ?, ?)")
.run(painting.id, painting.creator, painting.createdAt, painting.status, painting.frame, NO_IMAGE, hash, print);
known.set(painting.id, painting);
return painting.id;
return {uuid: painting.id};
};
// `by`: who approved it, when someone did.
@@ -239,11 +413,19 @@ const claimable = (account, id, frame) => {
};
// step 3, paid for: the painting is an item now. true when it is approved
// on the spot.
// on the spot: review is off, or its picture was approved before.
const claim = (id, frame) => {
const painting = known.get(String(id));
painting.frame = frame;
setStatus(painting, needsReview() ? PENDING : APPROVED);
if (!needsReview()) {
setStatus(painting, APPROVED);
}
else if (pictureApproved(painting.hash, printOf(painting))) {
setStatus(painting, APPROVED, AUTO_APPROVER);
}
else {
setStatus(painting, PENDING);
}
return painting.status === APPROVED;
};
@@ -278,14 +460,26 @@ const mayView = (id, address, addressOf) => {
return painting.status === APPROVED || Boolean(maker && addressOf(maker) && addressOf(maker) === address);
};
// `by`: the moderator's username, or "admin".
// `by`: the moderator's username, or "admin". its picture is approved from
// now on, and the same picture waiting in other paintings is approved with
// it. the paintings approved, none when `id` was not waiting.
const approve = (id, by) => {
const painting = get(id);
if (!painting || painting.status !== PENDING) {
return false;
return [];
}
setStatus(painting, APPROVED, by);
return true;
if (!painting.hash) {
return [painting];
}
const print = printOf(painting);
notePictureApproved(painting, print);
const twins = [...known.values()].filter(other => other.status === PENDING
&& (other.hash === painting.hash || (print && jpegPrint.samePicture(print, printOf(other)))));
for (const twin of twins) {
setStatus(twin, APPROVED, AUTO_APPROVER);
}
return [painting, ...twins];
};
// is a den item fit to be shown, traded and recycled? anything that is not
@@ -362,7 +556,7 @@ const frameList = listId =>
([LIST_FRAMES_OFFERED, LIST_FRAMES_IN_ORDER].includes(Number(listId)) ? FRAMES.flat() : null);
module.exports = {
load, issueToken, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, recentlyApproved, frameList,
load, issueToken, tooNew, upload, claimable, claim, get, image, mayView, approve, forget, itemApproved, itemFields, creatorOf, like, gallery, list, listsFor, recentlyApproved, frameList,
needsReview, setNeedsReview, madeBy,
PENDING, APPROVED, DEN_ITEM, TOKEN_DEN_ITEM, DIAMOND_DEF, MAX_IMAGE_BYTES,
};
+55 -14
View File
@@ -6,6 +6,7 @@ const defpacks = require("./defpacks.js");
const buddyGames = require("./buddygames.js");
const masterpieces = require("./masterpieces.js");
const dens = require("./dens.js");
const customItems = require("./customitems.js");
const limits = require("./limits.js");
const {activeAvatar, addClothing, sendClothingAdded} = require("./player.js");
@@ -16,10 +17,14 @@ const {activeAvatar, addClothing, sendClothingAdded} = require("./player.js");
// game: the room it runs in, the start signal, gem awards, and for some
// games a few messages of their own.
//
// lib/games.json is that table, put back together from what still names the
// ids: arcade-machine den items (gameDefId and a name), the room files (which
// id stands where), the names GameCardPopup has for each game class, and the
// achievement defs (which user vars a game counts in). entries:
// lib/games.json is that table, as a recording of the official game has it
// (its "mi" reply, made with tools/recorder.js): which class each id runs,
// in a window or in the room's place, its user vars and its pictures. it
// was first put back together from what still names the ids (arcade-machine
// den items, the room files, GameCardPopup's names, the achievement defs),
// which had some ids wrong: the print kits, the carnival games (run in the
// room, not in its place), Brady's lab, and the buddy games, given ids of
// other games' as nothing then named theirs. entries:
// id game def id
// swf the game's key in game.IncludeMinigames
// title its name; sent as the id of the localization string that says so
@@ -32,16 +37,16 @@ const {activeAvatar, addClothing, sendClothingAdded} = require("./player.js");
// icon media id of its picture in the HUD's Games window; the games with
// one are the ones that window lists
// buddy true: one of the eight games two players play from a player's
// card (lib/buddygames.js). their ids are ours: nothing in the
// client names them, and the official table is gone.
// card a buddy game's picture, on the card's game tab and in the
// invitation
// card (lib/buddygames.js)
// card the game's title picture on its "Play!" popup; a buddy game's
// in the invitation
//
// every other game is played alone (minPlayers = maxPlayers = 1): the
// multiplayer ones each have a protocol of their own between the players.
const games = new Map(require("./games.json").map(game => [game.id, game]));
const GAME_AFTERGLOW_MS = 15000; // how long a game's room id is still taken after leaving it (leave)
const IN_ROOM = 0;
const MAX_GEMS_PER_AWARD = 5000;
const MAX_MASTERY_PER_AWARD = 100;
@@ -83,7 +88,16 @@ const START = {
// which player is its own by the id (GemBreakerPlayer.init), and only
// that one aims and shoots.
seedAndPlayers: game => [serial(), game.players.length, ...game.players.flatMap(player => [player.id, 0])],
// Spider Zapper and Wind Rider (SpiderShooterPlayer.init,
// ParachuteGliderPlayer.init): each player's sfs id and where it starts.
// given only the seed they had no players, none of them their own:
// nothing could be shot, and nobody glided.
seedAndCrosshairs: game => [serial(), game.players.length,
...game.players.flatMap((player, at) => [player.id, CROSSHAIR_X + at * CROSSHAIR_GAP, CROSSHAIR_Y])],
};
const CROSSHAIR_X = 400;
const CROSSHAIR_GAP = 100;
const CROSSHAIR_Y = 300;
// the room games several players play together: "Multiplayer" on the
// game's waiting list (MinigameManager.setupWaitListPopup), for players in
@@ -121,8 +135,8 @@ module.exports = ({tell, leaveRoom, findOnline, blocks, watchers}) => {
game.buddy ? 2 : MULTIPLAYER[game.swf] ? MULTIPLAYER[game.swf].max : 1,
0, // max spectators
game.type,
// the game card: the title picture on the "play" popup (not known), and
// for a buddy game the picture in the invitation.
// the game card: the title picture on the "play" popup, and for a buddy
// game the picture in the invitation.
game.card || 0,
...(game.vars || [0, 0, 0]),
game.buddy ? 1 : 0, // ready for player-versus-player: listed on players' cards
@@ -234,6 +248,10 @@ module.exports = ({tell, leaveRoom, findOnline, blocks, watchers}) => {
return;
}
session.game = null;
// an in-room game may say it is done just before it hands over what it
// made (the Juice Bar's smoothie, the Cocoa Hut's drink: an attachment,
// lib/world.js pubMsg), labelled with the game's room
session.lastGame = {roomId: game.roomId, until: Date.now() + GAME_AFTERGLOW_MS};
if (session.bubbleOffOwed) {
bubbleOff(session);
}
@@ -408,8 +426,12 @@ module.exports = ({tell, leaveRoom, findOnline, blocks, watchers}) => {
// den items a claw machine can drop: the plushies, of the machine's own
// animal when it is named for one ("The Wolf Claw").
let plushies = null;
// the game's own den items only: a custom item (and a player's own, which
// is nobody else's to win) may be missing from the winner's game, whose
// prize popup then threw (DenItem.initShopItem) and left the game frozen.
const gameOwnDenItemIds = () => defpacks.denItemIds().filter(id => id < customItems.FIRST_ID);
const clawPrizes = game => {
plushies = plushies || defpacks.denItemIds().filter(id => /plush/i.test(defpacks.denItemDef(id).abbrName));
plushies = plushies || gameOwnDenItemIds().filter(id => /plush/i.test(defpacks.denItemDef(id).abbrName));
const item = defpacks.denItemIds().map(id => defpacks.denItemDef(id)).find(def => Number(def.gameDefId) === game.id);
const animal = item ? /^ArcCraneGame(.+)$/.exec(item.abbrName) : null;
const own = animal ? plushies.filter(id => defpacks.denItemDef(id).abbrName.toLowerCase().includes(animal[1].toLowerCase())) : [];
@@ -420,7 +442,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks, watchers}) => {
// machines aside.
let phantomItems = null;
const invasionPrizes = () => {
phantomItems = phantomItems || defpacks.denItemIds().filter(id => /phantom/i.test(defpacks.denItemDef(id).abbrName)
phantomItems = phantomItems || gameOwnDenItemIds().filter(id => /phantom/i.test(defpacks.denItemDef(id).abbrName)
&& !/^Arc/.test(defpacks.denItemDef(id).abbrName) && defpacks.string(defpacks.denItemDef(id).nameStrId));
return phantomItems.length ? phantomItems : defpacks.denItemIds().slice(0, 1);
};
@@ -464,8 +486,15 @@ module.exports = ({tell, leaveRoom, findOnline, blocks, watchers}) => {
},
};
// refused to an account under a day old: the game shows its "could not
// send" popup, and a plain message box ("xtl") says why.
const uploadToken = (session, game, [, purpose], reply) => {
reply("tkn", 1, 0, masterpieces.issueToken(session.account), 0, purpose === undefined ? 1 : Number(purpose) || 1);
const token = masterpieces.issueToken(session.account);
if (!token) {
const why = masterpieces.tooNew(session.account) || "Your Masterpiece could not be sent. Try again later.";
session.sendXt("xtl", -1, why.replace(/%/g, " percent"));
}
reply("tkn", token ? 1 : 0, 0, token || "", 0, purpose === undefined ? 1 : Number(purpose) || 1);
};
// what a game asks of the server while it runs, by game class and then by
@@ -543,7 +572,7 @@ module.exports = ({tell, leaveRoom, findOnline, blocks, watchers}) => {
WindRider: {
go() {},
gw(session, game, params, reply) {
const ids = defpacks.clothingIds();
const ids = defpacks.clothingIds().filter(id => id < customItems.FIRST_ID);
const def = Math.random() < SKY_HIGH_PRIZE_CHANCE ? defpacks.itemDef(ids[Math.floor(Math.random() * ids.length)]) : null;
session.gamePrize = def ? {def: Number(def.id), color: Number(String(def.colors).split(",")[0])} : null;
reply("gw", def ? "1" : "0", def ? def.id : 0, 0, def ? session.gamePrize.color : 0);
@@ -581,6 +610,18 @@ module.exports = ({tell, leaveRoom, findOnline, blocks, watchers}) => {
},
// the touch pool: the same again, with six prizes; which one is in the
// first number.
// Spider Zapper, after each wave: "wave" [1 if the player shot enough,
// else 0] -> "wavesuccess" (the next wave) or "wavefail" (the end), and
// "waveend" [spiders shot] -> "waveend" [spiders shot] (its results).
// they went unanswered and the game waited after the first wave.
SpiderShooter: {
wave(session, game, [passed], reply) {
reply(passed === "1" ? "wavesuccess" : "wavefail");
},
waveend(session, game, [shot], reply) {
reply("waveend", /^\d{1,4}$/.test(String(shot)) ? Number(shot) : 0);
},
},
TouchPool: {
ts(session, game, params, reply) {
session.prizeSerial = serial();
+20 -2
View File
@@ -18,13 +18,23 @@ const SCHEMA = `
`;
const MAX_DETAIL = 400;
const SHOWN = 300;
const listeners = new Set();
const load = () => accounts.database().exec(SCHEMA);
const record = (by, action, target = "", detail = "") => {
const entry = {at: Math.floor(Date.now() / 1000), by: String(by), action: String(action), target: String(target), detail: String(detail).slice(0, MAX_DETAIL)};
accounts.database().prepare("INSERT INTO mod_log (at, by, action, target, detail) VALUES (?, ?, ?, ?, ?)")
.run(Math.floor(Date.now() / 1000), by, action, String(target), String(detail).slice(0, MAX_DETAIL));
.run(entry.at, entry.by, entry.action, entry.target, entry.detail);
console.log(`[mod] ${logText(by)}: ${logText(action)}${logText(target ? ` "${target}"` : "")}`);
for (const listener of listeners) {
try {
listener(entry);
}
catch (err) {
console.error(`[modlog] listener failed: ${logText(err.message)}`);
}
}
};
const recent = () => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log ORDER BY id DESC LIMIT ?").all(SHOWN);
@@ -33,4 +43,12 @@ const recent = () => accounts.database().prepare("SELECT at, by, action, target,
const about = username => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log WHERE target = ? COLLATE NOCASE ORDER BY id DESC LIMIT 100")
.all(String(username));
module.exports = {load, record, recent, about};
// Optional integrations subscribe here rather than wrapping record(), so an
// unavailable Discord channel can never stop a moderation action or its DB
// audit record from being written.
const onRecord = listener => {
listeners.add(listener);
return () => listeners.delete(listener);
};
module.exports = {load, record, recent, about, onRecord};
+203 -16
View File
@@ -30,6 +30,7 @@ const sfs = require("./sfs.js");
const support = require("./support.js");
const totp = require("./totp.js");
const world = require("./world.js");
const {logText} = require("./logtext.js");
// the moderator panel at /mod: what a moderator needs to look after the
// players, and no more. it is apart from the admin panel (lib/panel.js),
@@ -66,7 +67,17 @@ const PROJECT_ROOT = path.resolve(__dirname, "..");
const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_MINUTES_MS);
const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator
const sessions = new Map(); // SHA-256 of a session token -> {id: account id, expiry: ms}
// SHA-256 of a session token -> {id: account id, expiry: ms, code}. `code`:
// a 2FA code was given for it (the password sign-in, and Discord's with a
// code after it), which the Discord bot's commands need (discordCommandActor).
const sessions = new Map();
// a Discord sign-in waiting for its 2FA code: SHA-256 of the token in its
// cookie -> {id, expiry, tries}. Discord says who it is; the code says it is
// still them, as the password sign-in asks.
const pendingDiscord = new Map();
const PENDING_COOKIE = "ajc_mod_pending";
const PENDING_MINUTES = 5;
const PENDING_TRIES = 5;
const addressSearched = new Map(); // moderator's account id -> the address they last searched for
const sha256 = text => crypto.createHash("sha256").update(text).digest("hex");
@@ -127,7 +138,12 @@ const cookieHeader = (token, maxAgeSeconds) =>
const discordCookie = (value, maxAgeSeconds) =>
`${DISCORD_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const beginSession = (account, res, address, detail = "") => {
const pendingCookieHeader = (token, maxAgeSeconds) =>
`${PENDING_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const pendingToken = req => (new RegExp(`(?:^|;\\s*)${PENDING_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1] || null;
// `extraCookies` go out with the session's own.
const beginSession = (account, res, address, detail = "", code = true, extraCookies = []) => {
accounts.recordLogin(account, "mod", address);
accounts.save(account);
for (const [hash, session] of sessions) {
@@ -136,8 +152,8 @@ const beginSession = (account, res, address, detail = "") => {
}
}
const token = crypto.randomBytes(24).toString("hex");
sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000});
res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600));
sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000, code});
res.setHeader("Set-Cookie", [cookieHeader(token, SESSION_HOURS * 3600), ...extraCookies]);
modlog.record(account.username, "signed in", "", detail);
};
@@ -159,6 +175,11 @@ const forget = account => {
sessions.delete(hash);
}
}
for (const [hash, pending] of pendingDiscord) {
if (pending.id === account.id) {
pendingDiscord.delete(hash);
}
}
};
const playerRow = (account, playing) => {
@@ -395,7 +416,7 @@ const PAGE_HEADERS = {
"X-Frame-Options": "DENY",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
"Content-Security-Policy": captcha.policy("default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; "
"Content-Security-Policy": captcha.policy("default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; media-src 'self'; font-src 'self'; "
+ "form-action 'none'; frame-ancestors 'none'; base-uri 'none'"),
};
@@ -433,13 +454,22 @@ const handle = async (req, res, url, from, web) => {
result.ok = false;
result.error = "denied";
}
// Discord has said who this is; the panel opens once their 2FA code is
// given too (POST /mod/api/discord/code), so a Discord account alone,
// taken over or linked by someone else, opens nothing.
const cookies = [discordCookie("", 0)];
if (result.ok) {
beginSession(result.account, res, from.address, "through Discord");
console.log(`[mod] ${result.account.username} signed in with Discord from ${from.address}`);
for (const [hash, pending] of pendingDiscord) {
if (pending.expiry < Date.now()) {
pendingDiscord.delete(hash);
}
}
const token = crypto.randomBytes(24).toString("hex");
pendingDiscord.set(sha256(token), {id: result.account.id, expiry: Date.now() + PENDING_MINUTES * 60000, tries: 0});
cookies.push(pendingCookieHeader(token, PENDING_MINUTES * 60));
}
const sessionCookie = res.getHeader("Set-Cookie");
res.setHeader("Set-Cookie", sessionCookie ? [sessionCookie, discordCookie("", 0)] : discordCookie("", 0));
res.writeHead(302, {Location: `/dashboard/staff?discord=${result.ok ? "ok" : result.error}`});
res.setHeader("Set-Cookie", cookies);
res.writeHead(302, {Location: `/dashboard/staff?discord=${result.ok ? "code" : result.error}`});
res.end();
return;
}
@@ -503,12 +533,52 @@ const handle = async (req, res, url, from, web) => {
}
}
const token = crypto.randomBytes(24).toString("hex");
sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000});
sessions.set(sha256(token), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000, code: true});
res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600));
modlog.record(account.username, "signed in");
reply(200, {ok: true, username: account.username});
return;
}
// the second half of a Discord sign-in (GET /mod/discord/callback): the
// account's 2FA code, from the browser Discord sent back here. a few
// wrong codes and the sign-in is gone; it must start again at Discord.
case "POST /mod/api/discord/code": {
if (!from.local && failuresByAddress.blocked(from.key)) {
reply(429, {error: "Too many attempts. Try later."});
return;
}
const token = pendingToken(req);
const hash = token ? sha256(token) : null;
const pending = hash ? pendingDiscord.get(hash) : null;
const account = pending && pending.expiry > Date.now() ? accounts.byId(pending.id) : null;
if (!account || !mayModerate(account)) {
if (hash) {
pendingDiscord.delete(hash);
}
res.setHeader("Set-Cookie", pendingCookieHeader("", 0));
reply(401, {error: "The Discord sign-in expired. Sign in with Discord again.", expired: true});
return;
}
if (!totp.verify(account, String(body.code || ""))) {
failuresByAddress.record(from.key);
accounts.recordLogin(account, "mod", from.address, false);
accounts.save(account);
pending.tries++;
if (pending.tries >= PENDING_TRIES) {
pendingDiscord.delete(hash);
res.setHeader("Set-Cookie", pendingCookieHeader("", 0));
reply(401, {error: "Too many wrong codes. Sign in with Discord again.", expired: true});
return;
}
reply(401, {error: "Wrong code."});
return;
}
pendingDiscord.delete(hash);
beginSession(account, res, from.address, "through Discord", true, [pendingCookieHeader("", 0)]);
console.log(`[mod] ${logText(account.username)} signed in with Discord and a code from ${logText(from.address)}`);
reply(200, {ok: true, username: account.username});
return;
}
// signed in through the game instead: a client the moderator is playing
// in hands over the game's login token, so they need not type their
// password and a code again. taken only for active staff with 2FA on
@@ -547,7 +617,8 @@ const handle = async (req, res, url, from, web) => {
}
}
const cookie = crypto.randomBytes(24).toString("hex");
sessions.set(sha256(cookie), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000});
// no code given here, so not one the Discord bot's commands count
sessions.set(sha256(cookie), {id: account.id, expiry: Date.now() + SESSION_HOURS * 3600000, code: false});
res.setHeader("Set-Cookie", cookieHeader(cookie, SESSION_HOURS * 3600));
modlog.record(account.username, "signed in", "", "through the game");
reply(200, {ok: true, username: account.username});
@@ -670,6 +741,17 @@ const handle = async (req, res, url, from, web) => {
return;
}
// the mod log (lib/modlog.js): what staff did, as the admin panel's
// Moderators page shows it.
if (route === "GET /mod/api/modlog") {
if (!roles.can(mod, "staff.log")) {
reply(403, {error: "Your role does not allow that."});
return;
}
reply(200, {log: modlog.recent()});
return;
}
// everything else shows players and what they did: not for a role that
// only makes things.
if (!roles.can(mod, "player.view")) {
@@ -885,10 +967,10 @@ const handle = async (req, res, url, from, web) => {
return;
}
// a painting judged: for the roles that judge what players make, and
// never their own or one by staff of their rank or above.
// a painting judged: for the roles that judge paintings, and never
// their own or one by staff of their rank or above.
case "POST /mod/api/masterpiece": {
if (!may("items.approve")) {
if (!may("masterpieces.approve")) {
return;
}
const id = String(body.id || "");
@@ -1073,4 +1155,109 @@ const moderators = () => accounts.all().filter(account => roles.roleOf(account))
.map(account => ({username: account.username, role: roles.roleOf(account), twoStep: totp.isOn(account), lastSeen: account.lastSeen || null}))
.sort((a, b) => a.username.localeCompare(b.username));
module.exports = {handle, forget, moderators, signedInAs, itemRoutes, reviewRoutes};
// The Discord bot is deliberately a small adapter over the panel rather than
// its own moderator system. Its actor is a Discord user id that is already
// linked to one Burrow account. From there these methods use the same role,
// rank, permission and action checks as POST /mod/api/act, and log every
// successful change under the staff member's normal Burrow username.
// whose Discord this is: the active staff member it is linked to, or null.
// it says who someone is (the bot leaves staff alone), not that they may act.
const discordActor = discordId => {
const account = accounts.all().find(candidate => candidate.discordId === String(discordId));
return mayModerate(account) ? account : null;
};
// who may use the bot's commands: the staff member above, while they are
// signed in to the panel with a code (a session above with `code`). a
// Discord account alone is not them, and a new password, signing out
// everywhere or 2FA turned off end those sessions (forget), and the bot's
// use with them.
const discordCommandActor = discordId => {
const account = discordActor(discordId);
if (!account) {
return null;
}
for (const session of sessions.values()) {
if (session.id === account.id && session.code && session.expiry > Date.now()) {
return account;
}
}
return null;
};
const discordError = (actor, permission) => !actor
? {error: "Link this Discord account to your active Burrow staff account, then sign in to the staff dashboard with your 2FA code. Discord commands work while that sign-in lasts (12 hours)."}
: !roles.can(actor, permission) ? {error: "Your Burrow role cannot do that."} : null;
const discordStatus = actor => {
const error = discordError(actor, "server.view");
if (error) {
return error;
}
const memory = process.memoryUsage();
const players = world.players();
return {ok: true, uptimeSeconds: Math.floor(process.uptime()), players: players.length,
rooms: new Set(players.map(player => player.room).filter(Boolean)).size,
reports: reports.openCount(), memoryMb: Math.round(memory.rss / 1048576)};
};
const discordPlayer = (actor, username) => {
const error = discordError(actor, "player.view");
if (error) {
return error;
}
const target = accounts.byName(String(username || "").trim());
return target ? {ok: true, player: playerDetail(target)} : {error: "No such player."};
};
const discordReports = actor => {
const error = discordError(actor, "player.view");
return error || {ok: true, reports: reports.list(false), open: reports.openCount()};
};
const discordStaff = actor => {
const error = discordError(actor, "staff.list");
return error || {ok: true, staff: moderators()};
};
const discordAnnounce = (actor, text) => {
const error = discordError(actor, "server.announce");
if (error) return error;
const message = String(text || "").trim().slice(0, 300);
if (!message) return {error: "The announcement is empty."};
const reached = world.announce(message);
modlog.record(actor.username, "Discord announcement", "", `${reached} player${reached === 1 ? "" : "s"}`);
return {ok: reached === 1 ? "Shown to 1 player." : `Shown to ${reached} players.`};
};
const discordHandleReport = (actor, id) => {
const error = discordError(actor, "player.warn");
if (error) {
return error;
}
const handled = reports.markHandled(Number(id));
if (handled) {
modlog.record(actor.username, "report dealt with", "", `#${Number(id)}`);
}
return handled ? {ok: "Marked as dealt with."} : {error: "No such report waiting."};
};
const discordAct = (actor, username, body) => {
if (!actor) {
return discordError(null);
}
const target = accounts.byName(String(username || "").trim());
if (!target) {
return {error: "No such player."};
}
const result = act(actor, target, body || {});
if (result.ok) {
modlog.record(actor.username, String(body.action), target.username, result.detail || "");
}
return result;
};
const discordBot = {actor: discordActor, commandActor: discordCommandActor, authorize: discordError, status: discordStatus, player: discordPlayer, reports: discordReports,
staff: discordStaff, announce: discordAnnounce, handleReport: discordHandleReport, act: discordAct};
module.exports = {handle, forget, moderators, signedInAs, itemRoutes, reviewRoutes, discordBot};
+1
View File
@@ -0,0 +1 @@
{"10":{"type":1033,"count":141,"entries":["9329","0","9326","0","9332","0","9330","0","9331","0","9327","0","9328","0","9167","0","9170","0","9172","0","9174","0","9175","0","9176","0","9013","0","9014","0","9015","0","9016","0","9017","0","4452","0","2702","0","4451","0","2706","0","4453","0","2762","0","2711","0","2716","0","2715","0","2723","0","2697","0","2717","0","4478","0","1250","0","1251","0","1354","0","1426","0","1627","0","5738","0","346","0","86","0","124","0","118","0","2805","0","2806","0","2807","0","2808","0","2809","0","2810","0","2811","0","2812","0","2813","0","2814","0","2815","0","2816","0","2817","0","2818","0","2819","0","2820","0","2821","0","2822","0","2823","0","2824","0","2825","0","2826","0","2827","0","2828","0","1","0","4547","0","4542","0","4544","0","4549","0","4540","0","4548","0","4538","0","4539","0","4541","0","4543","0","4545","0","4546","0","2708","0","4470","0","356","0","5077","0","5078","0","5079","0","2705","0","4457","0","4465","0","2703","0","2709","0","5092","0","5093","0","5094","0","5095","0","4856","0","2712","0","2713","0","2714","0","4477","0","6130","0","6138","0","4777","0","4778","0","4779","0","4780","0","4855","0","5980","0","5981","0","4435","0","4946","0","4460","0","4461","0","4462","0","2707","0","4454","0","5088","0","5089","0","5090","0","5091","0","4455","0","2700","0","1188","0","2704","0","4459","0","4467","0","4468","0","4469","0","4393","0","5073","0","5074","0","5075","0","5076","0","4410","0","5084","0","5085","0","5086","0","5087","0","4466","0","5080","0","5081","0","5082","0","5083","0"]},"16":{"type":1023,"count":50,"entries":["551","552","553","554","555","556","557","564","558","569","559","1831","573","560","578","561","576","562","563","579","565","1841","568","574","566","1845","567","570","577","575","1830","571","1844","1826","572","1835","1839","1832","1843","1829","1827","1842","1828","1846","1838","1833","1840","1836","1837","1834"]},"44":{"type":1033,"count":35,"entries":["13","0","11","0","2889","0","2896","0","1602","0","2886","0","1604","0","12","0","2877","0","2885","0","1603","0","2894","0","10","0","2899","0","2891","0","2876","0","376","0","2878","0","2879","0","2880","0","2881","0","2882","0","2884","0","2888","0","2898","0","2887","0","2890","0","377","0","2892","0","2893","0","2895","0","2900","0","378","0","2901","0","2902","0"]},"53":{"type":1033,"count":14,"entries":["1389","1603","1545","1600","1595","1601","1265","1604","1470","1599","1232","1790","2279","3726","2015","0","7061","18253","1185","912","1192","1571","1186","913","1187","914","6189","0"],"note":"not recorded: the Journey Book's pages, found among the media files by their jb_title parts, and each land's name"},"54":{"type":1035,"count":160,"entries":["634","7044","32198","32199","10","459","0","635","7045","32200","32201","10","459","1","636","7046","32202","32203","10","459","2","637","7047","32204","32205","10","459","3","638","7048","32206","32207","10","459","4","639","7049","32208","32209","10","459","5","640","7050","32210","32211","10","459","6","641","7051","32212","32213","10","459","7","642","7052","32214","32215","10","459","8","643","7053","32216","32217","10","459","9","606","6667","31309","31310","14","457","0","607","6666","31311","31312","14","457","1","608","6668","31313","31314","14","457","2","609","6670","31303","31304","14","457","3","610","6665","31307","31308","14","457","4","611","6669","31305","31306","14","457","5","578","6180","30096","30097","14","456","11","577","6181","30094","30095","14","456","10","576","6187","30092","30093","14","456","9","575","6186","30090","30091","14","456","8","574","6179","30088","30089","14","456","7","573","6178","30086","30087","14","456","6","572","6177","30084","30085","14","456","5","571","6176","30082","30083","14","456","4","570","6183","30080","30081","14","456","3","569","6182","30078","30079","14","456","2","568","6185","30076","30077","14","456","1","567","6184","30074","30075","14","456","0","140","775","812","848","10","289","0","141","777","814","850","10","289","1","142","780","817","853","10","289","2","143","125","808","844","10","289","3","144","776","813","849","10","289","4","145","772","809","845","10","289","5","146","774","811","847","10","289","6","147","778","815","851","10","289","7","148","781","818","854","10","289","8","149","779","816","852","10","289","9","150","773","810","846","10","289","10","151","815","832","868","10","291","0","152","821","840","876","10","291","1","153","817","834","871","10","291","2","154","824","843","883","10","291","3","155","820","839","875","10","291","4","156","819","838","873","10","291","5","157","818","835","872","10","291","6","158","822","841","879","10","291","7","159","823","842","880","10","291","8","160","816","833","869","10","291","9","161","784","821","857","10","290","0","162","786","823","859","10","290","1","163","813","830","866","10","290","2","164","788","825","861","10","290","3","165","783","820","856","10","Line truncated
+216 -10
View File
@@ -9,6 +9,7 @@ const achievements = require("./achievements.js");
const adopt = require("./adopt.js");
const badges = require("./badges.js");
const discordLinks = require("./discord.js");
const discordBot = require("./discordbot.js");
const bans = require("./bans.js");
const colours = require("./colours.js");
const chatlog = require("./chatlog.js");
@@ -31,6 +32,7 @@ const support = require("./support.js");
const totp = require("./totp.js");
const manage = require("./manage.js");
const world = require("./world.js");
const codes = require("./codes.js");
const {activeAvatar} = require("./player.js");
// the admin panel at /admin: the only place the server is administered from.
@@ -91,6 +93,11 @@ const passwordAcceptable = password =>
typeof password === "string" && password.length >= MIN_PASSWORD_LENGTH && password.length <= MAX_PASSWORD_LENGTH;
const load = () => {
// the number of worlds the admin chose last (world.setWorldCount)
const worlds = accounts.setting(world.WORLD_COUNT_SETTING);
if (worlds !== null) {
world.setWorldCount(worlds, false);
}
if (!hasPassword()) {
setupCode = crypto.randomBytes(5).toString("hex");
console.log(`[admin] no admin password yet: open ${logText(config.baseUrl)}admin to choose one`
@@ -118,7 +125,22 @@ const cookieHeader = (token, maxAgeSeconds) =>
const discordCookie = (value, maxAgeSeconds) =>
`${DISCORD_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const signIn = res => {
// a Discord sign-in waiting for the 2FA code of the account it is linked
// to: SHA-256 of the token in its cookie -> {id, expiry, tries}. Discord
// alone does not open this panel, as the password alone does not open the
// moderator panel.
const pendingDiscord = new Map();
const PENDING_COOKIE = "ajc_admin_pending";
const PENDING_MINUTES = 5;
const PENDING_TRIES = 5;
const pendingCookieHeader = (token, maxAgeSeconds) =>
`${PENDING_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const pendingToken = req => (new RegExp(`(?:^|;\\s*)${PENDING_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1] || null;
// may this account still sign in here with Discord?
const discordAdmin = account => Boolean(account && account.adminDashboardAccess && account.discordId && totp.isOn(account) && !account.locked);
// `extraCookies` go out with the session's own.
const signIn = (res, extraCookies = []) => {
for (const [hash, expiry] of sessions) {
if (expiry < Date.now()) {
sessions.delete(hash);
@@ -126,7 +148,7 @@ const signIn = res => {
}
const token = crypto.randomBytes(24).toString("hex");
sessions.set(sha256(token), Date.now() + SESSION_HOURS * 3600000);
res.setHeader("Set-Cookie", cookieHeader(token, SESSION_HOURS * 3600));
res.setHeader("Set-Cookie", [cookieHeader(token, SESSION_HOURS * 3600), ...extraCookies]);
};
const signOut = (req, res) => {
@@ -149,6 +171,7 @@ const accountRow = (account, playing) => {
twoStep: totp.isOn(account),
discord: account.discord,
adminDashboardAccess: Boolean(account.adminDashboardAccess),
guide: account.guideGiven === true,
bio: account.bio,
badges: account.badges,
featuresOff: accounts.FEATURES.filter(name => !accounts.featureOn(account, name)),
@@ -283,6 +306,12 @@ const ROOM_GROUP_NOTES = {
adventures: "adventure maps; nothing in them moves",
};
// the theatre's browser (experimental; the server's game.html and client
// 1.3.3): off unless the admin turns it on. what players see in it never
// reaches the server; this only says whether the game offers it.
const THEATRE_BROWSER_SETTING = "theatreBrowser";
const theatreBrowserOn = () => accounts.setting(THEATRE_BROWSER_SETTING) === "on";
const debugState = () => ({
players: world.players().map(player => player.username).sort((a, b) => a.localeCompare(b)),
rooms: defpacks.roomPaths().map(roomPath => {
@@ -290,6 +319,9 @@ const debugState = () => ({
return {path: roomPath, group, note: ROOM_NOTES[roomPath] || ROOM_GROUP_NOTES[group] || ""};
}).sort((a, b) => a.path.localeCompare(b.path)),
everythingOnSale: sales.everythingOnSale(),
theatreBrowser: theatreBrowserOn(),
worlds: config.shards.length,
maxWorlds: config.worldNames.length,
});
const debugAct = body => {
@@ -307,6 +339,17 @@ const debugAct = body => {
? "Sale dates are off: every item shows, for players who start the game from now on."
: "Sale dates are back on, for players who start the game from now on."};
}
if (body.action === "worlds") {
const count = world.setWorldCount(body.count);
return count ? {ok: `${count} ${count === 1 ? "world" : "worlds"}: ${config.shards.map(shard => shard.name).join(", ")}.`}
: {error: "A number of worlds, please."};
}
if (body.action === "theatreBrowser") {
accounts.setSetting(THEATRE_BROWSER_SETTING, body.on === true ? "on" : "off");
return {ok: body.on === true
? "The theatre browser is on, for players on client 1.3.3 or newer once their game page loads again."
: "The theatre browser is off, once players' game pages load again."};
}
return {error: "Unknown debug action."};
};
@@ -382,6 +425,13 @@ const gift = (account, body) => {
const MAX_QUEST_LEVEL = 100;
// a password for a player who lost theirs: read out or pasted to them, so
// nothing that looks like something else (0 O, 1 l I).
const TEMP_PASSWORD_LETTERS = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
const TEMP_PASSWORD_LENGTH = 12;
const randomPassword = () => Array.from({length: TEMP_PASSWORD_LENGTH},
() => TEMP_PASSWORD_LETTERS[crypto.randomInt(TEMP_PASSWORD_LETTERS.length)]).join("");
const wholeNumber = (value, min, max) => (Number.isInteger(value) && value >= min && value <= max ? value : null);
// returns {ok: text} or {error: text}.
@@ -534,6 +584,36 @@ const act = (account, body) => {
`+${(account.permGrants || []).join(",") || "none"} -${(account.permDenies || []).join(",") || "none"}`);
return {ok: `${name}'s permissions are saved.`};
}
// guide: lets the player log in as one (lib/accounts.js setLoginChoices).
// it shows from their next login.
// lost access: a new random password, shown here once. it signs them out
// everywhere (lib/accounts.js setPassword); with `twoStepOff` their 2FA
// goes as well, for a lost authenticator.
case "tempPassword": {
let password = randomPassword();
// the account rules want a capital, a small letter and a digit, and no
// common word or the username in it: draw again until it has them.
while (accounts.setPassword(account, password)) {
password = randomPassword();
}
const twoStepOff = body.twoStepOff === true && totp.isOn(account);
if (twoStepOff) {
totp.turnOff(account);
}
accounts.save(account);
world.disconnect(account);
manage.forget(account);
modpanel.forget(account);
modlog.record("admin", "temporary password set", account.username, twoStepOff ? "2FA turned off" : "");
return {ok: `${name}'s password is now ${password}${twoStepOff ? " and their 2FA is off" : ""}. Ask them to change it on their account page.`, password};
}
case "guide": {
const on = body.on === true;
account.guideGiven = on;
accounts.save(account);
modlog.record("admin", on ? "made a guide" : "no longer a guide", account.username, "");
return {ok: on ? `${name} is a guide from their next login.` : `${name} is no longer a guide from their next login.`};
}
case "adminDashboardAccess": {
const on = body.on === true;
if (on && !account.discordId) {
@@ -600,7 +680,7 @@ const PAGE_HEADERS = {
"X-Frame-Options": "DENY",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
"Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; "
"Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; media-src 'self'; font-src 'self'; "
+ "form-action 'none'; frame-ancestors 'none'; base-uri 'none'",
};
@@ -640,13 +720,25 @@ const handle = async (req, res, url, from, web) => {
const nonce = (new RegExp(`(?:^|;\\s*)${DISCORD_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1];
const result = url.searchParams.get("error") ? {error: "cancelled"}
: await discordLinks.finishAdmin(url.searchParams.get("state"), nonce, url.searchParams.get("code"));
if (result.ok) {
signIn(res);
console.log(`[admin] ${logText(result.account.username)} signed in with Discord from ${logText(from.address)}`);
// Discord has said who this is; the panel opens once that account's 2FA
// code is given too (POST /admin/api/discord/code).
if (result.ok && !discordAdmin(result.account)) {
result.ok = false;
result.error = totp.isOn(result.account) ? "denied" : "twostep";
}
const adminCookie = res.getHeader("Set-Cookie");
res.setHeader("Set-Cookie", adminCookie ? [adminCookie, discordCookie("", 0)] : discordCookie("", 0));
res.writeHead(302, {Location: `/dashboard/admin?discord=${result.ok ? "ok" : result.error}`});
const cookies = [discordCookie("", 0)];
if (result.ok) {
for (const [hash, pending] of pendingDiscord) {
if (pending.expiry < Date.now()) {
pendingDiscord.delete(hash);
}
}
const token = crypto.randomBytes(24).toString("hex");
pendingDiscord.set(sha256(token), {id: result.account.id, expiry: Date.now() + PENDING_MINUTES * 60000, tries: 0});
cookies.push(pendingCookieHeader(token, PENDING_MINUTES * 60));
}
res.setHeader("Set-Cookie", cookies);
res.writeHead(302, {Location: `/dashboard/admin?discord=${result.ok ? "code" : result.error}`});
res.end();
return;
}
@@ -708,6 +800,44 @@ const handle = async (req, res, url, from, web) => {
return;
}
// the second half of a Discord sign-in: the linked account's 2FA code.
case "POST /admin/api/discord/code": {
if (tooManyFailures(from.key)) {
reply(429, {error: "Too many attempts. Try again in a few minutes."});
return;
}
const token = pendingToken(req);
const hash = token ? sha256(token) : null;
const pending = hash ? pendingDiscord.get(hash) : null;
const account = pending && pending.expiry > Date.now() ? accounts.byId(pending.id) : null;
if (!discordAdmin(account)) {
if (hash) {
pendingDiscord.delete(hash);
}
res.setHeader("Set-Cookie", pendingCookieHeader("", 0));
reply(401, {error: "The Discord sign-in expired. Sign in with Discord again.", expired: true});
return;
}
if (!totp.verify(account, String(body.code || ""))) {
recordFailure(from.key);
console.log(`[admin] wrong 2FA code after Discord for ${logText(account.username)} from ${logText(from.address)}`);
pending.tries++;
if (pending.tries >= PENDING_TRIES) {
pendingDiscord.delete(hash);
res.setHeader("Set-Cookie", pendingCookieHeader("", 0));
reply(401, {error: "Too many wrong codes. Sign in with Discord again.", expired: true});
return;
}
reply(401, {error: "Wrong code."});
return;
}
pendingDiscord.delete(hash);
signIn(res, [pendingCookieHeader("", 0)]);
console.log(`[admin] ${logText(account.username)} signed in with Discord and a code from ${logText(from.address)}`);
reply(200, {ok: true});
return;
}
case "POST /admin/api/logout":
signOut(req, res);
reply(200, {ok: true});
@@ -757,6 +887,65 @@ const handle = async (req, res, url, from, web) => {
reply(200, overview());
return;
case "GET /admin/api/discord":
reply(200, discordBot.dashboardStatus());
return;
case "POST /admin/api/discord/status": {
const statusCard = discordBot.setStatusSettings({title: body.title, note: body.note, banner: body.banner});
if (statusCard.error) {
reply(400, {error: statusCard.error});
return;
}
modlog.record("admin", "Discord public status card changed", "", `title: ${statusCard.title}, banner: ${statusCard.banner || "none"}`);
reply(200, {ok: "Status-card text saved. Use Publish now to update Discord.", statusCard});
return;
}
case "POST /admin/api/discord/status/publish": {
const result = await discordBot.publishStatus();
if (result.ok) {
modlog.record("admin", "Discord public status card published");
}
reply(result.ok ? 200 : 400, result);
return;
}
case "POST /admin/api/discord/config": {
const result = discordBot.updateDashboardConfig(body);
if (result.ok) {
modlog.record("admin", "Discord bot routing settings changed");
}
reply(result.ok ? 200 : 400, result);
return;
}
case "POST /admin/api/discord/security": {
const result = discordBot.updateSecuritySettings(body);
if (result.ok) {
modlog.record("admin", "Discord security settings changed");
}
reply(result.ok ? 200 : 400, result);
return;
}
case "POST /admin/api/discord/community": {
const result = discordBot.updateCommunitySettings(body);
if (result.ok) modlog.record("admin", "Discord community and ticket settings changed");
reply(result.ok ? 200 : 400, result);
return;
}
case "POST /admin/api/discord/control": {
const action = String(body.action || "");
const result = await discordBot.control(action);
if (result.ok) {
modlog.record("admin", `Discord bot ${action}`);
}
reply(result.ok ? 200 : 400, result);
return;
}
// a page of accounts by name (lib/staff.js says in what order), never
// all of them: with thousands, sending every one every few seconds
// slowed the page and the game alike.
@@ -936,6 +1125,23 @@ const handle = async (req, res, url, from, web) => {
return;
}
// codes for the game's Redeem Code window (lib/codes.js), each giving
// an item, gems or diamonds
case "GET /admin/api/codes":
reply(200, {codes: codes.list(), kinds: codes.KINDS});
return;
case "POST /admin/api/codes": {
const result = body.action === "remove"
? (codes.remove(body.code) ? {ok: "Code deleted."} : {error: "No such code."})
: codes.create(body);
if (result.ok) {
console.log(`[admin] redemption code ${logText(body.action === "remove" ? "deleted" : "made")}: ${logText(String(body.code || "").toUpperCase())}`);
}
reply(result.ok ? 200 : 400, result);
return;
}
// the message everyone is shown when they arrive; empty for none.
case "POST /admin/api/motd":
world.setMotd(String(body.text || ""));
@@ -1066,4 +1272,4 @@ const handle = async (req, res, url, from, web) => {
}
};
module.exports = {load, handle, signedIn, PASSWORD_SETTING};
module.exports = {load, handle, signedIn, theatreBrowserOn, PASSWORD_SETTING};
+38 -18
View File
@@ -3,7 +3,7 @@
const accounts = require("./accounts.js");
const achievements = require("./achievements.js");
const defpacks = require("./defpacks.js");
const {activeAvatar, isUint} = require("./player.js");
const {activeAvatar, activePet, isUint} = require("./player.js");
// pets (client side: PetManager, PetXtCommManager). A pet's species and look
// are packed into three integers by PetManager.packPetBits; the species is
@@ -30,6 +30,13 @@ const MASTERY_FULL = 100;
const MASTERY_PER_ROOM = 5;
const MASTERY_BITS = 0xF00; // the part of uBits PetInventory writes
const SECONDS_TO_HATCH = 259200; // PetManager.hasHatched
// not one of the game's: the pet chooser's "play as your pet" switch
// (gui.PetInventory), kept with the user vars so it reaches the client at
// login. on, whichever pet is out stands in for the avatar, in any room, as
// at a Play-As-Your-Pet party.
const USER_VAR_PET_FORM = 9008;
const inPetForm = account => Number(account.userVars[USER_VAR_PET_FORM]) === 1 && Boolean(activePet(account));
const random = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
@@ -106,6 +113,24 @@ module.exports = ({others, findOnline, petFields}) => {
const ownPet = (account, invIdx) => account.pets.find(candidate => candidate.inv === Number(invIdx));
// tells the player and everyone who sees them whether the pet stands in
// for the avatar (UserCommXtCommManager, user communication type 13).
const sendPetForm = session => {
if (session.pos) {
const state = inPetForm(session.account) ? "on" : "off";
for (const other of [session, ...others(session)]) {
other.sendXt("uc", session.room.id, session.id, state, "13");
}
}
};
// the pet chooser's switch. on with no pet out is kept for the next pet.
const setPetForm = (session, on) => {
achievements.set(session.account, USER_VAR_PET_FORM, on ? 1 : 0);
accounts.save(session.account);
sendPetForm(session);
};
const handlers = {
// PetManager.onPetListResponse: [found, username, count, (invIdx,
// createdTs, name, lBits, uBits, eBits, mastery, personality, toy, food,
@@ -146,15 +171,8 @@ module.exports = ({others, findOnline, petFields}) => {
session.sendXt("ps", -1, 0);
return;
}
const wasPetForm = inPetForm(account);
activeAvatar(account).petInvId = pet ? pet.inv : 0;
if (!pet && session.petPlayerMode) {
session.petPlayerMode = false;
if (session.pos) {
for (const other of [session, ...others(session)]) {
other.sendXt("uc", session.room.id, session.id, "off", "13");
}
}
}
accounts.save(account);
const messageRoom = session.room ? session.room.id : -1;
session.sendXt("ps", messageRoom, 1, session.id, pet ? pet.inv : 0);
@@ -163,6 +181,11 @@ module.exports = ({others, findOnline, petFields}) => {
other.sendXt("ps", messageRoom, 1, session.id, ...petFields(pet));
}
}
// with no pet out the avatar comes back; the next pet out takes its
// place again while the switch is on.
if (wasPetForm !== inPetForm(account)) {
sendPetForm(session);
}
},
// PetManager.onPetDismissResponse: [success, invIdx]
@@ -173,14 +196,10 @@ module.exports = ({others, findOnline, petFields}) => {
session.sendXt("pd", -1, 0, invIdx);
return;
}
const wasPetForm = inPetForm(account);
account.pets = account.pets.filter(candidate => candidate !== pet);
if (session.petPlayerMode && activeAvatar(account).petInvId === pet.inv) {
session.petPlayerMode = false;
if (session.pos) {
for (const other of [session, ...others(session)]) {
other.sendXt("uc", session.room.id, session.id, "off", "13");
}
}
if (wasPetForm && !inPetForm(account)) {
sendPetForm(session);
}
for (const avatar of account.avatars) {
if (avatar.petInvId === pet.inv) {
@@ -215,7 +234,8 @@ module.exports = ({others, findOnline, petFields}) => {
// EggPetHatchedPopup: [petInvIdx, nameId1, nameId2] names a pet hatched
// from an egg. PetManager.onPetEggNameResponse: [success, invIdx, name].
pn(session, roomId, [invIdx, name1, name2]) {
const pet = ownPet(session.account, invIdx);
const {account} = session;
const pet = ownPet(account, invIdx);
const def = pet && defpacks.petDef(pet.lBits & 0xFF);
if (!pet || ![name1, name2].every(isUint) || pet.name || !def || def.isEgg !== "1"
|| pet.createdAt + SECONDS_TO_HATCH > Math.floor(Date.now() / 1000)) {
@@ -250,5 +270,5 @@ module.exports = ({others, findOnline, petFields}) => {
},
};
return {handlers, walked, giveCharacter, favouritesList, personalityList, PERSONALITY_LIST};
return {handlers, walked, giveCharacter, favouritesList, personalityList, PERSONALITY_LIST, inPetForm, setPetForm};
};
+19 -2
View File
@@ -45,6 +45,7 @@ const MERGE_SECONDS = 10;
const perTenMinutes = limits.limiter(10, 600000);
const now = () => Math.floor(Date.now() / 1000);
const clean = (text, max) => String(text === undefined ? "" : text).replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, " ").trim().slice(0, max);
const listeners = new Set();
const load = () => accounts.database().exec(SCHEMA);
@@ -68,9 +69,18 @@ const file = ({reporter, target, reason, detail = "", context = "", room = ""})
if (!perTenMinutes.allow(reporter.toLowerCase()) || openCount() >= MAX_OPEN) {
return false;
}
db.prepare("INSERT INTO reports (created_at, reporter, target, reason, detail, context, room) VALUES (?, ?, ?, ?, ?, ?, ?)")
const inserted = db.prepare("INSERT INTO reports (created_at, reporter, target, reason, detail, context, room) VALUES (?, ?, ?, ?, ?, ?, ?)")
.run(now(), reporter, target, Number.isInteger(reason) ? reason : 0, clean(detail, MAX_DETAIL), clean(context, MAX_CONTEXT), clean(room, 100));
console.log(`[world] ${logText(reporter)} reported "${logText(target)}" (${logText(REASONS[reason] || `reason ${reason}`)})`);
const report = row(db.prepare("SELECT * FROM reports WHERE id = ?").get(Number(inserted.lastInsertRowid)));
for (const listener of listeners) {
try {
listener(report);
}
catch (err) {
console.error(`[reports] listener failed: ${logText(err.message)}`);
}
}
return true;
};
@@ -95,8 +105,15 @@ const list = (handled = false) => accounts.database()
const markHandled = id => accounts.database().prepare("UPDATE reports SET handled_at = ? WHERE id = ? AND handled_at IS NULL").run(now(), id).changes > 0;
// Lets optional integrations (the Discord bot) receive a newly filed report
// without making a report depend on an external service being available.
const onFile = listener => {
listeners.add(listener);
return () => listeners.delete(listener);
};
// the reports about one player, newest first, for their timeline.
const about = username => accounts.database().prepare("SELECT * FROM reports WHERE target = ? COLLATE NOCASE ORDER BY id DESC LIMIT 100")
.all(String(username)).map(row);
module.exports = {load, file, list, about, markHandled, openCount, MAX_DETAIL};
module.exports = {load, file, list, about, markHandled, onFile, openCount, MAX_DETAIL};
+37 -3
View File
@@ -16,6 +16,7 @@ const totp = require("./totp.js");
const PERMISSIONS = {
"server.view": "see read-only server health in the moderator panel",
"server.announce": "send an announcement to everyone playing",
"player.view": "see players, chat, reports, requests, bans and paintings in the moderator panel, and keep notes on players (!note, !notes)",
"staff.list": "see which staff are online (!staff)",
"player.warn": "warn a player, take a warning back, send them a message and mark a report dealt with (!warn, !unwarn, !warnings, !message)",
@@ -28,15 +29,18 @@ const PERMISSIONS = {
"player.names": "reject or accept a name, answer requests for a new one, clear a bio, remove a player's Jammer Wall posts",
"address.ban": "ban the address a player last signed in from, or the computers they use, and lift those bans",
"items.approve": "approve or turn away the items and pictures players make, when the admin has asked for that",
"masterpieces.approve": "approve or remove the paintings players frame as masterpieces (the Masterpieces page)",
"items.restrict": "stop a clothing item from being worn by selected animal types",
"items.create": "make new items from the game's art, change and delete them, lock items out of the item finder and take items from players (!item, !lock, !unlock, !locked, !take)",
"room.effects": "run temporary room-wide size and colour effects (!roomfx)",
"theater.control": "play or stop a YouTube video for everyone in the theatre",
"music.upload": "upload MP3s as den music tracks, and delete those uploaded (the Music page)",
"staff.log": "read the mod log: what staff did, in the panels and the game (the Mod log page)",
};
const HELPER = ["server.view", "player.view", "staff.list", "player.warn", "player.goto", "chat.silence"];
const MODERATOR = [...HELPER, "player.kick", "player.summon", "staff.invisible", "player.ban", "player.names", "address.ban", "items.approve", "items.restrict", "theater.control"];
const ADMIN = [...MODERATOR, "items.create", "room.effects"];
const MODERATOR = [...HELPER, "player.kick", "player.summon", "staff.invisible", "player.ban", "player.names", "address.ban", "items.approve", "masterpieces.approve", "items.restrict", "theater.control", "staff.log"];
const ADMIN = [...MODERATOR, "server.announce", "items.create", "room.effects", "music.upload"];
// a developer makes things, and moderates nobody.
const DEVELOPER = ["server.view", "staff.list", "items.create", "room.effects", "theater.control"];
@@ -116,6 +120,36 @@ const setRolePermissions = (role, list) => {
return true;
};
// masterpieces.approve was split from items.approve (2026-10-21), which
// judged paintings before. once: a role list the admin changed, and a staff
// member's own grants and denies, that held items.approve hold this too.
const SPLIT_SETTING = "permissionSplitMasterpieces";
const load = () => {
if (accounts.setting(SPLIT_SETTING)) {
return;
}
const withSplit = list => (Array.isArray(list) && list.includes("items.approve") && !list.includes("masterpieces.approve")
? [...list, "masterpieces.approve"] : list);
const changed = {...overrides()};
for (const role of Object.keys(changed)) {
changed[role] = withSplit(changed[role]);
}
accounts.setSetting(ROLE_SETTING, JSON.stringify(changed));
roleOverrides = changed;
for (const account of accounts.all()) {
if (account.permGrants || account.permDenies) {
const grants = withSplit(account.permGrants);
const denies = withSplit(account.permDenies);
if (grants !== account.permGrants || denies !== account.permDenies) {
if (grants) account.permGrants = grants;
if (denies) account.permDenies = denies;
accounts.save(account);
}
}
}
accounts.setSetting(SPLIT_SETTING, "1");
};
const permissionsOf = account => {
const role = roleOf(account);
if (!role) {
@@ -167,5 +201,5 @@ const setRole = (account, role) => {
return true;
};
module.exports = {PERMISSIONS, ROLES, roleOf, rankOf, isActiveStaff, permissionsOf, rolePermissions, roleChanged, setRolePermissions,
module.exports = {load, PERMISSIONS, ROLES, roleOf, rankOf, isActiveStaff, permissionsOf, rolePermissions, roleChanged, setRolePermissions,
setAccountPermissions, can, outranks, setRole};
+7 -3
View File
@@ -14,8 +14,9 @@ const defpacks = require("./defpacks.js");
// then AMF3), so reading it here costs no extra download once anyone has
// been in the room.
// what the room editor left in files nobody named.
const UNNAMED = "Display Name";
// what the room editor left in files nobody named ("default": the museum's
// theatre).
const UNNAMED = ["display name", "default"];
// rooms whose file has no name and whose path does not spell it either.
const NAMES = new Map([
["jamaa_township.room_diamonds", "Diamond Shop"],
@@ -24,6 +25,9 @@ const NAMES = new Map([
["aussie.room_main", "Kimbara Outback"],
["aussie.room_aushop", "Outback Imports"],
["aussie.room_hos", "Medical Center"],
["appondale.room_museumtheater", "Museum Theater"],
["crystal_sands.room_tiertheater", "Tierney's Theater"],
["lost_temple_of_zios.bb_theater", "Temple Theater"],
]);
const VOLUME_SHOP = 12; // ActorVolume.type: clicking it opens generic list `typeDefId`
@@ -37,7 +41,7 @@ const parse = body => {
const settings = (room.actors.ActorSettings || [])[0] || {};
const volumes = room.actors.ActorVolume || [];
return {
name: typeof settings.name === "string" && settings.name.trim() !== UNNAMED ? settings.name.trim() : "",
name: typeof settings.name === "string" && !UNNAMED.includes(settings.name.trim().toLowerCase()) ? settings.name.trim() : "",
shops: new Set(volumes.filter(volume => Number(volume.type) === VOLUME_SHOP).map(volume => Number(volume.typeDefId))),
};
};
+4 -4
View File
@@ -141,19 +141,19 @@ const byDevice = query => {
// other accounts the same person may have: those that used one of its
// computers (lib/devices.js), and those that signed in from one of its
// addresses in the last 90 days. [{username, devices: [kind], weak,
// addresses in the last 90 days. [{username, devices: [kind],
// addresses: count, online, banned}], the likeliest first. the addresses
// themselves are not given: moderators do not see them.
const altsOf = account => {
const found = new Map();
const entry = username => {
if (!found.has(username)) {
found.set(username, {username, devices: [], weak: false, addresses: 0});
found.set(username, {username, devices: [], addresses: 0});
}
return found.get(username);
};
for (const alt of devices.alts(account)) {
Object.assign(entry(alt.username), {devices: alt.kinds, weak: alt.weak});
Object.assign(entry(alt.username), {devices: alt.kinds});
}
const mine = new Set(account.logins.filter(login => login.ok && login.address && !limits.isLoopback(login.address)).map(login => login.address));
if (mine.size) {
@@ -170,7 +170,7 @@ const altsOf = account => {
const other = accounts.byName(alt.username);
return {...alt, online: Boolean(world.findOnline(alt.username)), banned: other ? world.moderation.banRemaining(other) : 0,
deviceBanned: other ? devices.bannedId(other) !== 0 : false};
}).sort((one, other) => Number(other.devices.length > 0 && !other.weak) - Number(one.devices.length > 0 && !one.weak)
}).sort((one, other) => Number(other.devices.length > 0) - Number(one.devices.length > 0)
|| other.devices.length - one.devices.length || other.addresses - one.addresses || one.username.localeCompare(other.username)).slice(0, 100);
};
+67
View File
@@ -0,0 +1,67 @@
"use strict";
const zlib = require("zlib");
const amf3 = require("./amf3.js");
// a room file of a seasonal theme comes from an older build (lib/http.js,
// roomAsSeenBy in lib/world.js), and so do its clickable spots: a shop there
// names the generic list it had then, which today's lists may have as
// something else or as nothing, so one theme's shops worked and another's
// did not. each spot the room has today too (by its name) is given today's
// list, kind and message; what only the old room has stays as it was.
// the volume fields that say what a click does (RoomManagerWorld: type 1 a
// minigame by typeDefId, 7 a message, 12 a generic list)
const ACTION_FIELDS = ["type", "typeDefId", "message"];
const MAX_KEPT = 40; // rooms remembered, made once each (files of up to a few MB)
const kept = new Map(); // old file's path -> the file with today's spots, or null for "as it was"
const volumes = room => (room && room.actors && Array.isArray(room.actors.ActorVolume) ? room.actors.ActorVolume : []);
const withTodaysSpots = (oldBody, currentBody) => {
const old = amf3.decode(zlib.inflateSync(oldBody));
const today = new Map(volumes(amf3.decode(zlib.inflateSync(currentBody))).filter(volume => volume && volume.name).map(volume => [volume.name, volume]));
let changed = false;
for (const volume of volumes(old)) {
const now = volume && today.get(volume.name);
if (now && ACTION_FIELDS.some(field => volume[field] !== now[field])) {
for (const field of ACTION_FIELDS) {
if (now[field] === undefined) {
delete volume[field];
}
else {
volume[field] = now[field];
}
}
changed = true;
}
}
return changed ? zlib.deflateSync(amf3.encode(old)) : oldBody;
};
// `oldBody` with today's spots, `current` giving today's file (or null);
// the old one as it was when that cannot be had or read.
const fix = async (key, oldBody, current) => {
if (kept.has(key)) {
return kept.get(key) || oldBody;
}
let body = oldBody;
try {
const currentBody = await current();
if (currentBody) {
body = withTodaysSpots(oldBody, currentBody);
}
}
catch (err) {
console.log(`[themes] ${key}: ${err.message}`);
body = oldBody;
}
if (kept.size >= MAX_KEPT) {
kept.delete(kept.keys().next().value);
}
kept.set(key, body === oldBody ? null : body);
return body;
};
module.exports = {fix};
+17 -7
View File
@@ -15,7 +15,7 @@ const TYPE_CLOTHING = 0;
const TYPE_DEN_ITEM = 1;
const TYPE_PET = 3;
const MAX_TRADE_ITEMS = 50;
const MAX_TRADE_ITEMS = 200; // on a trade list (the game sets no end to it; past this the rest were dropped)
const MAX_PETS = 1000; // as in lib/pets.js
// "ti" request steps (first parameter from the client)
@@ -53,8 +53,11 @@ module.exports = ({findOnline, blocks}) => {
// createdTs, lBits, uBits, eBits, name, personality, toy, food)...]
const sendTradeList = (to, account) => {
const listed = type => account.tradeList.filter(entry => entry.type === type).map(entry => entry.inv);
const clothing = account.items.filter(item => listed(TYPE_CLOTHING).includes(item.inv));
const denItems = account.denItems.filter(item => listed(TYPE_DEN_ITEM).includes(item.inv) && masterpieces.itemApproved(item));
// one whose def is gone (a custom item deleted) is left out: the client
// cannot make an item of it, and the list stopped there.
const clothing = account.items.filter(item => listed(TYPE_CLOTHING).includes(item.inv) && defpacks.itemDef(item.def));
const denItems = account.denItems.filter(item => listed(TYPE_DEN_ITEM).includes(item.inv) && masterpieces.itemApproved(item)
&& defpacks.denItemDef(item.def));
const pets = account.pets.filter(pet => listed(TYPE_PET).includes(pet.inv));
to.sendXt("tl", -1, account.username,
clothing.length, ...clothing.flatMap(item => [item.def, item.inv, item.color]),
@@ -71,8 +74,10 @@ module.exports = ({findOnline, blocks}) => {
(type === TYPE_CLOTHING ? account.items : type === TYPE_DEN_ITEM ? account.denItems : type === TYPE_PET ? account.pets : []);
// A masterpiece still waiting for review is nobody's to trade.
// nor one whose def is gone.
const find = (account, type, inv) => collectionOf(account, type)
.find(entry => entry.inv === inv && (type !== TYPE_DEN_ITEM || masterpieces.itemApproved(entry)));
.find(entry => entry.inv === inv && (type !== TYPE_DEN_ITEM || masterpieces.itemApproved(entry))
&& (type === TYPE_CLOTHING ? Boolean(defpacks.itemDef(entry.def)) : type === TYPE_DEN_ITEM ? Boolean(defpacks.denItemDef(entry.def)) : true));
// the field layouts differ between the offer the owner is shown (no
// inventory ids for clothing and den items) and the completed trade.
@@ -129,6 +134,10 @@ module.exports = ({findOnline, blocks}) => {
return coming === 0 || collectionOf(account, type).length + coming - gives.filter(item => item.type === type).length <= max;
});
const endTrade = trade => {
trade.requester.trade = trade.owner.trade = null;
};
// ends the trade `session` is part of, telling the other side with `status`.
const abandon = (session, status) => {
const {trade} = session;
@@ -136,7 +145,7 @@ module.exports = ({findOnline, blocks}) => {
return;
}
const other = trade.requester === session ? trade.owner : trade.requester;
trade.requester.trade = trade.owner.trade = null;
endTrade(trade);
other.sendXt("ti", -1, status, session.account.username, USERNAME_SHOWN);
};
@@ -250,7 +259,7 @@ module.exports = ({findOnline, blocks}) => {
return;
}
const {requester, owner, wantedType, wanted, offered} = trade;
requester.trade = owner.trade = null;
endTrade(trade);
// either side may have recycled or re-traded something while deciding.
const stillThere = collectionOf(owner.account, wantedType).includes(wanted)
&& offered.every(item => collectionOf(requester.account, item.type).includes(item.entry))
@@ -312,7 +321,8 @@ module.exports = ({findOnline, blocks}) => {
sendTradeList(session, account);
},
// ["1"/"0"]: busy flag while the trade window is open; nothing to answer.
// ["1"/"0"]: busy flag while the trade window is open; nothing to
// answer.
tb() {},
ti(session, roomId, params) {
+3 -2
View File
@@ -77,10 +77,11 @@ const whole = value => (Number.isInteger(Number(value)) ? Number(value) : 0);
// the photo booth picture ("pb", PlayerWallGui): one level deeper than the
// rest, {avatar: {id, color1.., eyes, pattern}, bgid, pet: {ts, lbits, ..} |
// null, items: [{id, color}, ..]}. it was turned away as too deep, and the
// owner's whole change with it: the photo never stayed.
// owner's whole change with it: the photo never stayed. an animal wearing
// nothing has no items list at all (null), which was turned away too.
const MAX_PHOTO_ITEMS = 30;
const photoParam = value => value === null || (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length <= 6
&& Object.entries(value).every(([key, part]) => (key === "items" ? Array.isArray(part) && part.length <= MAX_PHOTO_ITEMS && part.every(flat)
&& Object.entries(value).every(([key, part]) => (key === "items" ? part === null || (Array.isArray(part) && part.length <= MAX_PHOTO_ITEMS && part.every(flat))
: key === "avatar" || key === "pet" ? part === null || flat(part) : scalar(part))));
module.exports = ({blocks, findOnline}) => {
+336 -37
View File
@@ -19,12 +19,16 @@ const badges = require("./badges.js");
const bans = require("./bans.js");
const devices = require("./devices.js");
const chatlog = require("./chatlog.js");
const support = require("./support.js");
const codes = require("./codes.js");
const chatFilter = require("./chatfilter.js");
const chatSpam = require("./chatspam.js");
const chatStyles = require("./chatstyles.js");
const buddyModule = require("./buddies.js");
const dens = require("./dens.js");
const disguises = require("./disguises.js");
const ecardModule = require("./ecards.js");
const ecoModule = require("./eco.js");
const epicDens = require("./epicdens.js");
const itemHandlers = require("./items.js");
const minigameModule = require("./minigames.js");
@@ -48,6 +52,8 @@ const {CURRENCIES, DIAMOND_TYPES, activeAvatar, avatarById, activePet, equippedB
const GENERIC_LIST_AVATARS = 64;
const GENERIC_LIST_NEWSPAPER = 627;
const GENERIC_LIST_WHATS_NEW = 369;
const WHATS_NEW_PAGES = 6;
// the worlds' names (ServerSelector.getShardName): localization ids, the
// game's own river names, world N being the Nth.
const GENERIC_LIST_WORLD_NAMES = 16;
@@ -127,20 +133,50 @@ const DEF_COMBINED_LIST = 1060;
const DEF_DEN_ROOM = 1040;
const DEF_CURRENCY_EXCHANGE = 1051;
const DEF_DIAMOND = 1054;
// generic lists as the official server answered them (gl), recorded with
// tools/recorder.js: used where this server has none of its own. one was
// not recorded and is made up the same way: the Journey Book's pages (53),
// found among the media files (each has a "jb_title_<land>" part) with the
// name of each land, which opens the book at the page of the land the
// player is in (GuiManager.onJourneyBookMediaListReceived). likewise the
// books of the Chamber of Knowledge (EBookChooser, lists 353-356) and their
// pages, for the four whose pages could be found.
const OFFICIAL_LISTS = require("./official-lists.json");
const SHOP_LIST_TYPES = [DEF_ITEM, DEF_DEN_ITEM, DEF_DEN_ROOM, DEF_COMBINED_LIST, DEF_CURRENCY_EXCHANGE, DEF_DIAMOND];
// a shop's title when its room gives it none (a shop in a land's main room,
// or one opened from elsewhere): what it sells (strings in lib/defpacks.js).
// with no title the shop window's banner was blank.
// shops opened from a window rather than a room, by their list: the Eco Shop.
const SHOP_LIST_TITLES = new Map([[778, 35727]]);
const SHOP_KIND_TITLES = new Map([[DEF_ITEM, 9000010], [DEF_DEN_ITEM, 9000011], [DEF_DEN_ROOM, 9000012],
[DEF_COMBINED_LIST, 9000013], [DEF_CURRENCY_EXCHANGE, 9000014], [DEF_DIAMOND, 9000015]]);
// diamond lists the client reads at login to learn which animals and pets
// cost diamonds. they stay empty: animals and pets are free here.
const DIAMOND_ANIMAL_AND_PET_LISTS = [166, 214, 293];
// the Diamond Shop's two den displays ("one" and "two" in its room file).
// taken for the dens sold for diamonds: nothing else in the room is.
const DIAMOND_DEN_LIST = 196;
// the egg the egg stands sell (pet.EggPetGuiManager, list 624): one at
// random of these, the diamond shop's eggs. empty, the stand threw.
const DIAMOND_EGG_LIST = 624;
const LANG_ENG = 0;
const IDLE_ANIM_LAND = 14;
const IDLE_ANIM_OCEAN = 29;
const MAX_PATH_POINTS = 12;
// Action messages are client-side animation names (":dance:", ":sitNW:",
// etc.). Keep the currently playing one only while the avatar is standing
// still, so someone who enters the room can see it once their client has
// created that avatar.
const ACTION_NAME = /^:[A-Za-z][A-Za-z0-9]*:$/;
const TYPED_NAME = /^[A-Za-z0-9][A-Za-z0-9 '.-]{0,19}$/; // an animal's or pet's name typed by its owner
// a typed name the server's filter (lib/chat-filter.txt) stops. the game's
// own names are word ids ("123|456"), which it never does.
const nameFiltered = name => !String(name).includes("|") && Boolean(chatFilter.broken(String(name)));
const MAX_BLOCKED = 1000; // from the account page; the game's own button has no limit
const TYPED_CHAT_TYPES = ["0", "9"];
// UserCommXtCommManager's safe chat phrase (1), emote (2), action (3),
// attachment (4), slide (6) and pet action (7)
const MOMENTARY_TYPES = ["1", "2", "3", "4", "6", "7"];
const MAX_CHAT_EXTRA = 100; // the field after a chat line's type
const MAX_USER_VARS = 2000;
const MAX_FILTER_WORDS = 100; // a player's own words for their chat filter
@@ -154,8 +190,32 @@ const LOGIN_OUTDATED = -12;
const THEME_PATH_PREFIX = "theme_"; // lib/http.js looks for this
const chatLines = limits.limiter(config.chatLinesPerWindow, config.chatWindowMs);
const codeTries = limits.limiter(10, 60000); // codes typed, per account a minute
// emotes, actions, attachments: each goes to everyone in the room, so a
// player pressing one over and over slowed a busy room for all of them.
const roomActions = limits.limiter(config.roomActionsPerWindow, config.roomActionWindowMs);
const online = new Map(); // lowercased username -> session
const rooms = new Map(); // "path.name#shard" -> room
const gameActivityListeners = new Set();
// An intentionally small, privacy-safe activity feed for optional
// integrations. It names only the player and lifecycle event—never IPs,
// device identifiers, game tokens or chat text.
const gameActivity = entry => {
for (const listener of gameActivityListeners) {
try {
listener(entry);
}
catch (err) {
console.error(`[world] activity listener failed: ${logText(err.message)}`);
}
}
};
const onGameActivity = listener => {
gameActivityListeners.add(listener);
return () => gameActivityListeners.delete(listener);
};
// worlds (config.shards): a land room's name ends in "#<world>"; dens,
// parties and adventures have none and belong to no world. each player has
@@ -186,7 +246,13 @@ const sees = (viewer, subject) => (!subject.invisible || roles.isActiveStaff(vie
&& !(viewer.account.hideBlocked && blocks.has(viewer.account, subject.account));
// everyone else in the room who should hear about this player's animal.
const watchers = session => others(session).filter(other => sees(other, session));
// the game's feedback windows by type (FeedbackManager.frameLabelForType;
// the titles are the feedback defs' own), for the panel to say where a
// message came from
const FEEDBACK_KINDS = new Map([[1, "Theatre feedback"], [3, "Feedback"], [4, "Jamaa Journal feedback"], [5, "Feedback"],
[11, "Theatre feedback"], [18, "Jammer Wall feedback"], [19, "Chat feedback"], [21, "Theatre feedback"], [22, "Theatre feedback"]]);
const TYPING_EVERY_MS = 2000; // "typing" passed on at most this often per player (xty)
const WORLD_COUNT_SETTING = "worldCount"; // how many worlds the admin chose (setWorldCount)
// tags ("@name") in chat and on Jammer Walls (xmn): the longest player's
// name that the text after an "@" starts with, ending where a word does
@@ -261,7 +327,7 @@ const loginParams = session => {
playerWallSettings: account.wall.privacy,
// not 0: PlayerWallManager only opens walls for accounts with them on.
webWallStatus: 1,
eCardPrivacySettings: account.ecardPrivacy,
eCardPrivacySettings: ecards.privacyShown(account),
// not empty: with neither address set, every fifth login opens a
// "parent's email" window (GuiManager.showAjEmailBtn). accounts here
// have no email.
@@ -356,6 +422,17 @@ const login = (session, msg) => {
existing.close();
leaveWorld(existing);
}
// a name typed before the filter covered names, or one a newer rule
// catches: the animal takes the username, the pet is "Pet".
const filteredNames = [...account.avatars.filter(avatar => nameFiltered(avatar.name)),
...account.pets.filter(pet => nameFiltered(pet.name))];
if (filteredNames.length) {
for (const thing of filteredNames) {
console.log(`[filter] ${logText(account.username)}'s name "${logText(thing.name)}" cleared`);
thing.name = account.avatars.includes(thing) ? account.username : "Pet";
}
accounts.save(account);
}
session.account = account;
accounts.hold(account);
account.numLogins++;
@@ -379,6 +456,7 @@ const login = (session, msg) => {
accounts.save(account);
online.set(key, session);
console.log(`[world] ${logText(account.username)} logged in as sfs user ${logText(session.id)}`);
gameActivity({type: "login", username: account.username, at: Math.floor(Date.now() / 1000)});
session.sendXtJson(-1, {_cmd: "login", status: "1", params: loginParams(session)});
// every custom colour, before anything that might be drawn with one
// (XtReplyDemuxer -> PaletteHelper.handleCustomColors in the patched SWF).
@@ -454,19 +532,28 @@ const sendAvatarCreate = (to, target) => {
avatar.questLevel || 0,
1, // userNameModeratedFlag
lastSeenField(account, Boolean(findOnline(account.username))), // daysSinceLastLogin: see lib/player.js
// optional-field flags: bit 0 accountType, bit 1 nameBarData, bit 2 pet
pet ? 7 : 3,
// optional-field flags: bit 0 accountType, bit 1 nameBarData, bit 2 pet,
// bit 3 a blend colour (none: 0), bit 4 guide (the name tag and bubble
// every client draws for a guide)
3 | (pet ? 4 : 0) | (account.isGuide ? 24 : 0),
account.accountType,
account.nameBarData,
...(pet ? petFields(pet) : []));
...(pet ? petFields(pet) : []),
...(account.isGuide ? [0, 1] : []));
sendItemList(to, target, false);
disguises.show(to, target);
if (target.invisible) {
to.sendXt("xiv", -1, target.id, 1);
}
if (target.petPlayerMode) {
if (pets.inPetForm(account)) {
to.sendXt("uc", room.id, target.id, "on", "13");
}
// `ac` only creates the avatar. Actions normally travel as live `uc`
// type-3 packets, so replay a standing player's current action after `ac`
// for a player who has just entered (or reloaded) the room.
if (target.activeAction) {
to.sendXt("uc", room.id, target.id, target.activeAction.name, "3", target.activeAction.extra);
}
minigames.showBubble(to, target);
};
@@ -507,8 +594,10 @@ const sortStock = () => {
// two out-of-the-way shops keep what was never in one: the shop in the
// Chamber of Knowledge's base (reached from a hidden spot on the world map)
// has the den items, the one in the Zios archives the clothing. see
// oddDenItemIds in lib/defpacks.js.
const ODDITY_SHOPS = new Map([[396, () => defpacks.oddDenItemIds()], [666, () => defpacks.oddClothingIds()]]);
// oddDenItemIds in lib/defpacks.js. of the clothing only the Founder's Hat
// (oddClothingIds' first): the rest, nameless pieces never finished, made the
// Forgotten Archive a heap of broken items.
const ODDITY_SHOPS = new Map([[396, () => defpacks.oddDenItemIds()], [666, () => defpacks.oddClothingIds().slice(0, 1)]]);
// the items staff have made (lib/customitems.js) are sold there too, first.
const CUSTOM_ITEM_SHOPS = new Map([[396, "den"], [666, "clothing"]]);
const ticketStock = kind => sortStock()[kind];
@@ -578,6 +667,10 @@ const sendFilter = session => {
session.sendXt("xfl", -1, filter.chosen ? 1 : 0, filter.level, filter.mode, filter.words);
};
// The in-game editor asks for this on demand too. It receives only canonical
// values, so the Flash client never has to guess at a missing account field.
const sendChatStyle = session => session.sendXt("xcs", -1, ...chatStyles.fields(session.account.chatStyle));
// the player called `username` as the senders above take one: their session
// when they are playing, else just their account. A player's card can be
// opened for anybody (the buddy list, the player search), and it asks for
@@ -604,6 +697,25 @@ const handlers = {
sendFilter(session);
},
// The Settings > Chat Bubble popup. An empty request just reloads the
// saved setting; a complete twelve-field request replaces it. Older custom
// clients remain accepted and receive a two-stop gradient automatically.
xcs(session, roomId, params) {
if (params.length === 0) {
sendChatStyle(session);
return;
}
if (![7, 10, 11, 12].includes(params.length)) return;
const [background, accent, text, border, opacity, animation, speed, gradient = "linear", angle = 45, strength = 100, outline = 1,
stops = `${background}:0;${accent}:100`] = params;
const style = {background, accent, text, border, opacity: Number(opacity), animation, speed: Number(speed),
gradient, angle: Number(angle), strength: Number(strength), outline: Number(outline), stops};
if (!chatStyles.valid(style)) return;
session.account.chatStyle = style;
accounts.save(session.account);
sendChatStyle(session);
},
// the patched client's hex colour picker (gui.ColorTable): [rgb1, rgb2,
// rgb3, rgb4], the four colours of one layer. everyone online is told the
// entry's id, the asker included, who then uses it as that layer's colour.
@@ -671,6 +783,9 @@ const handlers = {
const teleport = params[params.length - 1] === "1" ? 1 : 0;
const firstUpdate = !session.pos;
session.pos = {x: coords[coords.length - 2], y: coords[coords.length - 1]};
// Walking, swimming, or a teleport replaces a looping action on every
// client. Do not replay it to somebody entering later.
delete session.activeAction;
if (!session.greeted) {
// the first room has loaded: the client can show a popup now.
session.greeted = true;
@@ -678,6 +793,9 @@ const handlers = {
if (motd) {
tell(session, motd);
}
if (session.account.guideRefused) {
session.sendXt("xtl", -1, "Guide is only for players the Burrow team has made guides.");
}
buddies.greet(session);
minigames.greet(session);
moderation.greet(session);
@@ -742,6 +860,9 @@ const handlers = {
}
let entries = [];
let count;
if (Number(listId) === eco.SHOP_LIST) {
eco.shopOpened(session);
}
if (Number(listId) === GENERIC_LIST_AVATARS) {
entries = defpacks.avatarTypes();
}
@@ -811,6 +932,12 @@ const handlers = {
const real = shopStock.list(listId, type);
entries = [...new Set([...defpacks.customShopIds(CUSTOM_ITEM_SHOPS.get(Number(listId))), ...(real ? real.entries : []), ...ODDITY_SHOPS.get(Number(listId))()])];
}
else if (Number(listId) === DIAMOND_EGG_LIST) {
entries = defpacks.diamondIds().filter(id => {
const def = defpacks.diamondDef(id);
return def.type === DIAMOND_TYPES.pet && (defpacks.petDef(Number(def.refId)) || {}).isEgg === "1";
});
}
else if (Number(listId) === DIAMOND_DEN_LIST) {
entries = defpacks.diamondIds().filter(id => {
const def = defpacks.diamondDef(id);
@@ -843,9 +970,27 @@ const handlers = {
count = defpacks.petIds().length;
entries = defpacks.petIds().flatMap(id => [id, 1]);
}
// Jammer Central's "What's New" pictures (gui.BulletinBoard, list 369):
// the newest pages of the Jamaa Journal. empty, the window waited on
// its spinner.
if (Number(listId) === GENERIC_LIST_WHATS_NEW && (count === undefined ? entries.length : count) === 0) {
entries = defpacks.newestJournalPages(WHATS_NEW_PAGES).flatMap(id => [id, 0]);
count = entries.length / 2;
}
// what the official server answered, where this one has nothing of its
// own (lib/official-lists.json, from recordings of the official game:
// the Journey Book's facts and pictures among them)
if ((count === undefined ? entries.length : count) === 0 && Object.hasOwn(OFFICIAL_LISTS, String(Number(listId)))) {
const official = OFFICIAL_LISTS[String(Number(listId))];
if (official.type === type) {
entries = official.entries;
count = official.count;
}
}
// for shops the first unused field is the title's string id; left empty
// it keeps the shop window's own title (Shop.gotItemListCallback).
const title = SHOP_LIST_TYPES.includes(type) ? (session.room ? roomInfo.shopTitle(session.room.base, listId) : "") : 0;
const title = SHOP_LIST_TYPES.includes(type)
? (session.room && roomInfo.shopTitle(session.room.base, listId)) || SHOP_LIST_TITLES.get(Number(listId)) || SHOP_KIND_TITLES.get(type) : 0;
session.sendXt("gl", -1, listId, type, title, 0, 0, 0, count === undefined ? entries.length : count, ...entries);
},
@@ -867,6 +1012,10 @@ const handlers = {
if (vars[id] === undefined && Object.keys(vars).length >= MAX_USER_VARS) {
return;
}
// the eco plaques (lib/eco.js) are given, not set
if (eco.userVar(session, id, value)) {
return;
}
if (Number(id) === USER_VAR_HIDE_BLOCKED) {
setHideBlocked(session, Number(value) === 1);
}
@@ -984,6 +1133,60 @@ const handlers = {
}
},
// the game's feedback windows (the purple Help and Feedback buttons, the
// orbs in rooms, the newspaper's and the theatre's: the patched
// gui.FeedbackManager): xfb [the window's feedback type, the text]. it
// goes to the staff panels' feedback (lib/support.js), named by where it
// was written.
xfb(session, roomId, [type, ...text]) {
const where = FEEDBACK_KINDS.get(Number(type)) || "Feedback";
const said = text.join("%").trim();
if (!said) {
return;
}
const result = support.sendFeedback(session.account, "feedback", `${where} (in ${session.room ? session.room.displayName : "the game"}): ${said}`);
// the window has thanked them already; said only when it did not go
if (!result.ok) {
tell(session, result.error === "too_many" ? "You have sent a lot of feedback today. Try again tomorrow." : "That feedback could not be sent.");
}
},
// the game's Redeem Code window (GameRedemptionXtCommManager.requestRedeemCode):
// [code, captcha question, answer], a code made in the admin panel
// (lib/codes.js). the reply (CodeRedemptionPopup.onCodeRedeemResponse) is
// "1" redeemed: the gift comes as a card from HQ, or for gems and diamonds
// as a gift popup, whose card says so itself (lib/ecards.js deliver);
// "-4" not now (used already, and an HQ popup says so); else "that code
// didn't work". it was not answered at all, and the window spun.
grc(session, roomId, [code]) {
const {account} = session;
if (!codeTries.allow(account.id)) {
session.sendXt("grc", -1, "-4", "", 0);
return;
}
const result = codes.redeem(account, code);
if (result.error === "used" || result.error === "spent") {
tell(session, result.error === "used" ? "You have used that code already." : "That code has been used up.");
session.sendXt("grc", -1, "-4", "", 0);
return;
}
if (result.error) {
session.sendXt("grc", -1, "0", "", 0);
return;
}
const problem = ecards.sendFromHq(account, `Code ${result.code} redeemed!`, result.gift);
if (problem) {
codes.unredeem(account, result.code);
tell(session, `${problem}. The code can be used once there is room.`);
session.sendXt("grc", -1, "-4", "", 0);
return;
}
if (result.gift.kind === "clothing" || result.gift.kind === "den") {
session.sendXt("grc", -1, "1", "", 0);
tell(session, "Code redeemed! Your gift is in your Jam-A-Grams.");
}
},
// the patched client's tags (AJClient.resolveMentions): xmn [id, the text
// after each "@", ...] -> "xmn" [.., .., id, then for each text: how many
// of its characters are a player's name (0 for none), the name as it is
@@ -1032,7 +1235,12 @@ const handlers = {
const thing = kind === "a" ? account.avatars.find(avatar => avatar.perUserAvId === Number(id))
: kind === "p" ? account.pets.find(pet => pet.inv === Number(id)) : null;
// typed words others read: not while silenced.
const ok = Boolean(thing) && TYPED_NAME.test(wanted) && !moderation.isSilenced(account);
const filtered = Boolean(thing) && TYPED_NAME.test(wanted) && nameFiltered(wanted);
const ok = Boolean(thing) && TYPED_NAME.test(wanted) && !filtered && !moderation.isSilenced(account);
if (filtered) {
console.log(`[filter] ${logText(session.name)} named ${kind === "a" ? "an animal" : "a pet"}: "${logText(wanted)}" (${logText(chatFilter.broken(wanted))})`);
chatFilter.warn(session);
}
if (ok) {
thing.name = wanted;
accounts.save(account);
@@ -1064,11 +1272,28 @@ const handlers = {
// VolumeSelector.handleRoomCountResponse: the head-count shown on each land
// of the world map, as [count, (roomName, players)...].
// the map's buddy counts (VolumeSelector.handleRoomCountResponse): how
// many of the player's buddies are in each land of the player's world.
// the map takes a land from the room's name (an ocean's from its room)
// and keeps the last number it gets for it, so each land comes once,
// its rooms added up. it counted everyone in every room of every world.
// dens, parties and adventures are left out, whose names are nobody
// else's business.
rc(session) {
// the lands and their shops, as the map shows them: not dens, parties,
// or anybody's adventure, whose names are nobody else's business.
const counts = [...rooms.values()].filter(room => !room.denOwner && room.roomType === 0).flatMap(room => [room.name, room.sessions.size]);
session.sendXt("rc", -1, counts.length / 2, ...counts);
const counts = new Map(); // a name the map reads its land from -> buddies there
const world = session.worldId || config.shards[0].id;
for (const other of online.values()) {
const {room} = other;
if (other === session || !room || room.denOwner || room.roomType !== 0 || worldOf(room.name) !== world
|| !session.account.buddies.includes(other.account.username.toLowerCase()) || !sees(session, other)
|| blocks.either(session.account, other.account)) {
continue;
}
const [land, place = ""] = room.base.split(".");
const key = land === "oceans" ? `oceans.${place}#${world}` : `${land}.room_main#${world}`;
counts.set(key, (counts.get(key) || 0) + 1);
}
session.sendXt("rc", -1, counts.size, ...[...counts].flat());
},
// RoomXtCommManager.sendRoomJoinRequestFull: [nameOrId, confirmLanguage, invisible, joinType]
@@ -1282,6 +1507,7 @@ const pets = petModule(context);
const parties = partyModule(context);
const ecards = ecardModule(context);
const walls = wallModule(context);
const eco = ecoModule({others, ecards});
const commands = commandModule(context);
const minigames = minigameModule(context);
const adventures = adventureModule(context);
@@ -1291,9 +1517,22 @@ const trades = tradeHandlers(context);
achievements.setFinder(findOnline);
Object.assign(handlers, avatarHandlers(context), itemHandlers(context), pets.handlers, dens.handlers({...context, others}),
buddies.handlers, moderation.handlers, trades.handlers, achievements.handlers, adopt.handlers, worldItems.handlers,
parties.handlers, ecards.handlers, walls.handlers, minigames.handlers, adventures.handlers, stubHandlers,
parties.handlers, ecards.handlers, eco.handlers, walls.handlers, minigames.handlers, adventures.handlers, stubHandlers,
playerItems.handlers({itemsTaken: (...args) => itemsTaken(...args)}));
// a den's owner, wherever they are, is told how many are in it: the HUD's
// den count, with the doorbell when it goes up (DenXtCommManager.denRoomCount,
// GuiManager.updateDenRoomCount: [count, 1 if they are among them, owner]).
// someone they cannot see is not counted.
const tellDenCount = room => {
const owner = room && room.denOwner ? findOnline(room.denOwner.username) : null;
if (!owner) {
return;
}
const inside = [...room.sessions].filter(other => other === owner || sees(owner, other));
owner.sendXt("drc", -1, inside.length, inside.includes(owner) ? 1 : 0, room.denOwner.username);
};
const leaveRoom = session => {
const {room} = session;
if (!room) {
@@ -1302,6 +1541,7 @@ const leaveRoom = session => {
room.sessions.delete(session);
session.room = null;
session.pos = null;
delete session.activeAction;
minigames.roomLeft(session);
for (const other of room.sessions) {
// AvatarManager.avatarRemoveResponse
@@ -1312,6 +1552,7 @@ const leaveRoom = session => {
if (room.sessions.size === 0) {
rooms.delete(room.name);
}
tellDenCount(room);
};
// the Bio tab's words: the bio, under the time played when the player
@@ -1358,6 +1599,8 @@ setInterval(() => {
}, 60000).unref();
const leaveWorld = session => {
const username = session.account && session.account.username;
const playedSeconds = session.playStarted ? Math.max(0, Math.round((Date.now() - session.playStarted) / 1000)) : 0;
minigames.leave(session);
trades.forget(session);
leaveRoom(session);
@@ -1369,6 +1612,7 @@ const leaveWorld = session => {
accounts.release(session.account);
accounts.save(session.account);
buddies.announce(session.account);
gameActivity({type: "logout", username, at: Math.floor(Date.now() / 1000), playedSeconds});
}
};
@@ -1481,6 +1725,7 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => {
if (props.denOwner && props.denOwner !== session.account) {
noteDenVisit(props.denOwner, session.account);
}
tellDenCount(room);
roomInfo.ensure(base);
const avatar = activeAvatar(session.account);
pets.walked(session.account);
@@ -1738,7 +1983,9 @@ module.exports = {
// embedded SWF labels outgoing user messages with the minigame's
// temporary sub-room id. Accept that id as well so its attachment
// reward can make the normal round trip back to the avatar.
if (session.room && (session.room.id === msg.roomId || (session.game && session.game.roomId === Number(msg.roomId)))) {
const fromGame = (session.game && session.game.roomId === Number(msg.roomId))
|| (session.lastGame && session.lastGame.roomId === Number(msg.roomId) && Date.now() < session.lastGame.until);
if (session.room && (session.room.id === msg.roomId || fromGame)) {
// at most text, type and one extra field, and no essays.
const fields = decodeEntities(msg.cdata("txt") || "").split("%").slice(0, 3);
if (fields[0].length > config.maxChatLength || (fields[2] || "").length > MAX_CHAT_EXTRA) {
@@ -1757,17 +2004,24 @@ module.exports = {
minigames.bubble(session, fields[0], fields[2]);
return;
}
// Per-player pet form. It is deliberately a user-communication
// message so every client already in the room updates the same
// avatar, while the normal pet-out state stays unchanged.
// Per-player pet form (the pet chooser's switch, lib/pets.js). It
// is deliberately a user-communication message so every client
// already in the room updates the same avatar, while the normal
// pet-out state stays unchanged.
if (fields[1] === "13") {
const enabled = fields[0] === "on" && Boolean(activePet(session.account));
session.petPlayerMode = enabled;
for (const other of [session, ...watchers(session)]) {
other.sendXt("uc", session.room.id, session.id, enabled ? "on" : "off", "13");
}
pets.setPetForm(session, fields[0] === "on");
return;
}
// Type 3 is the action packet. It used to be sent only to people
// already in the room, leaving late arrivals with an idle avatar
// until the player performed the action again. Save the safe action
// name and its mirror marker for the next avatar-create packet.
if (fields[1] === "3") {
if (!ACTION_NAME.test(fields[0])) {
return;
}
session.activeAction = {name: fields[0], extra: fields[2] || ""};
}
// Attachment messages carry an emoticon *definition* id from the
// sender, while the recipient's avatar view needs that definition's
// media id. This is the normal path used by den attachments and
@@ -1793,6 +2047,10 @@ module.exports = {
// local client deliberately does not draw it optimistically, unlike
// typed chat and normal emotes.
const attachmentEcho = fields[1] === "4";
// A phrase from the phrase menus is drawn from the echo too (the
// patched UserCommXtCommManager.sendAvatarSafeChat), so that it
// comes in the sender's chat bubble style, as typed chat does.
const phrase = fields[1] === "1";
// silenced, or chat switched off on the account page: the line
// goes nowhere.
if (echo && (moderation.isSilenced(session.account) || !accounts.featureOn(session.account, "chat"))) {
@@ -1805,6 +2063,14 @@ module.exports = {
session.sendXt("uc", session.room.id, session.id, -1, 5);
return;
}
// the momentary ones (a phrase, an emote, an action, an attachment,
// a slide, a pet's trick), past a few in a few seconds, reach
// nobody: the sender has shown their own already. what sets a
// state (a colour, see-through, a lasting emote) always goes, or
// others would be left seeing the wrong one.
if (MOMENTARY_TYPES.includes(fields[1]) && !limits.isTrustedLocal(session.address) && !roomActions.allow(session.account.id)) {
return;
}
if (echo) {
// "!help" and the like (lib/commands.js). A command's line is
// still echoed to its sender, whose chat bubble waits for it.
@@ -1846,12 +2112,18 @@ module.exports = {
// nobody hears a player they have blocked, and with chat switched
// off nobody's typed lines arrive at all.
// an invisible staff member's emotes and the like reach staff only.
for (const recipient of (echo || attachmentEcho) ? session.room.sessions : others(session)) {
// Typed chat always gets a third (stock "extra") field, followed by
// its style. Keeping message and type at their original indexes is
// what clears the local "..." bubble; carrying the style on the
// same packet prevents it being lost or applied to a later line.
const style = echo || phrase ? chatStyles.packet(session.account.chatStyle) : "";
for (const recipient of (echo || attachmentEcho || phrase) ? session.room.sessions : others(session)) {
if (session.invisible && recipient !== session && !roles.isActiveStaff(recipient.account)) {
continue;
}
if (recipient === session || (!blocks.has(recipient.account, session.account) && (!echo || accounts.featureOn(recipient.account, "chat")))) {
recipient.sendXt("uc", session.room.id, session.id, ...fields);
recipient.sendXt("uc", session.room.id, session.id,
...((echo || phrase) && style ? [fields[0], fields[1], fields[2] || "", style] : fields));
}
}
}
@@ -1991,20 +2263,21 @@ module.exports = {
// the panel's Masterpieces page. A painting waiting for review is an
// item its maker cannot use yet; approving it tells them so, by a
// Jam-A-Gram from Animal Jam HQ and at once if they are playing. `by`
// is who approved it: a moderator's username, or "admin".
// is who approved it: a moderator's username, or "admin". the same
// picture waiting elsewhere is approved with it, and its makers told too.
approveMasterpiece(id, by) {
const maker = masterpieces.creatorOf(id);
if (!masterpieces.approve(id, by)) {
return false;
}
if (maker) {
ecards.noteFromHq(maker, "Your Masterpiece has been approved! It is with your den items.");
const session = findOnline(maker.username);
if (session) {
dens.sendDenItems(session);
const approved = masterpieces.approve(id, by);
for (const painting of approved) {
const maker = masterpieces.creatorOf(painting.id);
if (maker) {
ecards.noteFromHq(maker, "Your Masterpiece has been approved! It is with your den items.");
const session = findOnline(maker.username);
if (session) {
dens.sendDenItems(session);
}
}
}
return true;
return approved.length > 0;
},
// takes a painting away for good, from whoever has it by now: one that
// was not approved, or one that should not have been. its maker gets a
@@ -2029,7 +2302,7 @@ module.exports = {
account.denItems = account.denItems.filter(item => item.image !== painting.id);
account.tradeList = account.tradeList.filter(listed => !(listed.type === 1 && held.some(item => item.inv === listed.inv)));
}
masterpieces.forget(painting.id);
masterpieces.forget(painting.id, true);
if (maker) {
dens.giveDenItem(maker, masterpieces.TOKEN_DEN_ITEM);
ecards.noteFromHq(maker, "Your Masterpiece was not approved. Here is a Masterpiece Token to frame another one with.");
@@ -2049,6 +2322,31 @@ module.exports = {
return true;
},
// how many worlds there are (the admin panel), from 1 to 10, kept as a
// setting. the list is changed where it is (config.shards: everything
// reads it from there), so the world picker shows the new ones at once;
// whoever is in a world that is gone is moved to the first.
WORLD_COUNT_SETTING,
setWorldCount(count, keep = true) {
const wanted = Math.min(config.worldNames.length, Math.max(1, Math.floor(Number(count))));
if (!Number.isFinite(wanted)) {
return null;
}
config.shards.splice(0, config.shards.length, ...config.worldNames.slice(0, wanted).map((name, i) => ({id: i + 1, name})));
if (keep) {
accounts.setSetting(WORLD_COUNT_SETTING, String(wanted));
}
for (const session of online.values()) {
if (session.worldId > wanted) {
session.worldId = config.shards[0].id;
if (session.room && worldOf(session.room.name) === 0 && /#\d+$/.test(session.room.name)) {
sendHome(session);
}
}
}
return wanted;
},
// the panel's Debug page: puts a playing account into any room of the room
// list, as that room and nothing more (a den's file without its owner, a
// party's without the party). returns what is wrong, or null.
@@ -2105,4 +2403,5 @@ module.exports = {
room: session.room ? session.room.name.replace(/#(\d+)$/, (whole, id) => (worldOf(whole) ? ` (${worldName(Number(id))})` : whole)) : null,
address: session.address,
})),
onGameActivity,
};
+333
View File
@@ -0,0 +1,333 @@
{
"name": "aj-classic-private-server",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "aj-classic-private-server",
"version": "0.1.0",
"dependencies": {
"discord.js": "14.26.4"
},
"engines": {
"node": ">=22.5"
}
},
"node_modules/@discordjs/builders": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz",
"integrity": "sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==",
"license": "Apache-2.0",
"dependencies": {
"@discordjs/formatters": "^0.6.2",
"@discordjs/util": "^1.2.0",
"@sapphire/shapeshift": "^4.0.0",
"discord-api-types": "^0.38.40",
"fast-deep-equal": "^3.1.3",
"ts-mixer": "^6.0.4",
"tslib": "^2.6.3"
},
"engines": {
"node": ">=16.11.0"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/collection": {
"version": "1.5.3",
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz",
"integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==",
"license": "Apache-2.0",
"engines": {
"node": ">=16.11.0"
}
},
"node_modules/@discordjs/formatters": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.6.2.tgz",
"integrity": "sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==",
"license": "Apache-2.0",
"dependencies": {
"discord-api-types": "^0.38.33"
},
"engines": {
"node": ">=16.11.0"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/rest": {
"version": "2.6.3",
"resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.3.tgz",
"integrity": "sha512-wvOylxNYJkwKjctS/Mn5GP1w9r3/rzyH+ThD1JlAca6zEdlHs8QWBBUQJpU5Q+W6DoIj/Ljh1IPlZs7hTU+UAg==",
"license": "Apache-2.0",
"dependencies": {
"@discordjs/collection": "^2.1.1",
"@discordjs/util": "^1.2.0",
"@sapphire/async-queue": "^1.5.3",
"@sapphire/snowflake": "^3.5.5",
"@vladfrangu/async_event_emitter": "^2.4.6",
"discord-api-types": "^0.38.50",
"magic-bytes.js": "^1.13.0",
"tslib": "^2.6.3",
"undici": "^6.27.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/rest/node_modules/@discordjs/collection": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",
"integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==",
"license": "Apache-2.0",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/rest/node_modules/@sapphire/snowflake": {
"version": "3.5.5",
"resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz",
"integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==",
"license": "MIT",
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
}
},
"node_modules/@discordjs/rest/node_modules/undici": {
"version": "6.29.1",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz",
"integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==",
"license": "MIT",
"engines": {
"node": ">=18.17"
}
},
"node_modules/@discordjs/util": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.2.0.tgz",
"integrity": "sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==",
"license": "Apache-2.0",
"dependencies": {
"discord-api-types": "^0.38.33"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/ws": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.2.3.tgz",
"integrity": "sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==",
"license": "Apache-2.0",
"dependencies": {
"@discordjs/collection": "^2.1.0",
"@discordjs/rest": "^2.5.1",
"@discordjs/util": "^1.1.0",
"@sapphire/async-queue": "^1.5.2",
"@types/ws": "^8.5.10",
"@vladfrangu/async_event_emitter": "^2.2.4",
"discord-api-types": "^0.38.1",
"tslib": "^2.6.2",
"ws": "^8.17.0"
},
"engines": {
"node": ">=16.11.0"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/ws/node_modules/@discordjs/collection": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",
"integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==",
"license": "Apache-2.0",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@sapphire/async-queue": {
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.5.tgz",
"integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==",
"license": "MIT",
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
}
},
"node_modules/@sapphire/shapeshift": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-4.0.0.tgz",
"integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==",
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.3",
"lodash": "^4.17.21"
},
"engines": {
"node": ">=v16"
}
},
"node_modules/@sapphire/snowflake": {
"version": "3.5.3",
"resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.3.tgz",
"integrity": "sha512-jjmJywLAFoWeBi1W7994zZyiNWPIiqRRNAmSERxyg93xRGzNYvGjlZ0gR6x0F4gPRi2+0O6S71kOZYyr3cxaIQ==",
"license": "MIT",
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
}
},
"node_modules/@types/node": {
"version": "26.6.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",
"integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==",
"license": "MIT",
"dependencies": {
"undici-types": "~8.9.0"
}
},
"node_modules/@types/ws": {
"version": "8.18.2",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz",
"integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@vladfrangu/async_event_emitter": {
"version": "2.4.7",
"resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.4.7.tgz",
"integrity": "sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==",
"license": "MIT",
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
}
},
"node_modules/discord-api-types": {
"version": "0.38.57",
"resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.57.tgz",
"integrity": "sha512-R1CTSSt4RshqCq23j2Xq2ZscvzB4LzG9OB1CYQdKUGdw8Ti/oF/72EEtK2mNpagG/Vj9NcBT7dw9lKLf+Dacfg==",
"license": "MIT"
},
"node_modules/discord.js": {
"version": "14.26.4",
"resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.26.4.tgz",
"integrity": "sha512-4oBp8tc6Kf8IDBwAHhbsMaAqx1b5fob9SNasZT7V6yyyUydoO5i5fGuX7TmvRtR+q/WgKRnRViRoAWnG7fNyvA==",
"license": "Apache-2.0",
"dependencies": {
"@discordjs/builders": "^1.14.1",
"@discordjs/collection": "1.5.3",
"@discordjs/formatters": "^0.6.2",
"@discordjs/rest": "^2.6.1",
"@discordjs/util": "^1.2.0",
"@discordjs/ws": "^1.2.3",
"@sapphire/snowflake": "3.5.3",
"discord-api-types": "^0.38.40",
"fast-deep-equal": "3.1.3",
"lodash.snakecase": "4.1.1",
"magic-bytes.js": "^1.13.0",
"tslib": "^2.6.3",
"undici": "6.24.1"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"license": "MIT"
},
"node_modules/lodash": {
"version": "4.18.1",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
"integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
"license": "MIT"
},
"node_modules/lodash.snakecase": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz",
"integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==",
"license": "MIT"
},
"node_modules/magic-bytes.js": {
"version": "1.13.1",
"resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.1.tgz",
"integrity": "sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw==",
"license": "MIT"
},
"node_modules/ts-mixer": {
"version": "6.0.4",
"resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz",
"integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==",
"license": "MIT"
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/undici": {
"version": "6.24.1",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.24.1.tgz",
"integrity": "sha512-sC+b0tB1whOCzbtlx20fx3WgCXwkW627p4EA9uM+/tNNPkSS+eSEld6pAs9nDv7WbY1UUljBMYPtu9BCOrCWKA==",
"license": "MIT",
"engines": {
"node": ">=18.17"
}
},
"node_modules/undici-types": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"license": "MIT"
},
"node_modules/ws": {
"version": "8.22.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
"integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}
+3
View File
@@ -10,5 +10,8 @@
},
"engines": {
"node": ">=22.5"
},
"dependencies": {
"discord.js": "14.26.4"
}
}
+297 -7
View File
@@ -94,6 +94,8 @@
transition: background 0.12s, border-color 0.12s, color 0.12s;
}
button:hover { background: var(--raised); border-color: #555; }
a.button { border: 1px solid var(--line); border-radius: 999px; padding: 7px 16px 8px; white-space: nowrap; text-decoration: none; }
a.button:hover { background: var(--raised); border-color: #555; }
button:disabled { opacity: 0.45; cursor: default; }
button:focus-visible, a:focus-visible, input[type="checkbox"]:focus-visible { outline: 2px solid var(--text); outline-offset: 2px; }
button.primary { font-weight: 700; color: #000; background: var(--text); border-color: var(--text); }
@@ -116,7 +118,7 @@
line-height: 17px;
text-align: center;
}
@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
@media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important; } }
.wrap { max-width: 760px; margin: 0 auto; }
label.check { display: flex; align-items: center; color: var(--text); font-size: 14px; cursor: pointer; }
/* dark on white whatever the page: that is what a phone's camera reads. */
@@ -175,6 +177,26 @@
.ban-head { display: flex; align-items: center; gap: 12px; margin-bottom: 4px; }
.ban-head img { width: 44px; height: 44px; flex: none; }
.ban-head h2 { margin: 0; font-size: 22px; }
.chat-style-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0 12px; }
.chat-style-grid input[type="color"] { width: 100%; height: 42px; padding: 3px; cursor: pointer; }
.gradient-editor { margin: 14px 0; padding: 12px; border: 1px solid var(--line); border-radius: 12px; }
.gradient-editor-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px; }
.gradient-stops { display: grid; gap: 8px; }
.gradient-ramp { height: 22px; margin-bottom: 10px; border: 1px solid var(--line); border-radius: 999px; }
.gradient-stop { display: grid; grid-template-columns: 50px minmax(100px, 1fr) 72px auto; align-items: center; gap: 8px; }
.gradient-stop input[type="color"] { width: 50px; height: 36px; padding: 2px; cursor: pointer; }
.gradient-stop input[type="range"] { margin: 0; }
.gradient-stop output { color: var(--muted); font-size: 12px; text-align: right; }
.chat-preview { min-height: 74px; display: grid; place-items: center; margin-top: 14px; padding: 12px 18px; border: 1px solid var(--line); border-radius: 18px; text-align: center; font-weight: 700; background: linear-gradient(120deg, #fff, #dfe8ff); color: #445559; }
.chat-preview.pulse { animation: chatPulse 1.5s ease-in-out infinite alternate; }
.chat-preview.shimmer { background-size: 250% 100%; animation: chatShimmer 1.5s linear infinite; }
.chat-preview.flow { background-size: 220% 220%; animation: chatFlow 1.5s linear infinite alternate; }
.chat-preview.rainbow { animation: chatRainbow 2s linear infinite; }
@keyframes chatPulse { to { opacity: .55; } }
@keyframes chatShimmer { to { background-position: 100% 0; } }
@keyframes chatFlow { to { background-position: 100% 100%; } }
@keyframes chatRainbow { to { filter: hue-rotate(360deg); } }
@media (max-width: 440px) { .chat-style-grid { grid-template-columns: 1fr; } }
#ban-section pre { margin: 0 0 12px; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; }
#ban-section h3 { margin: 18px 0 0; }
</style>
@@ -195,7 +217,7 @@
<label class="check" style="margin-top:12px"><input id="remember-device" type="checkbox"> Trust this device for 30 days</label>
</div>
<div class="captcha" id="captcha"></div>
<div class="row"><button class="primary" type="submit">Sign in</button></div>
<div class="row"><button class="primary" type="submit">Sign in</button><button id="client-sign-in" type="button">Sign in with the Burrow client</button></div>
</form>
<p class="status" id="gate-status" role="status"></p>
<p class="hint" style="margin:10px 0 0">No account yet? <a href="/register">Create one</a> · <a href="/account/recover">Forgot password or 2FA?</a></p>
@@ -205,6 +227,7 @@
<header>
<img class="mark" src="/logo.png" alt="">
<h1 id="title"></h1>
<a class="button" id="item-giver" href="/account/items">Item giver</a>
<button id="sign-out" type="button">Sign out</button>
</header>
@@ -242,7 +265,11 @@
<section>
<h2>Buddies</h2>
<div id="buddies"></div>
<!-- closed at first: a long list made the page slow to scroll -->
<details id="buddies-box" hidden>
<summary id="buddies-summary">Buddies</summary>
<div id="buddies"></div>
</details>
<p class="hint" id="no-buddies" hidden>No buddies yet.</p>
<p class="status" id="buddy-status" role="status"></p>
</section>
@@ -293,7 +320,10 @@
<section>
<h2>Den visitors</h2>
<div id="visits"></div>
<details id="visits-box" hidden>
<summary id="visits-summary">Visitors</summary>
<div id="visits"></div>
</details>
<p class="hint" id="no-visits" hidden>No visitors yet.</p>
</section>
@@ -354,6 +384,35 @@
<p class="status" id="bio-status" role="status"></p>
</section>
<section id="chat-bubble">
<h2>Chat bubble</h2>
<p>Choose how your spoken chat bubbles look for everyone using Burrow's current client.</p>
<form id="chat-style-form">
<div class="gradient-editor">
<div class="gradient-editor-head"><b>Gradient colours</b><button id="chat-stop-add" type="button">Add colour</button></div>
<div class="gradient-ramp" id="chat-ramp"></div>
<div class="gradient-stops" id="chat-stops"></div>
</div>
<div class="chat-style-grid">
<div hidden><input id="chat-background" type="color" value="#ffffff"></div>
<div hidden><input id="chat-accent" type="color" value="#dfe8ff"></div>
<div><label for="chat-text-colour">Text colour</label><input id="chat-text-colour" type="color" value="#445559"></div>
<div><label for="chat-border">Border</label><input id="chat-border" type="color" value="#9aabb0"></div>
<div><label for="chat-opacity">Opacity <span class="hint" id="chat-opacity-value"></span></label><input id="chat-opacity" type="range" min="25" max="100" value="75"></div>
<div><label for="chat-gradient">Gradient</label><select id="chat-gradient"><option value="linear">Linear</option><option value="radial">Radial</option><option value="solid">Solid</option></select></div>
<div><label for="chat-angle">Direction</label><select id="chat-angle"><option value="0">0°</option><option value="45">45°</option><option value="90">90°</option><option value="135">135°</option><option value="180">180°</option><option value="225">225°</option><option value="270">270°</option><option value="315">315°</option></select></div>
<div><label for="chat-strength">Gradient strength <span class="hint" id="chat-strength-value"></span></label><input id="chat-strength" type="range" min="0" max="100" value="100"></div>
<div><label for="chat-outline">Outline thickness <span class="hint" id="chat-outline-value"></span></label><input id="chat-outline" type="range" min="0" max="4" step="1" value="1"></div>
<div><label for="chat-animation">Animation</label><select id="chat-animation"><option value="none">Still</option><option value="pulse">Pulse</option><option value="shimmer">Shimmer</option><option value="flow">Flow</option><option value="rainbow">Rainbow</option></select></div>
<div><label for="chat-speed">Animation speed <span class="hint" id="chat-speed-value"></span></label><input id="chat-speed" type="range" min="40" max="300" value="100"></div>
</div>
<div class="chat-preview" id="chat-preview">Your chat bubble preview</div>
<div class="row"><button id="chat-style-swap" type="button">Swap gradient</button><button id="chat-style-random" type="button">Random gradient</button></div>
<div class="row"><button class="primary" type="submit">Save chat style</button><button id="chat-style-reset" type="button">Use original bubble</button></div>
</form>
<p class="status" id="chat-style-status" role="status"></p>
</section>
<section>
<h2>Playtime</h2>
<p id="playtime-text"></p>
@@ -504,8 +563,12 @@
];
const VIA = {game: "Game", launcher: "Client", web: "This page", mod: "Moderator panel"};
const ANIMALS = {1: "Tiger", 4: "Wolf", 5: "Koala", 6: "Panda", 7: "Monkey", 8: "Bunny", 13: "Rhino", 18: "Seal", 24: "Penguin"};
const DEFAULT_CHAT_STYLE = {background: "ffffff", accent: "dfe8ff", text: "445559", border: "9aabb0", opacity: 75,
animation: "none", speed: 100, gradient: "linear", angle: 45, strength: 100, outline: 1,
stops: "ffffff:0;dfe8ff:100"};
let account = null;
let chatStops = [];
let twoStepSetup = null; // {secret, uri} while two-step sign-in is being turned on
let twoStepCodes = null; // the recovery codes, until the player says they kept them
@@ -527,6 +590,126 @@
$(id).classList.toggle("bad", bad);
};
const parseChatStops = style => {
const parsed = String(style.stops || "").split(";").map(value => {
const match = /^([0-9a-f]{6}):(100|[1-9]?\d)$/i.exec(value);
return match ? {color: match[1].toLowerCase(), position: Number(match[2])} : null;
});
return parsed.length >= 2 && parsed.length <= 5 && parsed.every(Boolean)
? parsed : [{color: style.background, position: 0}, {color: style.accent, position: 100}];
};
const styleValue = () => {
if (chatStops.length < 2) chatStops = parseChatStops(DEFAULT_CHAT_STYLE);
chatStops.sort((one, two) => one.position - two.position);
chatStops[0].position = 0;
chatStops.at(-1).position = 100;
const background = chatStops[0].color;
const accent = chatStops.at(-1).color;
$("chat-background").value = `#${background}`;
$("chat-accent").value = `#${accent}`;
return {
background, accent,
text: $("chat-text-colour").value.slice(1).toLowerCase(),
border: $("chat-border").value.slice(1).toLowerCase(),
opacity: Number($("chat-opacity").value),
animation: $("chat-animation").value,
speed: Number($("chat-speed").value),
gradient: $("chat-gradient").value,
angle: Number($("chat-angle").value),
strength: Number($("chat-strength").value),
outline: Number($("chat-outline").value),
stops: chatStops.map(stop => `${stop.color}:${stop.position}`).join(";"),
};
};
const paintChatPreview = () => {
const style = styleValue();
const preview = $("chat-preview");
preview.className = `chat-preview ${style.animation}`;
const mix = (one, two, amount) => one.map((part, index) => Math.round(part + (two[index] - part) * amount));
const rgb = hex => [0, 2, 4].map(at => parseInt(hex.slice(at, at + 2), 16));
const stops = parseChatStops(style).map((stop, index) => {
const colour = index ? mix(rgb(style.background), rgb(stop.color), style.strength / 100) : rgb(stop.color);
return `#${colour.map(part => part.toString(16).padStart(2, "0")).join("")} ${stop.position}%`;
}).join(", ");
preview.style.background = style.gradient === "solid" ? `#${style.background}` : style.gradient === "radial"
? `radial-gradient(circle, ${stops})`
: `linear-gradient(${style.angle}deg, ${stops})`;
preview.style.color = `#${style.text}`;
preview.style.borderColor = `#${style.border}`;
preview.style.borderWidth = `${style.outline}px`;
preview.style.opacity = String(style.opacity / 100);
preview.style.animationDuration = `${Math.max(.25, 1.5 * 100 / style.speed)}s`;
$("chat-opacity-value").textContent = `${style.opacity}%`;
$("chat-speed-value").textContent = `${style.speed}%`;
$("chat-strength-value").textContent = `${style.strength}%`;
$("chat-outline-value").textContent = `${style.outline}px`;
};
const renderChatStops = () => {
chatStops.sort((one, two) => one.position - two.position);
const holder = $("chat-stops");
holder.replaceChildren();
$("chat-ramp").style.background = `linear-gradient(90deg, ${chatStops.map(stop => `#${stop.color} ${stop.position}%`).join(", ")})`;
chatStops.forEach((stop, index) => {
const row = el("div", undefined, "gradient-stop");
const colour = document.createElement("input");
colour.type = "color";
colour.value = `#${stop.color}`;
colour.setAttribute("aria-label", `Gradient colour ${index + 1}`);
const position = document.createElement("input");
position.type = "range";
position.min = String(index ? chatStops[index - 1].position + 1 : 0);
position.max = String(index < chatStops.length - 1 ? chatStops[index + 1].position - 1 : 100);
position.value = String(stop.position);
position.disabled = index === 0 || index === chatStops.length - 1;
const value = document.createElement("output");
value.textContent = index === 0 ? "Start" : index === chatStops.length - 1 ? "End" : `${stop.position}%`;
const remove = document.createElement("button");
remove.type = "button";
remove.textContent = "Remove";
remove.disabled = chatStops.length <= 2;
colour.addEventListener("input", () => {
stop.color = colour.value.slice(1).toLowerCase();
renderChatStops();
paintChatPreview();
});
position.addEventListener("input", () => {
stop.position = Number(position.value);
value.textContent = `${stop.position}%`;
$("chat-ramp").style.background = `linear-gradient(90deg, ${chatStops.map(item => `#${item.color} ${item.position}%`).join(", ")})`;
paintChatPreview();
});
remove.addEventListener("click", () => {
chatStops.splice(index, 1);
renderChatStops();
paintChatPreview();
});
row.append(colour, position, value, remove);
holder.append(row);
});
$("chat-stop-add").disabled = chatStops.length >= 5;
};
const fillChatStyle = style => {
style = {...DEFAULT_CHAT_STYLE, ...style};
chatStops = parseChatStops(style);
$("chat-background").value = `#${style.background}`;
$("chat-accent").value = `#${style.accent}`;
$("chat-text-colour").value = `#${style.text}`;
$("chat-border").value = `#${style.border}`;
$("chat-opacity").value = String(style.opacity);
$("chat-animation").value = style.animation;
$("chat-speed").value = String(style.speed);
$("chat-gradient").value = style.gradient;
$("chat-angle").value = String(style.angle);
$("chat-strength").value = String(style.strength);
$("chat-outline").value = String(style.outline);
renderChatStops();
paintChatPreview();
};
const api = async (path, body) => {
try {
const response = await fetch(`/account/api/${path}`, body === undefined ? {} : {
@@ -687,8 +870,8 @@
// moving), else drawn into a PNG that fits, smaller until it is small
// enough. any picture this browser can open will do (WebP, AVIF, BMP...).
// null when it cannot be read at all.
const PICTURE_SIDE = 512;
const PICTURE_BYTES = 300 * 1024;
const PICTURE_SIDE = 256;
const PICTURE_BYTES = 100 * 1024;
const preparePicture = async file => {
const kept = ["image/png", "image/jpeg", "image/gif"].includes(file.type);
let image = null;
@@ -702,7 +885,7 @@
image.close();
return file;
}
for (const side of [PICTURE_SIDE, 384, 256, 128]) {
for (const side of [PICTURE_SIDE, 192, 128, 96]) {
const scale = Math.min(1, side / image.width, side / image.height);
const canvas = document.createElement("canvas");
canvas.width = Math.max(1, Math.round(image.width * scale));
@@ -757,6 +940,9 @@
}
renderMyItems();
$("lock-notice").hidden = !account.locked;
if (!$("chat-style-form").contains(document.activeElement)) {
fillChatStyle(account.chatStyle);
}
const tiles = [
[account.online ? "Playing now" : account.lastSeen ? when(account.lastSeen) : "Not played yet", "Last seen"],
@@ -843,6 +1029,8 @@
}));
}
$("no-buddies").hidden = account.buddyList.length > 0;
$("buddies-box").hidden = account.buddyList.length === 0;
$("buddies-summary").textContent = `Show ${account.buddyList.length.toLocaleString()} ${account.buddyList.length === 1 ? "buddy" : "buddies"}`;
$("blocked").replaceChildren(...account.blocked.map(name => {
const row = el("div", undefined, "switch");
@@ -888,6 +1076,8 @@
return entry;
}));
$("no-visits").hidden = account.denVisits.length > 0;
$("visits-box").hidden = account.denVisits.length === 0;
$("visits-summary").textContent = `Show ${account.denVisits.length.toLocaleString()} ${account.denVisits.length === 1 ? "visit" : "visits"}`;
$("achievement-summary").textContent = `${account.achievements.earned} of ${account.achievements.of} earned.`;
$("achievements").replaceChildren(...account.achievements.counted.map(counted => {
@@ -944,9 +1134,71 @@
}
else {
showGate(result.status === 0 ? result.data.error : "");
if (Object.hasOwn(CLIENT_RESULTS, clientResult || "")) {
setStatus("gate-status", CLIENT_RESULTS[clientResult], true);
}
// never by itself on the way back from it: a browser that would
// not keep the sign-in would open tab after tab.
else if (!clientResult && clientRemembered()) {
signInWithClient();
}
}
if (clientResult) {
if (result.ok && clientResult === "ok") {
try {
localStorage.setItem(CLIENT_KEY, "1");
}
catch (err) {
// not kept: the button stays the way in.
}
}
history.replaceState(null, "", location.pathname + location.hash);
}
};
// "Sign in with the Burrow client" (lib/manage.js): the browser asks
// whether to open Burrow, which opens this page again signed in (in a
// new tab: this one follows). once that has worked in this browser, the
// page asks by itself each time it opens signed out.
const CLIENT_KEY = "burrow-client-sign-in";
const CLIENT_RESULTS = {
ok: "Burrow signed you in, but this browser did not keep it. Sign in with your password.",
expired: "That sign-in took too long. Try again.",
elsewhere: "Burrow opened the page in another browser than the one you started in. Start from this browser again, or sign in with your password.",
};
const clientResult = new URLSearchParams(location.search).get("client");
const clientRemembered = () => {
try {
return localStorage.getItem(CLIENT_KEY) === "1";
}
catch (err) {
return false;
}
};
let clientWait = null;
const signInWithClient = async () => {
const started = await api("client-start", {});
if (!started.ok) {
setStatus("gate-status", started.data.error || "That did not work.", true);
return;
}
setStatus("gate-status", "Opening Burrow… Allow it if your browser asks. Burrow must be logged in, or remember you.");
location.href = `burrow://account?n=${started.data.nonce}`;
clearInterval(clientWait);
const until = Date.now() + 120000;
clientWait = setInterval(async () => {
if (account || Date.now() > until) {
clearInterval(clientWait);
return;
}
if ((await api("me")).ok) {
clearInterval(clientWait);
await load();
}
}, 2000);
};
$("client-sign-in").addEventListener("click", signInWithClient);
$("sign-in").addEventListener("submit", async event => {
event.preventDefault();
const answer = captchaPass ? undefined : await check.answer();
@@ -1343,6 +1595,44 @@
});
$("bio-remove").addEventListener("click", () => act({action: "bio", text: ""}, "bio-status"));
["chat-background", "chat-accent", "chat-text-colour", "chat-border", "chat-opacity", "chat-gradient", "chat-angle", "chat-strength", "chat-outline", "chat-animation", "chat-speed"].forEach(id => {
$(id).addEventListener("input", paintChatPreview);
$(id).addEventListener("change", paintChatPreview);
});
$("chat-style-form").addEventListener("submit", async event => {
event.preventDefault();
await act({action: "chatStyle", style: styleValue()}, "chat-style-status");
});
$("chat-stop-add").addEventListener("click", () => {
if (chatStops.length >= 5) return;
let gapAt = 0;
for (let index = 1; index < chatStops.length - 1; index++) {
if (chatStops[index + 1].position - chatStops[index].position > chatStops[gapAt + 1].position - chatStops[gapAt].position) gapAt = index;
}
const before = chatStops[gapAt];
const after = chatStops[gapAt + 1];
const rgb = hex => [0, 2, 4].map(at => parseInt(hex.slice(at, at + 2), 16));
const mixed = rgb(before.color).map((part, index) => Math.round((part + rgb(after.color)[index]) / 2).toString(16).padStart(2, "0")).join("");
chatStops.splice(gapAt + 1, 0, {color: mixed, position: Math.round((before.position + after.position) / 2)});
renderChatStops();
paintChatPreview();
});
$("chat-style-swap").addEventListener("click", () => {
chatStops = chatStops.slice().reverse().map(stop => ({color: stop.color, position: 100 - stop.position}));
renderChatStops();
paintChatPreview();
});
$("chat-style-random").addEventListener("click", () => {
const randomColour = () => Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, "0");
chatStops.forEach(stop => { stop.color = randomColour(); });
renderChatStops();
paintChatPreview();
});
$("chat-style-reset").addEventListener("click", async () => {
fillChatStyle(DEFAULT_CHAT_STYLE);
await act({action: "chatStyle", style: DEFAULT_CHAT_STYLE}, "chat-style-status");
});
// off to Discord's sign-in; it comes back to /account?discord=<how it went>
$("discord-link").addEventListener("click", () => {
location.href = "/account/discord/link";
+601 -14
View File
@@ -215,9 +215,25 @@
.page-title h1 { font-size: 26px; }
@media (max-width: 860px) {
#panel { grid-template-columns: 1fr; }
#side { position: static; height: auto; flex-direction: column; }
nav { flex-direction: row; flex-wrap: wrap; }
nav button { width: auto; }
#side { position: static; height: auto; gap: 12px; padding: 12px; }
nav { flex-direction: row; flex-wrap: nowrap; overflow-x: auto; overflow-y: hidden; padding-bottom: 2px; scrollbar-width: thin; }
nav button { flex: 0 0 auto; width: auto; }
#main { padding: 16px 12px 32px; }
section { padding: 15px; border-radius: 14px; }
.page-title { align-items: flex-start; flex-direction: column; gap: 3px; margin-bottom: 14px; }
.columns, .actions { grid-template-columns: minmax(0, 1fr); }
.toolbar input[type="search"] { flex-basis: 100%; min-width: 0; width: 100%; }
.table-wrap { max-width: 100%; }
}
@media (max-width: 520px) {
body { font-size: 14px; overflow-x: hidden; }
.brand { padding: 0; }
.tiles, .paintings { grid-template-columns: minmax(0, 1fr); }
.tile { padding: 14px; }
.tile .value { font-size: 26px; }
dl { grid-template-columns: 1fr; gap: 2px; }
dd { margin-bottom: 9px; }
.preview { padding: 8px; }
}
section { background: var(--panel); border: 1px solid var(--line); border-radius: 18px; padding: 20px; margin-bottom: 18px; box-shadow: var(--shadow); }
@@ -376,6 +392,12 @@
</div>
<button class="primary" id="gate-button">Sign in</button>
</form>
<form id="discord-code-form" hidden>
<p class="hint">Discord confirmed who you are. Enter that account's 2FA code to finish signing in.</p>
<label for="discord-code">2FA code</label>
<input id="discord-code" inputmode="numeric" autocomplete="one-time-code" maxlength="20" spellcheck="false" required>
<button class="primary" id="discord-code-button">Finish signing in</button>
</form>
<button type="button" id="discord-sign-in" hidden>Sign in with Discord</button>
<p class="hint" id="discord-gate-hint" hidden>Only Discord accounts explicitly allowed by the owner can use this.</p>
<p class="status" id="gate-status" role="status"></p>
@@ -397,8 +419,10 @@
<button role="tab" data-tab="masterpieces" aria-selected="false"><span class="icon" aria-hidden="true">&#9635;</span>Masterpieces<span id="masterpiece-count"></span></button>
<button role="tab" data-tab="items" aria-selected="false"><span class="icon" aria-hidden="true">&#10070;</span>Items</button>
<button role="tab" data-tab="wear-rules" aria-selected="false"><span class="icon" aria-hidden="true">&#9873;</span>Wear rules</button>
<button role="tab" data-tab="music" aria-selected="false"><span class="icon" aria-hidden="true">&#9835;</span>Music</button>
<button role="tab" data-tab="bans" aria-selected="false"><span class="icon" aria-hidden="true">&#8856;</span>Bans</button>
<button role="tab" data-tab="moderators" aria-selected="false"><span class="icon" aria-hidden="true">&#9733;</span>Moderators</button>
<button role="tab" data-tab="discord" aria-selected="false"><span class="icon" aria-hidden="true">&#128172;</span>Discord</button>
<button role="tab" data-tab="messages" aria-selected="false"><span class="icon" aria-hidden="true">&#9993;</span>Messages</button>
<button role="tab" data-tab="logs" aria-selected="false"><span class="icon" aria-hidden="true">&#9776;</span>Logs</button>
<button role="tab" data-tab="debug" aria-selected="false"><span class="icon" aria-hidden="true">&#9881;</span>Debug</button>
@@ -443,6 +467,98 @@
</section>
</div>
<div data-view="discord" hidden>
<section>
<h2>Discord staff bot</h2>
<p class="hint" id="discord-bot-summary">Checking Discord bot configuration…</p>
<dl id="discord-bot-facts"></dl>
<div class="send-row">
<button type="button" id="discord-bot-start">Start</button>
<button type="button" id="discord-bot-stop">Stop</button>
<button type="button" id="discord-bot-reconnect">Reconnect</button>
<button type="button" id="discord-bot-sync">Sync slash commands</button>
</div>
<p class="status" id="discord-bot-status" role="status"></p>
</section>
<section>
<h2>Bot modules</h2>
<p class="hint">Every listed module is configured on this page. Permissions for staff commands are managed in the dashboard’s Moderators role matrix.</p>
<div class="table-wrap"><table>
<thead><tr><th>Module</th><th>State</th><th>What it does</th></tr></thead>
<tbody id="discord-modules"></tbody>
</table></div>
</section>
<section>
<h2>Public status card</h2>
<p class="hint">This Components V2 card is updated every five minutes. Save changes, then publish immediately when the bot and public-status channel are configured.</p>
<form id="discord-status-form">
<label for="discord-status-title">Title</label>
<input id="discord-status-title" maxlength="80" placeholder="Burrow status" aria-label="Discord public status-card title">
<label for="discord-status-note">Status message</label>
<textarea id="discord-status-note" rows="3" maxlength="500" placeholder="Optional message shown above the live player and moderation counts." aria-label="Discord public status-card message"></textarea>
<label for="discord-status-banner">Banner image URL</label>
<input id="discord-status-banner" type="url" maxlength="500" placeholder="https://… (leave blank for no banner)" aria-label="Discord public status-card banner image URL">
<div class="send-row">
<button class="primary" type="submit">Save status card</button>
<button type="button" id="discord-status-publish">Publish now</button>
</div>
</form>
<p class="status" id="discord-status-card-result" role="status"></p>
</section>
<section>
<h2>Notification channels</h2>
<p class="hint">Set a Discord channel ID for any stream you want. Leave a field empty to turn that stream off. Changes take effect immediately.</p>
<form id="discord-routing-form">
<div id="discord-channel-inputs"></div>
<label for="discord-github-repository">GitHub repository</label>
<input id="discord-github-repository" maxlength="201" placeholder="owner/repository" aria-label="GitHub repository for Discord update cards">
<div class="send-row"><button class="primary" type="submit">Save bot routing</button></div>
</form>
<p class="status" id="discord-routing-status" role="status"></p>
</section>
<section>
<h2>GitHub game updates</h2>
<p class="hint">Signed pushes become Components V2 commit cards. Client/SWF and game-asset pushes are marked as game updates.</p>
<dl id="github-update-facts"></dl>
</section>
<section>
<h2>Discord security</h2>
<p class="hint">AutoMod deletes matching messages and posts an audit card without storing message text. Anti-raid sends an alert when the join limit is reached. Enable the Message Content and Server Members intents for this bot in the Discord Developer Portal, then reconnect it.</p>
<form id="discord-security-form">
<label class="check"><input id="discord-security-enabled" type="checkbox"> Enable Discord AutoMod and anti-raid alerts</label>
<label class="check"><input id="discord-security-invites" type="checkbox"> Block Discord invite links</label>
<label for="discord-security-words">Blocked words or phrases</label>
<textarea id="discord-security-words" rows="4" maxlength="3000" placeholder="One word or phrase per line; matching is case-insensitive."></textarea>
<div class="row">
<label for="discord-security-spam">Messages allowed per 10 seconds</label>
<input id="discord-security-spam" type="number" min="2" max="20" step="1" inputmode="numeric">
<label for="discord-security-raid">Joins allowed per minute</label>
<input id="discord-security-raid" type="number" min="3" max="100" step="1" inputmode="numeric">
</div>
<div class="send-row"><button class="primary" type="submit">Save security settings</button></div>
</form>
<p class="status" id="discord-security-status" role="status"></p>
</section>
<section>
<h2>Tickets and member notices</h2>
<p class="hint">Tickets open with `/ticket open` and remain visible to the opener and the configured staff role. Welcome and goodbye messages support `{user}` and `{server}`.</p>
<form id="discord-community-form">
<label for="discord-ticket-category">Ticket category ID</label><input id="discord-ticket-category" inputmode="numeric" maxlength="25" placeholder="Required for tickets">
<label for="discord-ticket-staff-role">Ticket staff role ID</label><input id="discord-ticket-staff-role" inputmode="numeric" maxlength="25" placeholder="Required for tickets">
<label for="discord-welcome-channel">Welcome channel ID</label><input id="discord-welcome-channel" inputmode="numeric" maxlength="25" placeholder="Optional">
<textarea id="discord-welcome-message" rows="2" maxlength="500" placeholder="Welcome {user} to {server}!"></textarea>
<label for="discord-goodbye-channel">Goodbye channel ID</label><input id="discord-goodbye-channel" inputmode="numeric" maxlength="25" placeholder="Optional">
<textarea id="discord-goodbye-message" rows="2" maxlength="500" placeholder="Goodbye {user}."></textarea>
<div class="send-row"><button class="primary" type="submit">Save ticket and notice settings</button></div>
</form>
<p class="status" id="discord-community-status" role="status"></p>
</section>
<section>
<h2>Discord server moderation</h2>
<p class="hint">The consolidated bot also provides `/discord timeout`, `/discord untimeout`, `/discord kick`, `/discord ban`, `/discord unban`, and `/discord purge`. Give its Discord role the matching server permissions (Moderate Members, Kick Members, Ban Members, and Manage Messages) and keep that role above members it should moderate. Burrow staff permissions remain the first check.</p>
</section>
</div>
<div data-view="stats" hidden>
<!--stats-view-->
</div>
@@ -485,6 +601,15 @@
<div class="row"><input id="new-name" maxlength="100" placeholder="New username" autocomplete="off" spellcheck="false" aria-label="New username">
<button type="button" data-action="rename">Rename</button></div>
</div>
<div class="action">
<h3>Lost access</h3>
<p class="hint">A new random password, shown once. They are signed out everywhere and should change it on their account page.</p>
<div class="row"><label class="check"><input type="checkbox" id="temp-two-step-off"> Turn off their 2FA too</label></div>
<div class="row" style="margin-top:8px"><button type="button" data-action="tempPassword">Make temporary password</button></div>
<div class="row" style="margin-top:8px" id="temp-password-row" hidden>
<input id="temp-password" readonly aria-label="Temporary password" spellcheck="false" style="font-family:monospace">
<button type="button" id="temp-password-copy">Copy</button></div>
</div>
<div class="action">
<h3>Adventure level</h3>
<div class="row"><input id="quest-level" type="number" min="0" max="100" step="1" aria-label="Adventure level of the animal in use">
@@ -509,6 +634,8 @@
<h3>Badges</h3>
<div class="buttons" id="badge-boxes"></div>
<div class="row" style="margin-top:8px"><button type="button" data-action="badges">Set</button></div>
<div class="row" style="margin-top:8px" title="A guide's name tag and chat bubble, seen by everyone; from their next login">
<button type="button" data-action="guide" id="guide-toggle"></button></div>
<div class="row" style="margin-top:8px" title="Players link their Discord themselves, on the account page">
<span class="hint" id="discord-name"></span>
<button type="button" data-action="discord">Unlink Discord</button></div>
@@ -719,6 +846,31 @@
</section>
</div>
<div data-view="music" hidden>
<section>
<h2>Upload music</h2>
<p class="hint">An MP3 becomes a den music track at once, with no restart: players get it from the item finder (and the shop, if it is on sale) and play it in their dens like the game's own tracks. 44.1 kHz MP3s play best; 15 MB at most.</p>
<div class="actions">
<div class="action">
<h3>The track</h3>
<div class="row"><input id="music-file" type="file" accept=".mp3,audio/mpeg" aria-label="MP3 file"></div>
<div class="row" style="margin-top:8px"><input id="music-name" maxlength="40" placeholder="Name" aria-label="Name"></div>
<div class="row" style="margin-top:8px"><input id="music-cost" type="number" min="0" placeholder="Price in gems (0)" aria-label="Price in gems">
<label class="check"><input type="checkbox" id="music-shop"> On sale in the shop</label></div>
<div class="row" style="margin-top:8px"><button type="button" class="primary" id="music-upload">Upload</button></div>
</div>
</div>
<p class="status" id="music-status" role="status"></p>
</section>
<section>
<h2>Uploaded tracks</h2>
<div class="table-wrap"><table>
<thead><tr><th>Track</th><th class="num">Den item</th><th>Uploaded</th><th class="num">Size</th><th></th></tr></thead>
<tbody id="music-list"></tbody>
</table></div>
<div class="empty" id="no-music" hidden>None yet.</div>
</section>
</div>
<div data-view="items" hidden>
<section>
<h2 id="item-form-title">Make an item</h2>
@@ -907,6 +1059,34 @@
</div>
<p class="status" id="announce-status" role="status"></p>
</section>
<section>
<h2>Redemption codes</h2>
<p class="hint">For the game's Redeem Code window (in its settings). Each account may use a code once; "uses" is how many may use it in all, 0 for any number.</p>
<form id="code-form">
<div class="row">
<input id="code-code" maxlength="32" placeholder="CODE" autocomplete="off" spellcheck="false" aria-label="Code" required style="text-transform:uppercase">
<select id="code-kind" aria-label="What it gives">
<option value="clothing">Clothing</option>
<option value="den">Den item</option>
<option value="gems">Gems</option>
<option value="diamonds">Diamonds</option>
</select>
</div>
<div class="row">
<input id="code-item" type="number" min="1" placeholder="Item id" aria-label="Item id">
<input id="code-color" placeholder="Colour (optional)" aria-label="Colour" autocomplete="off">
<input id="code-amount" type="number" min="1" placeholder="Amount" aria-label="Amount" hidden>
<input id="code-uses" type="number" min="0" value="0" aria-label="Uses in all" title="Uses in all, 0 for any number">
<button class="primary" type="submit">Make</button>
</div>
</form>
<p class="status" id="code-status" role="status"></p>
<table>
<thead><tr><th>Code</th><th>Gives</th><th>Used</th><th></th></tr></thead>
<tbody id="codes"></tbody>
</table>
<div class="empty" id="no-codes" hidden>No codes yet.</div>
</section>
</div>
</div>
@@ -947,6 +1127,22 @@
<label class="check"><input id="debug-onsale" type="checkbox"> Everything on sale</label>
<p class="status" id="debug-sale-status" role="status"></p>
</section>
<section>
<h2>Worlds</h2>
<form id="debug-worlds-form" class="row">
<label for="debug-worlds">How many worlds</label>
<input id="debug-worlds" type="number" min="1" max="10" style="width:5em">
<button type="submit">Set</button>
</form>
<p class="hint">Aldan, Congo, Draa and on. Takes effect at once; anyone in a world taken away is moved to Aldan.</p>
<p class="status" id="debug-worlds-status" role="status"></p>
</section>
<section>
<h2>Theatre browser (experimental)</h2>
<label class="check"><input id="debug-theatre-browser" type="checkbox"> Players may open a web browser on the theatre screen</label>
<p class="hint">For each player alone, on desktop client 1.3.3 or newer; nothing they see reaches the server. The client's browser is an old Chrome, so a bad site could harm a player's computer.</p>
<p class="status" id="debug-browser-status" role="status"></p>
</section>
</div>
</div>
@@ -1002,6 +1198,8 @@
let tab = "overview";
let lastLogId = 0;
let timer = null;
// Older responses must never overwrite a newer account search.
let accountSearchRun = 0;
const api = async (path, body) => {
const response = await fetch(`/dashboard/api/admin/${path}`, body === undefined ? {} : {
@@ -1018,6 +1216,35 @@
return {ok: response.ok, status: response.status, data};
};
// the redemption codes (Messages): what each gives and how often it was used
const renderCodes = list => {
$("codes").replaceChildren(...list.map(code => {
const row = el("tr");
const gives = code.kind === "clothing" ? `Clothing ${code.item}${code.color !== null ? ` (colour ${code.color})` : ""}`
: code.kind === "den" ? `Den item ${code.item}` : `${code.amount.toLocaleString()} ${code.kind}`;
const button = el("button", "Delete");
button.type = "button";
button.addEventListener("click", async () => {
const result = await api("codes", {action: "remove", code: code.code});
setStatus($("code-status"), result.data.ok || result.data.error || "That did not work.", !result.ok);
if (result.ok) {
row.remove();
}
});
const cell = el("td");
cell.append(button);
row.append(el("td", code.code), el("td", gives), el("td", code.uses ? `${code.used} of ${code.uses}` : String(code.used)), cell);
return row;
}));
$("no-codes").hidden = list.length > 0;
};
const showCodeFields = () => {
const item = ["clothing", "den"].includes($("code-kind").value);
$("code-item").hidden = !item;
$("code-color").hidden = $("code-kind").value !== "clothing";
$("code-amount").hidden = item;
};
const setStatus = (element, text, bad = false) => {
element.textContent = text;
element.classList.toggle("bad", bad);
@@ -1107,6 +1334,38 @@
location.href = "/dashboard/admin/discord/login";
});
// after Discord: the linked account's 2FA code (POST discord/code)
const discordGate = (codeStep, message) => {
history.replaceState(null, "", location.pathname + location.hash);
showGate(message);
$("gate-form").hidden = codeStep;
$("discord-code-form").hidden = !codeStep;
if (codeStep) {
$("discord-sign-in").textContent = "Start again with Discord";
$("discord-code").focus();
}
};
$("discord-code-form").addEventListener("submit", async event => {
event.preventDefault();
$("discord-code-button").disabled = true;
const result = await api("discord/code", {code: $("discord-code").value.trim()});
$("discord-code-button").disabled = false;
$("discord-code").value = "";
if (result.ok) {
$("discord-code-form").hidden = true;
$("gate-form").hidden = false;
state = {needsSetup: false, needsSetupCode: false, signedIn: true};
showPanel();
}
else if (result.data.expired) {
discordGate(false, result.data.error);
}
else {
setStatus($("gate-status"), result.data.error || "That did not work.", true);
}
});
$("sign-out").addEventListener("click", async () => {
await api("logout", {});
state.signedIn = false;
@@ -1155,6 +1414,163 @@
$("server-facts").replaceChildren(...facts.flatMap(([name, value]) => [el("dt", name), el("dd", String(value))]));
};
const renderDiscord = data => {
const configured = data.botTokenConfigured && data.guildId;
$("discord-bot-summary").textContent = !configured
? "The Discord staff bot is off. Set AJ_DISCORD_BOT_TOKEN and AJ_DISCORD_GUILD_ID, then restart the server."
: data.connected ? "The Discord staff bot is connected and ready." : "The Discord staff bot is configured but is not connected. Check the server log and bot permissions.";
const facts = [
["Bot token", data.botTokenConfigured ? "Configured" : "Missing"],
["Guild", data.guildId || "Missing"],
["Connection", data.connected ? "Connected" : "Not connected"],
["Commands", (data.commands || []).join(", ") || "None"],
];
$("discord-bot-facts").replaceChildren(...facts.flatMap(([name, value]) => [el("dt", name), el("dd", value)]));
$("discord-modules").replaceChildren(...(data.modules || []).map(module => {
const row = el("tr");
row.append(el("td", module.name), el("td", module.enabled ? "Enabled" : "Off / needs setup"), el("td", module.detail));
return row;
}));
$("discord-bot-status").textContent = configured
? "Credentials and webhook secrets are intentionally never shown in this dashboard."
: "Add the missing environment variables to the service that starts Burrow; dashboard settings cannot store bot secrets.";
$("discord-bot-status").classList.toggle("bad", !configured || !data.connected);
const editingStatusCard = ["discord-status-title", "discord-status-note", "discord-status-banner"].includes(document.activeElement && document.activeElement.id);
if (!editingStatusCard) {
$("discord-status-title").value = data.statusCard && data.statusCard.title || "Burrow status";
$("discord-status-note").value = data.statusCard && data.statusCard.note || "";
$("discord-status-banner").value = data.statusCard && data.statusCard.banner || "";
}
const editingRouting = document.activeElement && (document.activeElement.dataset.discordChannel || document.activeElement.id === "discord-github-repository");
if (!editingRouting) {
$("discord-channel-inputs").replaceChildren(...(data.channels || []).flatMap(channel => {
const label = el("label", channel.name);
label.htmlFor = `discord-channel-${channel.key}`;
const input = el("input");
input.id = label.htmlFor;
input.dataset.discordChannel = channel.key;
input.inputMode = "numeric";
input.maxLength = 25;
input.placeholder = "Discord channel ID (optional)";
input.value = channel.id || "";
input.setAttribute("aria-label", `${channel.name} Discord channel ID`);
return [label, input];
}));
$("discord-github-repository").value = data.github && data.github.repository || "";
}
const github = data.github || {};
const githubFacts = [
["Repository", github.repository || "Missing (AJ_GITHUB_REPOSITORY)"],
["Webhook secret", github.webhookSecretConfigured ? "Configured" : "Missing"],
["Update channel", (data.channels || []).some(channel => channel.name === "GitHub updates" && channel.configured) ? "Configured" : "Missing"],
["Webhook endpoint", github.endpoint || "/discord/github"],
["Update cards", github.updatesEnabled ? "Enabled" : "Off until all three settings are configured"],
];
$("github-update-facts").replaceChildren(...githubFacts.flatMap(([name, value]) => [el("dt", name), el("dd", value)]));
const editingSecurity = ["discord-security-words", "discord-security-spam", "discord-security-raid"].includes(document.activeElement && document.activeElement.id);
if (!editingSecurity) {
const security = data.security || {};
$("discord-security-enabled").checked = Boolean(security.enabled);
$("discord-security-invites").checked = Boolean(security.blockInvites);
$("discord-security-words").value = (security.blockedWords || []).join("\n");
$("discord-security-spam").value = String(security.spamLimit || 6);
$("discord-security-raid").value = String(security.raidJoinLimit || 12);
setStatus($("discord-security-status"), security.enabled
? security.monitoring ? "Security monitoring is active." : "Security is saved. Reconnect the bot after enabling Discord Message Content and Server Members intents."
: "Security monitoring is off.", security.enabled && !security.monitoring);
}
const editingCommunity = ["discord-ticket-category", "discord-ticket-staff-role", "discord-welcome-channel", "discord-welcome-message", "discord-goodbye-channel", "discord-goodbye-message"].includes(document.activeElement && document.activeElement.id);
if (!editingCommunity) {
const community = data.community || {};
$("discord-ticket-category").value = community.ticketCategoryId || "";
$("discord-ticket-staff-role").value = community.ticketStaffRoleId || "";
$("discord-welcome-channel").value = community.welcomeChannelId || "";
$("discord-welcome-message").value = community.welcomeMessage || "";
$("discord-goodbye-channel").value = community.goodbyeChannelId || "";
$("discord-goodbye-message").value = community.goodbyeMessage || "";
}
};
const controlDiscordBot = async action => {
const buttons = ["discord-bot-start", "discord-bot-stop", "discord-bot-reconnect", "discord-bot-sync"].map($);
buttons.forEach(button => { button.disabled = true; });
const result = await api("discord/control", {action});
buttons.forEach(button => { button.disabled = false; });
setStatus($("discord-bot-status"), said(result), !result.ok);
refresh();
};
$("discord-bot-start").addEventListener("click", () => controlDiscordBot("start"));
$("discord-bot-stop").addEventListener("click", () => controlDiscordBot("stop"));
$("discord-bot-reconnect").addEventListener("click", () => controlDiscordBot("reconnect"));
$("discord-bot-sync").addEventListener("click", () => controlDiscordBot("sync"));
$("discord-routing-form").addEventListener("submit", async event => {
event.preventDefault();
const button = event.submitter;
if (button) button.disabled = true;
const fields = {githubRepository: $("discord-github-repository").value};
for (const input of $("discord-channel-inputs").querySelectorAll("input[data-discord-channel]")) {
fields[input.dataset.discordChannel] = input.value;
}
const result = await api("discord/config", fields);
if (button) button.disabled = false;
setStatus($("discord-routing-status"), said(result), !result.ok);
if (result.ok) refresh();
});
$("discord-security-form").addEventListener("submit", async event => {
event.preventDefault();
const button = event.submitter;
if (button) button.disabled = true;
const result = await api("discord/security", {
enabled: $("discord-security-enabled").checked,
blockInvites: $("discord-security-invites").checked,
blockedWords: $("discord-security-words").value,
spamLimit: Number($("discord-security-spam").value),
raidJoinLimit: Number($("discord-security-raid").value),
});
if (button) button.disabled = false;
setStatus($("discord-security-status"), said(result), !result.ok);
if (result.ok) refresh();
});
$("discord-community-form").addEventListener("submit", async event => {
event.preventDefault();
const button = event.submitter;
if (button) button.disabled = true;
const result = await api("discord/community", {
ticketCategoryId: $("discord-ticket-category").value, ticketStaffRoleId: $("discord-ticket-staff-role").value,
welcomeChannelId: $("discord-welcome-channel").value, welcomeMessage: $("discord-welcome-message").value,
goodbyeChannelId: $("discord-goodbye-channel").value, goodbyeMessage: $("discord-goodbye-message").value,
});
if (button) button.disabled = false;
setStatus($("discord-community-status"), said(result), !result.ok);
if (result.ok) refresh();
});
$("discord-status-form").addEventListener("submit", async event => {
event.preventDefault();
const button = event.submitter;
if (button) button.disabled = true;
const result = await api("discord/status", {title: $("discord-status-title").value, note: $("discord-status-note").value, banner: $("discord-status-banner").value});
if (button) button.disabled = false;
setStatus($("discord-status-card-result"), said(result), !result.ok);
if (result.ok && result.data.statusCard) {
$("discord-status-title").value = result.data.statusCard.title;
$("discord-status-note").value = result.data.statusCard.note;
$("discord-status-banner").value = result.data.statusCard.banner;
}
});
$("discord-status-publish").addEventListener("click", async () => {
const button = $("discord-status-publish");
button.disabled = true;
const result = await api("discord/status/publish", {});
button.disabled = false;
setStatus($("discord-status-card-result"), said(result), !result.ok);
if (result.ok) refresh();
});
const accountState = account => {
const tags = [];
if (account.online) {
@@ -1483,6 +1899,8 @@
label.append(box, ` ${badge.label}`);
return label;
}));
$("temp-two-step-off").disabled = !current || !current.twoStep;
$("guide-toggle").textContent = current && current.guide ? "Remove guide" : "Make guide";
$("discord-name").textContent = current && current.discord ? `Discord: ${current.discord}` : "No Discord linked";
$("admin-dashboard-access").textContent = current && current.adminDashboardAccess ? "Remove Discord dashboard access" : "Allow Discord dashboard access";
$("admin-dashboard-access").disabled = !current || (!current.discord && !current.adminDashboardAccess);
@@ -1519,7 +1937,8 @@
selected = username;
current = null;
setStatus($("detail-status"), "");
for (const id of ["new-name", "ban-hours", "silence-hours", "message-text", "gems-amount", "gift-value", "gift-text"]) {
$("temp-password-row").hidden = true;
for (const id of ["temp-password", "new-name", "ban-hours", "silence-hours", "message-text", "gems-amount", "gift-value", "gift-text"]) {
$(id).value = "";
}
hashArg = username;
@@ -1606,7 +2025,7 @@
stateCell.append(el("span", "Hardware banned", "tag bad"));
}
row.append(el("td", alt.username), stateCell,
el("td", alt.devices.length ? `${alt.devices.map(kind => KIND_NAMES[kind] || kind).join(", ")}${alt.weak ? " (weak)" : ""}` : "—"),
el("td", alt.devices.length ? `${alt.devices.map(kind => KIND_NAMES[kind] || kind).join(", ")}` : "—"),
el("td", alt.addresses ? String(alt.addresses) : "—", "num"));
row.addEventListener("click", () => openAccount(alt.username));
return row;
@@ -1672,6 +2091,8 @@
case "role": return {role: $("role-select").value};
case "permissions": return permissionChoices();
case "adminDashboardAccess": return {on: !(current || {}).adminDashboardAccess};
case "guide": return {on: !(current || {}).guide};
case "tempPassword": return {twoStepOff: $("temp-two-step-off").checked};
case "message": return {text: $("message-text").value};
case "gems": return {amount: numberFrom("gems-amount")};
case "gift": return giftBody();
@@ -1683,6 +2104,10 @@
}
};
$("temp-password-copy").addEventListener("click", () => {
navigator.clipboard.writeText($("temp-password").value).catch(() => $("temp-password").select());
});
// the "N ago" buttons fill the last-seen box and press Set.
$("detail").addEventListener("click", event => {
const quick = event.target.closest("button[data-ago]");
@@ -1712,6 +2137,9 @@
if (action === "banDevices" && !window.confirm(`Hardware ban ${selected}? Everyone on their hardware is put out.`)) {
return;
}
if (action === "tempPassword" && !window.confirm(`Give ${selected} a new random password? Their old one stops working and they are signed out everywhere.`)) {
return;
}
button.disabled = true;
const result = await api("account", {username: selected, action, ...actionBody(action)});
button.disabled = false;
@@ -1719,6 +2147,11 @@
if (result.ok && action === "delete") {
selected = null;
}
if (result.ok && action === "tempPassword") {
$("temp-password").value = result.data.password;
$("temp-password-row").hidden = false;
$("temp-two-step-off").checked = false;
}
if (result.ok && action === "rename") {
selected = result.data.username;
$("new-name").value = "";
@@ -1735,6 +2168,7 @@
// the server searches, once typing stops for a moment.
let addressWait = null;
$("account-search").addEventListener("input", () => {
accountSearchRun++;
clearTimeout(addressWait);
addressWait = setTimeout($("account-search-by").value !== "name" ? searchByAddress : refresh, $("account-search-by").value !== "name" ? 400 : 250);
});
@@ -1752,6 +2186,7 @@
}
});
$("account-search-by").addEventListener("change", () => {
accountSearchRun++;
const byAddress = $("account-search-by").value !== "name";
$("account-search").placeholder = {address: "203.0.113.7, or the start of one", device: "Hardware ID, or the start of one"}[$("account-search-by").value] || "Search";
if (byAddress) {
@@ -1761,7 +2196,10 @@
refresh();
}
});
$("account-filter").addEventListener("change", () => refresh());
$("account-filter").addEventListener("change", () => {
accountSearchRun++;
refresh();
});
const act = async (username, action, extra, statusElement) => {
const result = await api("account", {username, action, ...extra});
@@ -2041,7 +2479,7 @@
$("masterpieces").replaceChildren(...paintings.map(painting => {
const box = el("div", undefined, "painting");
const picture = el("img");
picture.src = `/admin/api/masterpiece?id=${encodeURIComponent(painting.id)}`;
picture.src = `/dashboard/api/admin/masterpiece?id=${encodeURIComponent(painting.id)}`;
picture.alt = `Painting by ${painting.creator}`;
picture.loading = "lazy";
picture.addEventListener("click", () => showPreview(picture.src));
@@ -2286,6 +2724,11 @@
$("debug-player").value = player;
}
$("debug-onsale").checked = data.everythingOnSale;
$("debug-theatre-browser").checked = data.theatreBrowser;
if (document.activeElement !== $("debug-worlds")) {
$("debug-worlds").value = data.worlds;
$("debug-worlds").max = data.maxWorlds;
}
if (debugRooms.length !== data.rooms.length) {
debugRooms = data.rooms;
renderDebugRooms();
@@ -2298,6 +2741,29 @@
setStatus($("debug-status"), result.data.ok || result.data.error || "That did not work.", !result.ok);
});
$("debug-room").addEventListener("dblclick", () => $("debug-go").click());
$("debug-theatre-browser").addEventListener("change", async () => {
const result = await api("debug", {action: "theatreBrowser", on: $("debug-theatre-browser").checked});
setStatus($("debug-browser-status"), result.data.ok || result.data.error || "That did not work.", !result.ok);
});
$("code-kind").addEventListener("change", showCodeFields);
$("code-form").addEventListener("submit", async event => {
event.preventDefault();
const result = await api("codes", {code: $("code-code").value, kind: $("code-kind").value, item: Number($("code-item").value),
color: $("code-color").value.trim(), amount: Number($("code-amount").value), uses: Number($("code-uses").value) || 0});
setStatus($("code-status"), result.data.ok || result.data.error || "That did not work.", !result.ok);
if (result.ok) {
$("code-code").value = "";
const codeList = await api("codes");
if (codeList.ok) {
renderCodes(codeList.data.codes);
}
}
});
$("debug-worlds-form").addEventListener("submit", async event => {
event.preventDefault();
const result = await api("debug", {action: "worlds", count: Number($("debug-worlds").value)});
setStatus($("debug-worlds-status"), result.data.ok || result.data.error || "That did not work.", !result.ok);
});
$("debug-onsale").addEventListener("change", async () => {
const result = await api("debug", {action: "everythingOnSale", on: $("debug-onsale").checked});
setStatus($("debug-sale-status"), result.data.ok || result.data.error || "That did not work.", !result.ok);
@@ -2578,8 +3044,8 @@
// moving), else drawn into a PNG that fits, smaller until it is small
// enough. any picture this browser can open will do (WebP, AVIF, BMP...).
// null when it cannot be read at all.
const PICTURE_SIDE = 512;
const PICTURE_BYTES = 300 * 1024;
const PICTURE_SIDE = 256;
const PICTURE_BYTES = 100 * 1024;
const preparePicture = async file => {
const kept = ["image/png", "image/jpeg", "image/gif"].includes(file.type);
let image = null;
@@ -2593,7 +3059,7 @@
image.close();
return file;
}
for (const side of [PICTURE_SIDE, 384, 256, 128]) {
for (const side of [PICTURE_SIDE, 192, 128, 96]) {
const scale = Math.min(1, side / image.width, side / image.height);
const canvas = document.createElement("canvas");
canvas.width = Math.max(1, Math.round(image.width * scale));
@@ -2830,6 +3296,91 @@
setStatus($("control-status"), said(result), !result.ok);
});
// ---- music uploaded by staff (lib/custommusic.js): an MP3 made a den
// music track, which players get from the item finder at once
const MUSIC = "/admin/api/music";
let musicShown = "";
const musicCall = async (query, body) => {
try {
const response = await fetch(`${MUSIC}${query}`, {method: "POST", headers: {"Content-Type": "audio/mpeg"}, body});
return await response.json().catch(() => ({error: "That did not work."}));
}
catch (err) {
return {error: "The server did not answer."};
}
};
const renderMusic = data => {
const tracks = data.tracks || [];
// drawn again only when something changed: a track being listened to keeps playing
const shown = JSON.stringify(tracks);
if (shown === musicShown) {
return;
}
musicShown = shown;
$("no-music").hidden = tracks.length > 0;
$("music-list").replaceChildren(...tracks.map(track => {
const row = el("tr");
const name = el("td");
const player = el("audio");
player.controls = true;
player.preload = "none";
player.src = `${MUSIC}?play=${track.id}`;
player.style.cssText = "display:block;margin-top:6px;height:32px;max-width:260px";
name.append(el("strong", track.name), player);
const actions = el("td");
actions.append(button("Delete", async () => {
if (!confirm(`Delete "${track.name}"? It is taken from every player who has it. This cannot be undone.`)) {
return;
}
const result = await musicCall(`?delete=${track.id}`, new Uint8Array(0));
setStatus($("music-status"), result.ok || result.error || "That did not work.", !result.ok);
await loadMusic();
}, "danger"));
row.append(name, el("td", String(track.id), "num"), el("td", `${when(track.createdAt)} · ${track.createdBy}${track.inShop ? ` · on sale, ${track.cost} gems` : ""}`),
el("td", `${(track.bytes / 1048576).toFixed(1)} MB`, "num"), actions);
return row;
}));
};
const loadMusic = async () => {
try {
const response = await fetch(MUSIC);
const data = await response.json().catch(() => ({}));
if (response.ok) {
renderMusic(data);
}
}
catch (err) {
// shown again with the next refresh
}
};
// the name from the file's, until one is typed
$("music-file").addEventListener("change", () => {
const file = $("music-file").files[0];
if (file && !$("music-name").value.trim()) {
$("music-name").value = file.name.replace(/\.mp3$/i, "").replace(/[_]+/g, " ").slice(0, 40);
}
});
$("music-upload").addEventListener("click", async () => {
const file = $("music-file").files[0];
if (!file || !$("music-name").value.trim()) {
setStatus($("music-status"), file ? "Give the track a name." : "Choose an MP3 first.", true);
return;
}
$("music-upload").disabled = true;
setStatus($("music-status"), "Uploading...");
const query = `?name=${encodeURIComponent($("music-name").value.trim())}&cost=${encodeURIComponent($("music-cost").value || 0)}&inShop=${$("music-shop").checked ? 1 : 0}`;
const result = await musicCall(query, new Uint8Array(await file.arrayBuffer()));
$("music-upload").disabled = false;
setStatus($("music-status"), result.ok || result.error || "That did not work.", !result.ok);
if (result.ok) {
for (const id of ["music-file", "music-name", "music-cost"]) {
$(id).value = "";
}
$("music-shop").checked = false;
}
await loadMusic();
});
const refresh = async () => {
clearTimeout(timer);
if (!state || !state.signedIn) {
@@ -2860,15 +3411,30 @@
quickLockFind();
}
}
else if (tab === "accounts") {
const query = $("account-search-by").value !== "name" ? "" : $("account-search").value.trim();
result = await api(`accounts?q=${encodeURIComponent(query)}&filter=${$("account-filter").value}`);
else if (tab === "discord") {
result = await api("discord");
if (result.ok) {
renderDiscord(result.data);
}
}
else if (tab === "accounts") {
const searchBy = $("account-search-by").value;
const query = searchBy !== "name" ? "" : $("account-search").value.trim();
const filter = $("account-filter").value;
const searchRun = ++accountSearchRun;
result = await api(`accounts?q=${encodeURIComponent(query)}&filter=${filter}`);
// A slower earlier search must not replace what the person just typed.
if (result.ok && searchRun === accountSearchRun && tab === "accounts"
&& searchBy === $("account-search-by").value
&& query === (searchBy !== "name" ? "" : $("account-search").value.trim())
&& filter === $("account-filter").value) {
accounts = result.data.accounts;
accountTotal = result.data.total;
badges = result.data.badges || [];
await loadCurrent();
renderAccounts();
if (searchRun === accountSearchRun && tab === "accounts") {
renderAccounts();
}
}
}
else if (tab === "stats") {
@@ -2889,6 +3455,9 @@
else if (tab === "wear-rules") {
await loadWearRules();
}
else if (tab === "music") {
await loadMusic();
}
else if (tab === "items") {
result = await api("items");
if (result.ok) {
@@ -2969,6 +3538,10 @@
if (result.ok) {
renderMessages(result.data);
}
const codeList = await api("codes");
if (codeList.ok) {
renderCodes(codeList.data.codes);
}
}
else if (tab === "debug") {
result = await api("debug");
@@ -3073,9 +3646,23 @@
showGate("The server did not answer.");
return;
}
const discordResult = new URLSearchParams(location.search).get("discord");
if (state.signedIn) {
showPanel();
}
else if (discordResult === "code") {
discordGate(true, "");
}
else if (discordResult) {
discordGate(false, {
denied: "That Discord account is not allowed to sign in here.",
twostep: "Turn on 2FA for the linked account first.",
expired: "The Discord sign-in request expired. Try again.",
cancelled: "Discord sign-in was cancelled.",
discord: "Discord could not confirm that sign-in. Try again.",
off: "Discord sign-in is not configured.",
}[discordResult] || "");
}
else {
showGate();
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

+7 -1
View File
@@ -25,17 +25,21 @@
-webkit-font-smoothing: antialiased;
}
#status { margin: 0; text-align: center; }
button { display: none; border: 1px solid #8c8c8c; border-radius: 5px; padding: 6px 12px; background: transparent; color: #ddd; font: inherit; cursor: pointer; }
button.show { display: block; }
</style>
</head>
<body>
<div id="widget"></div>
<p id="status" role="status">Checking…</p>
<button id="retry" type="button">Try again</button>
<script src="/captcha.js"></script>
<script>
"use strict";
const action = new URLSearchParams(location.search).get("action") === "signup" ? "signup" : "login";
const status = document.getElementById("status");
const retry = document.getElementById("retry");
const done = token => {
if (window.burrowCaptcha) {
window.burrowCaptcha.done(token);
@@ -53,10 +57,12 @@
}});
check.answer().then(token => {
if (!token) {
status.textContent = "Captcha failed. Close this and try again.";
status.textContent = "Captcha could not load. Check your connection or content blocker.";
retry.classList.add("show");
}
});
}
retry.addEventListener("click", () => location.reload());
</script>
</body>
</html>
+72 -23
View File
@@ -10,14 +10,29 @@
// captcha.FAILED then), and check.reset() after it: an answer is good once.
window.captcha = (() => {
const siteKey = "{{siteKey}}";
const LOAD_TIMEOUT_MS = 15000;
let loading = null;
const load = () => {
loading = loading || new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
script.onload = () => resolve(window.turnstile);
const timer = setTimeout(() => {
loading = null;
reject(new Error("the captcha took too long to load"));
}, LOAD_TIMEOUT_MS);
script.onload = () => {
clearTimeout(timer);
if (window.turnstile && typeof window.turnstile.render === "function") {
resolve(window.turnstile);
}
else {
loading = null;
reject(new Error("the captcha did not start"));
}
};
script.onerror = () => {
clearTimeout(timer);
loading = null;
reject(new Error("the captcha did not load"));
};
@@ -26,12 +41,15 @@ window.captcha = (() => {
return loading;
};
// `options`: {appearance} ("interaction-only" by default: seen only when
// cloudflare wants a click), {onAnswer(token)}.
// `options`: {appearance} ("always" by default: hidden till cloudflare
// wanted a click, it was taken for one that never showed), {onAnswer(token)}.
const MAX_RETRIES = 2; // a widget that errs is started again this often first
const mount = (element, action, options = {}) => {
let widget = null;
let answer = null; // a token, "" when none could be had, null while waiting
let waiting = [];
let retries = 0;
let starting = false;
const settle = value => {
answer = value;
if (value && options.onAnswer) {
@@ -42,42 +60,73 @@ window.captcha = (() => {
}
waiting = [];
};
if (siteKey) {
const start = () => {
if (!siteKey || starting || widget !== null) {
return;
}
starting = true;
load().then(turnstile => {
widget = turnstile.render(element, {
sitekey: siteKey,
action,
theme: "dark",
appearance: options.appearance || "interaction-only",
callback: settle,
"expired-callback": () => {
answer = null;
},
// its code is cloudflare's (110200: this site's name is not on the widget)
"error-callback": code => {
console.log(`captcha error ${code}`);
settle("");
},
});
}, () => settle(""));
}
starting = false;
try {
widget = turnstile.render(element, {
sitekey: siteKey,
action,
theme: "dark",
appearance: options.appearance || "always",
callback: value => {
retries = 0;
settle(value);
},
"expired-callback": () => {
answer = null;
},
// its code is cloudflare's (110200: this site's name is not on
// the widget). many pass with a second go: it is had first.
"error-callback": code => {
console.log(`captcha error ${code}`);
if (retries < MAX_RETRIES) {
retries++;
answer = null;
setTimeout(() => window.turnstile.reset(widget), 1000 * retries);
return true;
}
settle("");
return true;
},
});
}
catch (err) {
console.log(`captcha could not start: ${err.message}`);
settle("");
}
}, () => {
starting = false;
settle("");
});
};
start();
return {
on: Boolean(siteKey),
answer: () => {
if (!siteKey) {
return Promise.resolve(undefined);
}
// one that could not load is tried again when an answer is wanted
if (answer === "" && widget === null) {
answer = null;
start();
}
return answer !== null ? Promise.resolve(answer) : new Promise(resolve => waiting.push(resolve));
},
// (a widget that never loaded keeps its "" so nothing waits on it)
reset: () => {
if (widget !== null) {
answer = null;
retries = 0;
window.turnstile.reset(widget);
}
},
};
};
return {on: Boolean(siteKey), mount, FAILED: "Captcha could not load. Reload the page."};
return {on: Boolean(siteKey), mount, FAILED: "Captcha could not load. Check your connection or content blocker, then reload."};
})();
+973 -9
View File
File diff suppressed because it is too large. Load diff
+67
View File
@@ -0,0 +1,67 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Item preview</title>
<style>
html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: #1a1a1a; }
ruffle-player, ruffle-object, ruffle-embed { display: block; width: 100%; height: 100%; }
</style>
<script>
// ruffle's own settings: no menus, overlays or sound.
window.RufflePlayer = {config: {
publicPath: "https://cdn.jsdelivr.net/npm/@ruffle-rs/[email protected]/",
polyfills: false,
autoplay: "on",
unmuteOverlay: "hidden",
splashScreen: false,
contextMenu: "off",
letterbox: "off",
backgroundColor: "#1A1A1A", // the giver page's
volume: 0,
openUrlMode: "deny",
allowScriptAccess: false,
showSwfDownload: false,
warnOnUnsupportedContent: false,
logLevel: "error",
}};
</script>
<script src="https://cdn.jsdelivr.net/npm/@ruffle-rs/[email protected]/ruffle.js" integrity="sha256-JgNqlFZwiN+z3oinWejtEKTOoHspUArzbzRe70JCAJg=" crossorigin="anonymous"></script>
</head>
<body>
<script>
"use strict";
// one den item for the web item giver (public/items.html), in a frame of
// its own: #id=&v=&tint=rrggbb&s=, as Give would give it. its art plays
// in public/item-preview.swf (tools/preview-host), which sets the
// variant and tint as a den does. served sandboxed (lib/manage.js): this
// page has no origin, so no sign-in, of its own.
let player = null;
const show = () => {
const wanted = new URLSearchParams(location.hash.slice(1));
const id = /^\d{1,9}$/.test(wanted.get("id") || "") ? wanted.get("id") : null;
if (player) {
player.remove();
player = null;
}
if (!id || !window.RufflePlayer || !window.RufflePlayer.newest) {
return;
}
player = window.RufflePlayer.newest().createPlayer();
document.body.append(player);
const parameters = {art: new URL(`/account/art/den/${id}`, location.href).href, version: String(Number(wanted.get("v")) || 0)};
if (/^[0-9a-f]{6}$/i.test(wanted.get("tint") || "")) {
parameters.tint = wanted.get("tint");
parameters.strength = String(Number(wanted.get("s")) || 100);
}
const movie = {url: new URL("/account/item-preview.swf", location.href).href, parameters};
(player.ruffle ? player.ruffle().load(movie) : player.load(movie)).catch(() => {});
};
window.addEventListener("hashchange", show);
show();
</script>
</body>
</html>
Binary file not shown.
+786
View File
@@ -0,0 +1,786 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Item giver</title>
<link rel="icon" type="image/png" href="/logo-square.png">
<style>
/* the account page's look (public/account.html): black and white, in
the game's own text font. the only colours are the items' own. */
@font-face { font-family: "DigitalDelivery"; font-weight: 400; src: url("/fonts/CCDigitalDelivery-Regular.otf") format("opentype"); }
@font-face { font-family: "DigitalDelivery"; font-weight: 700; src: url("/fonts/CCDigitalDelivery-Bold.otf") format("opentype"); }
:root {
color-scheme: dark;
--bg: #000;
--panel: #0d0d0d;
--raised: #1a1a1a;
--line: #2e2e2e;
--text: #fff;
--muted: #8c8c8c;
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
::selection { background: #fff; color: #000; }
body {
margin: 0;
padding: 32px 16px 48px;
background: var(--bg);
color: var(--text);
font: 15px/1.4 "DigitalDelivery", system-ui, "Segoe UI", sans-serif;
-webkit-font-smoothing: antialiased;
}
a { color: inherit; text-underline-offset: 3px; }
h1 { margin: 0; font-size: 26px; font-weight: 700; flex: 1; }
h2 { margin: 0 0 6px; font-size: 17px; font-weight: 700; }
h3 { margin: 16px 0 8px; font-size: 14px; font-weight: 700; }
p { margin: 0 0 12px; color: var(--muted); }
.wrap { max-width: 760px; margin: 0 auto; }
header { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; }
header img { width: 40px; height: 40px; }
section {
padding: 20px;
margin-bottom: 16px;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 18px;
}
input, select {
font: inherit;
color: var(--text);
background: var(--bg);
border: 1px solid var(--line);
border-radius: 14px;
padding: 9px 14px 10px;
}
input:hover, select:hover { border-color: #555; }
input:focus, select:focus { outline: none; border-color: var(--text); }
input:disabled { opacity: 0.4; }
button, a.button {
font: inherit;
color: var(--text);
background: none;
border: 1px solid var(--line);
border-radius: 999px;
padding: 7px 16px 8px;
cursor: pointer;
white-space: nowrap;
text-decoration: none;
}
button:hover, a.button:hover { background: var(--raised); border-color: #555; }
button:disabled { opacity: 0.45; cursor: default; }
button:focus-visible, a:focus-visible, input:focus-visible { outline: 2px solid var(--text); outline-offset: 2px; }
button.primary { font-weight: 700; color: #000; background: var(--text); border-color: var(--text); }
button.primary:hover { background: #d9d9d9; border-color: #d9d9d9; }
button[aria-pressed="true"] { border-color: var(--text); background: var(--raised); }
.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
#search-row input { flex: 1; min-width: 180px; }
.status { min-height: 20px; margin: 10px 0 0; font-size: 13px; color: var(--muted); }
.status.bad { color: var(--text); }
.status.bad::before { content: "! "; font-weight: 700; }
#results { list-style: none; margin: 12px 0 0; padding: 0; display: grid; gap: 6px; }
#results button {
display: flex; width: 100%; gap: 10px; align-items: baseline;
border-radius: 14px; padding: 9px 14px 10px; text-align: left; white-space: normal;
}
#results .name { flex: 1; overflow-wrap: anywhere; }
.meta { font-size: 12px; color: var(--muted); white-space: nowrap; }
.swatches { display: inline-flex; gap: 3px; vertical-align: middle; }
.swatch { width: 16px; height: 16px; border-radius: 5px; border: 1px solid rgba(255, 255, 255, 0.25); }
#presets, #variants { display: flex; flex-wrap: wrap; gap: 6px; }
#presets button, #variants button { padding: 6px 10px 7px; border-radius: 12px; }
.slot { display: grid; grid-template-columns: 74px 44px 1fr; gap: 8px; align-items: center; margin-bottom: 8px; }
.slot span { color: var(--muted); font-size: 13px; }
.colour-slot { grid-template-columns: 74px 44px minmax(0, 160px) 96px; }
input.aj { width: 100%; min-width: 0; font-variant-numeric: tabular-nums; }
#whole-row { margin-top: 4px; }
#whole-row > span:first-child { width: 74px; color: var(--muted); font-size: 13px; }
#whole { width: 190px; }
#whole-note { white-space: normal; }
input[type="color"] { width: 44px; height: 38px; padding: 3px; border-radius: 10px; cursor: pointer; }
input.hex { width: 100%; max-width: 160px; font-variant-numeric: tabular-nums; text-transform: lowercase; }
input[type="range"] { flex: 1; padding: 0; border: none; accent-color: #fff; }
label.check { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; }
#give-row { margin-top: 16px; }
#item-head { display: flex; gap: 16px; align-items: center; }
#item-head > div:first-child { flex: 1; min-width: 0; }
#preview {
position: relative; flex: none; width: 160px; height: 160px;
display: grid; place-items: center;
background: var(--raised); border: 1px solid var(--line); border-radius: 14px; overflow: hidden;
}
#preview canvas, #preview img { max-width: 144px; max-height: 144px; }
#preview iframe { width: 100%; height: 100%; border: 0; }
#preview-note { position: absolute; inset: auto 8px 6px; font-size: 11px; text-align: center; color: var(--muted); }
@media (max-width: 480px) {
.slot { grid-template-columns: 64px 44px 1fr; }
.colour-slot { grid-template-columns: 64px 44px minmax(0, 1fr) 56px; }
.colour-slot span { white-space: nowrap; }
#whole-row > span:first-child { width: auto; }
#whole { width: 100%; }
#item-head { flex-direction: column-reverse; align-items: flex-start; }
}
</style>
</head>
<body>
<div class="wrap">
<header>
<img src="/logo.png" alt="">
<h1>Item giver</h1>
<a class="button" href="/account">Your account</a>
</header>
<section id="gate" hidden>
<h2 id="gate-title">Sign in first</h2>
<p id="gate-text">The item giver uses your account page's sign-in.</p>
<a class="button" href="/account">Go to your account page</a>
</section>
<section id="finder" hidden>
<p id="who"></p>
<div class="row" id="search-row">
<input id="query" type="search" placeholder="Name or id" maxlength="60" autocomplete="off" spellcheck="false" aria-label="Search items">
<select id="kind" aria-label="Kind of item">
<option value="all">Everything</option>
<option value="clothing">Clothing</option>
<option value="den">Den items</option>
</select>
</div>
<p class="status" id="search-status" role="status"></p>
<ul id="results"></ul>
</section>
<section id="detail" hidden>
<div id="item-head">
<div>
<h2 id="item-name"></h2>
<p class="meta" id="item-meta"></p>
</div>
<div id="preview" aria-label="How it looks">
<canvas id="preview-icon" hidden></canvas>
<img id="preview-art" alt="" hidden>
<iframe id="preview-den" title="How it looks" sandbox="allow-scripts" hidden></iframe>
<span id="preview-note"></span>
</div>
</div>
<div id="clothing-part">
<h3>The item's own colours</h3>
<div id="presets"></div>
<h3>Your own colours</h3>
<div id="slots"></div>
<div class="row" id="whole-row">
<span>Whole item</span>
<input class="aj" id="whole" inputmode="numeric" maxlength="11" spellcheck="false" autocomplete="off" placeholder="AJ colour" aria-label="The whole item's colour as the game writes it">
<span class="meta" id="whole-note"></span>
</div>
</div>
<div id="den-part">
<h3>Variant</h3>
<div id="variants"></div>
<p id="no-variants" hidden>This item has no other variants.</p>
<h3>Tint</h3>
<p id="tint-off" hidden>Mannequins cannot be tinted.</p>
<div id="tint-on">
<label class="check"><input id="tint" type="checkbox"> The whole item in shades of a colour</label>
<div class="slot" style="margin-top:10px">
<span>Colour</span>
<input type="color" id="tint-picker" value="#4ab3f4" aria-label="Tint colour">
<input class="hex" id="tint-hex" value="#4ab3f4" maxlength="7" spellcheck="false" aria-label="Tint colour as #RRGGBB">
</div>
<div class="row">
<span class="meta">Strength</span>
<input type="range" id="tint-strength" min="1" max="100" value="70" aria-label="Tint strength">
<span class="meta" id="tint-strength-text">70%</span>
</div>
</div>
</div>
<div class="row" id="give-row">
<button class="primary" id="give" type="button">Give</button>
<span class="meta" id="give-what"></span>
</div>
<p class="status" id="give-status" role="status"></p>
</section>
</div>
<script>
"use strict";
// the item giver on the web (lib/admin.js searchFor and giveAs, by way
// of lib/manage.js), signed in as on the account page: items go to that
// account, as the in-game giver's go to the one playing.
const $ = id => document.getElementById(id);
const KINDS = {clothing: "Clothing", den: "Den item"};
let chosen = null; // the result picked
let preset = 0; // the item's own colour picked, or null for the slots' own
let variant = 0;
const setStatus = (id, text, bad = false) => {
$(id).textContent = text;
$(id).classList.toggle("bad", bad);
};
const api = async (path, body) => {
try {
const response = await fetch(`/account/api/${path}`, body === undefined ? {} : {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(body),
});
return {ok: response.ok, status: response.status, data: await response.json().catch(() => ({}))};
}
catch (err) {
return {ok: false, status: 0, data: {error: "The server did not answer."}};
}
};
// "#abc", "abc", "#aabbcc" or "aabbcc" as "#aabbcc"; null for anything else.
const readHex = text => {
const match = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(String(text).trim());
if (!match) {
return null;
}
const digits = match[1].length === 3 ? match[1].replace(/./g, digit => digit + digit) : match[1];
return `#${digits.toLowerCase()}`;
};
const swatches = colours => {
const box = document.createElement("span");
box.className = "swatches";
for (const colour of colours) {
const swatch = document.createElement("span");
swatch.className = "swatch";
swatch.style.background = `#${colour}`;
box.append(swatch);
}
return box;
};
// a colour picker and a #RRGGBB box that follow each other; `onChange`
// is told of each colour taken.
const pairUp = (picker, box, onChange) => {
picker.addEventListener("input", () => {
box.value = picker.value;
onChange();
});
box.addEventListener("input", () => {
const hex = readHex(box.value);
box.setCustomValidity(hex ? "" : "#RRGGBB");
if (hex) {
picker.value = hex;
onChange();
}
});
box.addEventListener("change", () => {
const hex = readHex(box.value);
box.value = hex || picker.value;
box.setCustomValidity("");
});
};
// the game's way of writing colours: one number for the whole item, its
// four colours' places in the game's palette of 256, colour 1 the top
// byte; written unsigned, or signed as lists of the game's colours often
// have them. top byte 0xFD: a custom colour, four RGB values of the
// server's own (lib/colours.js), not palette places.
let palette = null; // the game's 256 colours, "#rrggbb", once the server says
let customId = null; // the custom colour the four make, when one is known
const CUSTOM_TOP = 0xFD;
const isCustom = value => value >>> 24 === CUSTOM_TOP;
const readWhole = text => {
const value = /^-?\d{1,10}$/.test(String(text).trim()) ? Number(String(text).trim()) : NaN;
return value >= -0x80000000 && value <= 0xFFFFFFFF ? value >>> 0 : null;
};
// one colour's place, 0 to 255; -128 to -1 are 128 to 255 written signed
const readIndex = text => {
const value = /^-?\d{1,3}$/.test(String(text).trim()) ? Number(String(text).trim()) : NaN;
return value >= -128 && value <= 255 ? (value + 256) % 256 : null;
};
const pack = indexes => indexes.reduce((value, index) => value * 256 + index, 0);
// a slot set: its colour, and its place in the palette or null. `from`
// is the box typed in, left as typed.
const setSlot = (slot, hex, index, from = null) => {
slot.index = index;
if (from !== "hex") {
slot.picker.value = hex;
slot.box.value = hex;
}
if (from !== "aj") {
slot.aj.value = index === null ? "" : String(index);
slot.aj.setCustomValidity("");
}
slot.aj.placeholder = index === null && palette ? "custom" : "AJ";
};
// what Give gives: a colour id, or null for a custom colour still to make.
const wholeValue = () => {
if (preset !== null && chosen && chosen.presets[preset]) {
return chosen.presets[preset].id;
}
if (customId !== null) {
return customId;
}
return slots.every(slot => slot.index !== null) ? pack(slots.map(slot => slot.index)) : null;
};
let lookupTimer = null;
const showWhole = () => {
const value = wholeValue();
if (document.activeElement !== $("whole")) {
$("whole").value = value === null ? "" : String(value);
$("whole").setCustomValidity("");
}
$("whole-note").textContent = value === null ? "A new custom colour, made when you give it."
: `${value} unsigned · ${value | 0} signed${isCustom(value) ? " · a custom colour" : ""}`;
// four colours not all the palette's: a custom colour they make already?
clearTimeout(lookupTimer);
if (value === null) {
const asked = slots.map(slot => slot.picker.value.slice(1)).join(",");
lookupTimer = setTimeout(async () => {
const result = await api(`colour?rgbs=${asked}`);
if (result.ok && result.data.id !== null && preset === null && customId === null
&& slots.map(slot => slot.picker.value.slice(1)).join(",") === asked) {
customId = result.data.id;
showWhole();
showChoice();
}
}, 200);
}
};
// a whole item's colour taken: from the whole box (`from`) or one of the item's own.
const applyWhole = async (value, from = null, own = null) => {
if (isCustom(value)) {
const colours = own || await api(`colour?id=${value}`).then(result => (result.ok ? result.data.colours : null));
if (!colours) {
$("whole-note").textContent = "No such custom colour.";
return;
}
if (from === "whole" && readWhole($("whole").value) !== value) {
return; // typed on since
}
colours.forEach((colour, index) => setSlot(slots[index], `#${colour}`, null));
customId = value;
}
else {
[24, 16, 8, 0].forEach((shift, index) => {
const place = value >>> shift & 255;
setSlot(slots[index], palette ? palette[place] : own ? `#${own[index]}` : slots[index].picker.value, place);
});
customId = null;
}
showChoice();
};
const slots = [];
for (let slot = 0; slot < 4; slot++) {
const row = document.createElement("div");
row.className = "slot colour-slot";
const name = document.createElement("span");
name.textContent = `Colour ${slot + 1}`;
const picker = document.createElement("input");
picker.type = "color";
picker.value = "#ffffff";
picker.setAttribute("aria-label", `Colour ${slot + 1}`);
const box = document.createElement("input");
box.className = "hex";
box.maxLength = 7;
box.spellcheck = false;
box.value = "#ffffff";
box.setAttribute("aria-label", `Colour ${slot + 1} as #RRGGBB`);
const aj = document.createElement("input");
aj.className = "aj";
aj.inputMode = "numeric";
aj.maxLength = 4;
aj.spellcheck = false;
aj.autocomplete = "off";
aj.placeholder = "AJ";
aj.title = "Its place in the game's palette: 0 to 255 (-128 to -1 written signed)";
aj.setAttribute("aria-label", `Colour ${slot + 1} as the game writes it, 0 to 255`);
const own = {picker, box, aj, index: null};
pairUp(picker, box, () => {
const place = palette ? palette.indexOf(picker.value) : -1;
setSlot(own, picker.value, place < 0 ? null : place, "hex");
preset = null;
customId = null;
showChoice();
});
aj.addEventListener("input", () => {
const place = readIndex(aj.value);
aj.setCustomValidity(place === null || !palette ? "0 to 255" : "");
if (place !== null && palette) {
setSlot(own, palette[place], place, "aj");
preset = null;
customId = null;
showChoice();
}
});
aj.addEventListener("change", () => setSlot(own, own.picker.value, own.index));
row.append(name, picker, box, aj);
$("slots").append(row);
slots.push(own);
}
$("whole").addEventListener("input", () => {
const value = readWhole($("whole").value);
$("whole").setCustomValidity(value === null ? "A colour id, signed or not" : "");
if (value !== null) {
preset = null;
applyWhole(value, "whole");
}
else if ($("whole").value.trim()) {
$("whole-note").textContent = "A whole number: -2147483648 to 4294967295.";
}
});
$("whole").addEventListener("change", showChoice);
pairUp($("tint-picker"), $("tint-hex"), () => {
$("tint").checked = true;
showChoice();
});
$("tint").addEventListener("change", showChoice);
$("tint-strength").addEventListener("input", () => {
$("tint-strength-text").textContent = `${$("tint-strength").value}%`;
$("tint").checked = true;
showChoice();
});
// the item as it would be given (lib/itempreview.js). clothing: its
// closet icon, coloured here as the game colours it
// (PaletteHelper.BuildAnimalPalette, LayerBitmap.paintFrame). den items:
// their art played in a frame of public/item-preview.html. a custom
// item with a picture of its own: that picture.
const icons = new Map(); // clothing id: its icon, {w, h, bytes}, or null
const rgbOf = hex => parseInt(hex.slice(1), 16);
const gradient = (palette, rgb, start, count) => {
let [red, green, blue] = [rgb >> 16 & 255, rgb >> 8 & 255, rgb & 255];
const [stepRed, stepGreen, stepBlue] = [red, green, blue].map(value => Math.floor(value / (count + 2)));
for (let at = start + count - 1, left = count; left > 0; left--, at--) {
[255, 192, 128, 64].forEach((alpha, shade) => {
palette[at + 25 * shade] = [red, green, blue, alpha];
});
red -= stepRed;
green -= stepGreen;
blue -= stepBlue;
}
};
const mix = (one, other) => [16, 8, 0].reduce((sum, shift) => sum | (((one >> shift & 255) + (other >> shift & 255)) >> 1) << shift, 0);
const paletteOf = ([one, two, three, four]) => {
const palette = [];
[[one, 1, 3], [two, 4, 3], [three, 7, 3], [four, 10, 3], [mix(one, two), 13, 2], [mix(two, three), 15, 2],
[mix(one, three), 17, 2], [mix(one, four), 19, 2], [mix(two, four), 21, 2], [mix(three, four), 23, 2]]
.forEach(([rgb, start, count]) => gradient(palette, rgb, start, count));
return palette;
};
const paintIcon = (icon, colours) => {
const canvas = $("preview-icon");
canvas.width = icon.w;
canvas.height = icon.h;
const context = canvas.getContext("2d");
const image = context.createImageData(icon.w, icon.h);
const palette = paletteOf(colours.map(rgbOf));
const bytes = icon.bytes;
let [x, y, at] = [0, 0, 0];
while (at < bytes.length) {
let index = bytes[at++];
let run = 1;
if (index & 0x80) {
index &= 0x7F;
run = bytes[at++] + 1;
}
if (index === 0) {
x += run;
if (x >= icon.w) {
const over = x - icon.w;
x = over % icon.w;
y += Math.floor(over / icon.w) + 1;
}
continue;
}
const colour = palette[index];
for (; run > 0; run--) {
if (colour && y < icon.h) {
image.data.set(colour, (y * icon.w + x) * 4);
}
if (++x === icon.w) {
x = 0;
y++;
}
}
}
context.putImageData(image, 0, 0);
};
let previewShown = null; // what the preview shows, to change only what changed
let denTimer = null;
const showPreview = () => {
const entry = chosen;
const note = text => {
$("preview-note").textContent = text;
};
const only = id => {
for (const one of ["preview-icon", "preview-art", "preview-den"]) {
$(one).hidden = one !== id;
}
};
if (entry.art) {
if (previewShown !== entry.art) {
previewShown = entry.art;
only("preview-art");
note("");
$("preview-art").src = entry.art;
}
return;
}
if (entry.kind === "clothing") {
const colours = slots.map(slot => slot.picker.value);
const icon = icons.get(entry.id);
if (icon === undefined) {
only(null);
note("Loading…");
icons.set(entry.id, false);
fetch(`/account/art/clothing/${entry.id}`).then(response => (response.ok ? response.json() : null)).catch(() => null).then(found => {
icons.set(entry.id, found ? {w: found.w, h: found.h, bytes: Uint8Array.from(atob(found.b), letter => letter.charCodeAt(0))} : null);
if (chosen === entry) {
showPreview();
}
});
return;
}
if (icon) {
only("preview-icon");
note("");
paintIcon(icon, colours);
}
else if (icon === null) {
only(null);
note("No picture");
}
previewShown = null;
return;
}
const wanted = new URLSearchParams({id: entry.id, v: variant});
if (entry.tintable && $("tint").checked) {
wanted.set("tint", $("tint-picker").value.slice(1));
wanted.set("s", $("tint-strength").value);
}
const address = `/account/item-preview#${wanted}`;
if (previewShown === address) {
return;
}
previewShown = address;
only("preview-den");
note("");
// a new player each time: a slider dragged waits for it to stop
clearTimeout(denTimer);
denTimer = setTimeout(() => {
$("preview-den").src = address;
}, $("preview-den").src ? 250 : 0);
};
// what Give would give, said beside it.
function showChoice() {
for (const [index, button] of [...$("presets").children].entries()) {
button.setAttribute("aria-pressed", String(index === preset));
}
for (const button of $("variants").children) {
button.setAttribute("aria-pressed", String(Number(button.dataset.variant) === variant));
}
if (!chosen) {
return;
}
showPreview();
if (chosen.kind === "clothing") {
showWhole();
const value = wholeValue();
$("give-what").textContent = preset !== null ? `Its own colour ${preset + 1} (${value})`
: value !== null ? `Colour ${value}` : `A new colour of ${slots.map(slot => slot.picker.value).join(" ")}`;
}
else {
const parts = [chosen.variants.length ? `Variant ${chosen.variants.indexOf(variant) + 1}` : "As it is"];
if (chosen.tintable && $("tint").checked) {
parts.push(`tinted ${$("tint-picker").value} at ${$("tint-strength").value}%`);
}
$("give-what").textContent = parts.join(", ");
}
}
const choosePreset = index => {
preset = index;
applyWhole(chosen.presets[index].id, null, chosen.presets[index].colours);
};
const choose = entry => {
chosen = entry;
$("detail").hidden = false;
$("item-name").textContent = entry.name;
$("item-meta").textContent = `${KINDS[entry.kind]} · id ${entry.id}${entry.cost ? ` · ${entry.cost} gems in shops` : ""}`;
$("clothing-part").hidden = entry.kind !== "clothing";
$("den-part").hidden = entry.kind !== "den";
setStatus("give-status", "");
if (entry.kind === "clothing") {
$("presets").textContent = "";
entry.presets.forEach((option, index) => {
const button = document.createElement("button");
button.type = "button";
button.title = `Colour ${index + 1} (${option.id})`;
button.append(option.colours ? swatches(option.colours) : String(index + 1));
button.addEventListener("click", () => choosePreset(index));
$("presets").append(button);
});
if (entry.presets.length) {
choosePreset(0);
}
else {
preset = null;
}
}
else {
$("variants").textContent = "";
variant = entry.variants.length ? entry.variants[0] : 0;
entry.variants.forEach((version, index) => {
const button = document.createElement("button");
button.type = "button";
button.dataset.variant = String(version);
button.title = `Variant ${index + 1}`;
button.append(entry.variantColours ? swatches(entry.variantColours[index]) : String(index + 1));
button.addEventListener("click", () => {
variant = version;
showChoice();
});
$("variants").append(button);
});
$("no-variants").hidden = entry.variants.length > 0;
$("tint-on").hidden = !entry.tintable;
$("tint-off").hidden = entry.tintable;
$("tint").checked = false;
}
showChoice();
$("detail").scrollIntoView({behavior: "smooth", block: "nearest"});
};
const showResults = found => {
const list = $("results");
list.textContent = "";
for (const entry of found.results) {
const row = document.createElement("li");
const button = document.createElement("button");
button.type = "button";
const name = document.createElement("span");
name.className = "name";
name.textContent = entry.name;
const meta = document.createElement("span");
meta.className = "meta";
meta.textContent = `${KINDS[entry.kind]} · ${entry.id}`;
button.append(name, meta);
button.addEventListener("click", () => choose(entry));
row.append(button);
list.append(row);
}
setStatus("search-status", found.total === 0 ? "Nothing found." : found.total > found.results.length
? `${found.total} found; the first ${found.results.length} shown. Type more to narrow it down.` : `${found.total} found.`);
};
const showGate = (title, text) => {
$("gate").hidden = false;
$("finder").hidden = true;
$("detail").hidden = true;
$("gate-title").textContent = title;
$("gate-text").textContent = text;
};
let asked = 0;
const search = async () => {
const mine = ++asked;
const result = await api(`giver?q=${encodeURIComponent($("query").value.trim())}&kind=${encodeURIComponent($("kind").value)}`);
if (mine !== asked) {
return;
}
if (result.status === 401) {
showGate("Sign in first", "The item giver uses your account page's sign-in.");
}
else if (result.status === 403) {
showGate("Not now", "The item giver is not open to this account at the moment. Your account page says why.");
}
else if (!result.ok) {
setStatus("search-status", result.data.error || "That did not work.", true);
}
else {
$("gate").hidden = true;
$("finder").hidden = false;
showResults(result.data);
}
};
let typing = null;
$("query").addEventListener("input", () => {
clearTimeout(typing);
typing = setTimeout(search, 250);
});
$("kind").addEventListener("change", search);
$("give").addEventListener("click", async () => {
if (!chosen) {
return;
}
const body = {kind: chosen.kind, id: chosen.id};
if (chosen.kind === "clothing") {
const value = wholeValue();
if (preset !== null) {
body.colorIndex = preset;
}
else if (value !== null) {
body.color = String(value);
}
else {
body.color = slots.map(slot => slot.picker.value).join(" ");
}
}
else {
body.version = variant;
if (chosen.tintable && $("tint").checked) {
body.tint = $("tint-picker").value;
body.tintStrength = Number($("tint-strength").value);
}
}
$("give").disabled = true;
const result = await api("give", body);
$("give").disabled = false;
if (result.status === 401) {
showGate("Sign in again", "Your account page's sign-in ended.");
return;
}
if (!result.ok) {
setStatus("give-status", result.data.error || "That did not work.", true);
return;
}
const as = result.data.color !== undefined ? ` Its colour in the game: ${result.data.color}.` : result.data.version ? ` Its version in the game: ${result.data.version}.` : "";
setStatus("give-status", `${chosen.name}: given. ${result.data.online ? "It is in your inventory in the game now." : "It is in your inventory next time you play."}${as}`);
});
api("colour").then(result => {
if (result.ok && result.data.palette) {
palette = result.data.palette.map(colour => `#${colour}`);
for (const slot of slots) {
const place = palette.indexOf(slot.picker.value);
setSlot(slot, slot.picker.value, slot.index !== null ? slot.index : place < 0 ? null : place);
}
showChoice();
}
else {
for (const slot of slots) {
slot.aj.disabled = true;
}
}
});
api("me").then(result => {
if (result.ok) {
$("who").textContent = `Items go to ${result.data.username}.`;
}
});
search();
</script>
</body>
</html>
+227 -12
View File
@@ -216,9 +216,25 @@
.page-title h1 { font-size: 26px; }
@media (max-width: 860px) {
#panel { grid-template-columns: 1fr; }
#side { position: static; height: auto; flex-direction: column; }
nav { flex-direction: row; flex-wrap: wrap; }
nav button { width: auto; }
#side { position: static; height: auto; gap: 12px; padding: 12px; }
nav { flex-direction: row; flex-wrap: nowrap; overflow-x: auto; overflow-y: hidden; padding-bottom: 2px; scrollbar-width: thin; }
nav button { flex: 0 0 auto; width: auto; }
#main { padding: 16px 12px 32px; }
section { padding: 15px; border-radius: 14px; }
.page-title { align-items: flex-start; flex-direction: column; gap: 3px; margin-bottom: 14px; }
.columns, .actions { grid-template-columns: minmax(0, 1fr); }
.toolbar input[type="search"] { flex-basis: 100%; min-width: 0; width: 100%; }
.table-wrap { max-width: 100%; }
}
@media (max-width: 520px) {
body { font-size: 14px; overflow-x: hidden; }
.brand { padding: 0; }
.tiles, .paintings { grid-template-columns: minmax(0, 1fr); }
.tile { padding: 14px; }
.tile .value { font-size: 26px; }
dl { grid-template-columns: 1fr; gap: 2px; }
dd { margin-bottom: 9px; }
.preview { padding: 8px; }
}
section { background: var(--panel); border: 1px solid var(--line); border-radius: 18px; padding: 20px; margin-bottom: 18px; box-shadow: var(--shadow); }
@@ -438,6 +454,12 @@
<div id="captcha"></div>
<button class="primary" id="gate-button">Sign in</button>
</form>
<form id="discord-code-form" hidden>
<p class="hint">Discord confirmed who you are. Enter your 2FA code to finish signing in.</p>
<label for="discord-code">2FA code</label>
<input id="discord-code" inputmode="numeric" autocomplete="one-time-code" maxlength="20" spellcheck="false" required>
<button class="primary" id="discord-code-button">Finish signing in</button>
</form>
<button type="button" id="discord-sign-in" hidden>Sign in with Discord</button>
<p class="hint" id="discord-gate-hint" hidden>Use the Discord account linked to your active staff account.</p>
<p class="status" id="gate-status" role="status"></p>
@@ -459,9 +481,11 @@
<button role="tab" data-tab="masterpieces" data-needs="player.view" aria-selected="false"><span class="icon" aria-hidden="true">&#9635;</span>Masterpieces<span id="masterpiece-count"></span></button>
<button role="tab" data-tab="bans" data-needs="player.view" aria-selected="false"><span class="icon" aria-hidden="true">&#8856;</span>Bans</button>
<button role="tab" data-tab="stats" data-needs="player.view" aria-selected="false"><span class="icon" aria-hidden="true">&#9636;</span>Stats</button>
<button role="tab" data-tab="mod-log" data-needs="staff.log" aria-selected="false" hidden><span class="icon" aria-hidden="true">&#9776;</span>Mod log</button>
<button role="tab" data-tab="review" data-needs="items.approve" aria-selected="false" hidden><span class="icon" aria-hidden="true">&#10004;</span>Review</button>
<button role="tab" data-tab="wear-rules" data-needs="items.restrict" aria-selected="false" hidden><span class="icon" aria-hidden="true">&#9873;</span>Wear rules</button>
<button role="tab" data-tab="items" data-needs="items.create" aria-selected="false" hidden><span class="icon" aria-hidden="true">&#10070;</span>Items</button>
<button role="tab" data-tab="music" data-needs="music.upload" aria-selected="false" hidden><span class="icon" aria-hidden="true">&#9835;</span>Music</button>
</nav>
<button id="sign-out" type="button">Sign out</button>
</aside>
@@ -881,6 +905,31 @@
</section>
</div>
<div data-view="music" hidden>
<section>
<h2>Upload music</h2>
<p class="hint">An MP3 becomes a den music track at once, with no restart: players get it from the item finder (and the shop, if it is on sale) and play it in their dens like the game's own tracks. 44.1 kHz MP3s play best; 15 MB at most.</p>
<div class="actions">
<div class="action">
<h3>The track</h3>
<div class="row"><input id="music-file" type="file" accept=".mp3,audio/mpeg" aria-label="MP3 file"></div>
<div class="row" style="margin-top:8px"><input id="music-name" maxlength="40" placeholder="Name" aria-label="Name"></div>
<div class="row" style="margin-top:8px"><input id="music-cost" type="number" min="0" placeholder="Price in gems (0)" aria-label="Price in gems">
<label class="check"><input type="checkbox" id="music-shop"> On sale in the shop</label></div>
<div class="row" style="margin-top:8px"><button type="button" class="primary" id="music-upload">Upload</button></div>
</div>
</div>
<p class="status" id="music-status" role="status"></p>
</section>
<section>
<h2>Uploaded tracks</h2>
<div class="table-wrap"><table>
<thead><tr><th>Track</th><th class="num">Den item</th><th>Uploaded</th><th class="num">Size</th><th></th></tr></thead>
<tbody id="music-list"></tbody>
</table></div>
<div class="empty" id="no-music" hidden>None yet.</div>
</section>
</div>
<div data-view="items" hidden>
<section>
<h2 id="item-form-title">Make an item</h2>
@@ -950,6 +999,17 @@
</section>
</div>
<div data-view="mod-log" hidden>
<section>
<h2>What staff did</h2>
<div class="table-wrap"><table>
<thead><tr><th>When</th><th>Who</th><th>What</th><th>Player</th><th>Detail</th></tr></thead>
<tbody id="mod-log"></tbody>
</table></div>
<div class="empty" id="no-mod-log" hidden>Nothing yet.</div>
</section>
</div>
<div data-view="bans" hidden>
<section>
<h2>Banned and silenced</h2>
@@ -1020,6 +1080,8 @@
let tab = "home";
let selected = null; // the username of the player whose box is open
let players = [];
// Older responses must never overwrite a newer player search.
let playerSearchRun = 0;
let chatQuery = null; // what the Chat page shows: {username, room, text}
let chatLines = [];
let timer = null;
@@ -1442,7 +1504,7 @@
const tags = stateTags({...alt, silenced: 0, nameRejected: false, moderator: false, role: null, banned: alt.banned});
stateCell.append(...(tags.length ? tags.flatMap(tag => [tag, " "]) : ["—"]));
row.append(el("td", alt.username), stateCell,
el("td", alt.devices.length ? `${alt.devices.map(kind => KIND_NAMES[kind] || kind).join(", ")}${alt.weak ? " (weak)" : ""}` : "—"),
el("td", alt.devices.length ? `${alt.devices.map(kind => KIND_NAMES[kind] || kind).join(", ")}` : "—"),
el("td", alt.addresses ? String(alt.addresses) : "—", "num"));
row.addEventListener("click", () => openPlayer(alt.username));
return row;
@@ -1560,6 +1622,7 @@
$("player-only").addEventListener("click", event => {
const chip = event.target.closest("button[data-only]");
if (chip) {
playerSearchRun++;
setListOnly(chip.dataset.only);
refresh();
}
@@ -1567,6 +1630,7 @@
// from another page: that player's box, whether or not the search shows them.
const openPlayer = username => {
playerSearchRun++;
$("player-search").value = username;
$("player-search-by").value = "name";
$("player-search").placeholder = "Search";
@@ -1582,6 +1646,7 @@
// every account that used a hardware ID: the player list, searched by it.
const searchDevice = id => {
playerSearchRun++;
$("player-search-by").value = "device";
$("player-search").placeholder = "Hardware ID, or the start of one";
$("player-search").value = id;
@@ -1664,6 +1729,7 @@
// by address, asked once typing stops: each search is written down.
let searchWait = null;
$("player-search").addEventListener("input", () => {
playerSearchRun++;
clearTimeout(searchWait);
searchWait = setTimeout(refresh, $("player-search-by").value === "name" ? 250 : 700);
});
@@ -1687,6 +1753,7 @@
}
});
$("player-search-by").addEventListener("change", () => {
playerSearchRun++;
$("player-search").placeholder = {address: "203.0.113.7, or the start of one", device: "Hardware ID, or the start of one"}[$("player-search-by").value] || "Search";
refresh();
});
@@ -1966,7 +2033,7 @@
let recentList = [];
let paintingsShown = "";
let recentShown = "";
const paintingSrc = painting => `/mod/api/masterpiece?id=${encodeURIComponent(painting.id)}`;
const paintingSrc = painting => `/dashboard/api/staff/masterpiece?id=${encodeURIComponent(painting.id)}`;
const paintingWords = painting => (painting.status === "waiting" ? `Waiting · painted ${ago(painting.createdAt)}`
: `Approved${painting.approvedAt ? ` ${ago(painting.approvedAt)}` : ""}${painting.approvedBy ? ` by ${painting.approvedBy === myName ? "you" : painting.approvedBy}` : ""}`
+ `${painting.likes ? ` · ${painting.likes} ${painting.likes === 1 ? "like" : "likes"}` : ""}`);
@@ -1996,8 +2063,8 @@
// card, their name opens it)
const paintingButtons = (painting, withPlayer) => {
const buttons = el("div", undefined, "buttons");
// judging paintings is for the roles that judge what players make
if (permissions.has("items.approve")) {
// judging paintings is for the roles that may (masterpieces.approve)
if (permissions.has("masterpieces.approve")) {
buttons.append(...(painting.status === "waiting" ? [button("Approve", () => judge(painting, true), "primary")] : []),
button("Reject", () => judge(painting, false), "danger"));
}
@@ -2324,8 +2391,8 @@
// moving), else drawn into a PNG that fits, smaller until it is small
// enough. any picture this browser can open will do (WebP, AVIF, BMP...).
// null when it cannot be read at all.
const PICTURE_SIDE = 512;
const PICTURE_BYTES = 300 * 1024;
const PICTURE_SIDE = 256;
const PICTURE_BYTES = 100 * 1024;
const preparePicture = async file => {
const kept = ["image/png", "image/jpeg", "image/gif"].includes(file.type);
let image = null;
@@ -2339,7 +2406,7 @@
image.close();
return file;
}
for (const side of [PICTURE_SIDE, 384, 256, 128]) {
for (const side of [PICTURE_SIDE, 192, 128, 96]) {
const scale = Math.min(1, side / image.width, side / image.height);
const canvas = document.createElement("canvas");
canvas.width = Math.max(1, Math.round(image.width * scale));
@@ -2710,6 +2777,91 @@
$("server-updated").textContent = `Updated ${new Date(Number(data.now || Date.now())).toLocaleTimeString()}.`;
};
// ---- music uploaded by staff (lib/custommusic.js): an MP3 made a den
// music track, which players get from the item finder at once
const MUSIC = "/mod/api/music";
let musicShown = "";
const musicCall = async (query, body) => {
try {
const response = await fetch(`${MUSIC}${query}`, {method: "POST", headers: {"Content-Type": "audio/mpeg"}, body});
return await response.json().catch(() => ({error: "That did not work."}));
}
catch (err) {
return {error: "The server did not answer."};
}
};
const renderMusic = data => {
const tracks = data.tracks || [];
// drawn again only when something changed: a track being listened to keeps playing
const shown = JSON.stringify(tracks);
if (shown === musicShown) {
return;
}
musicShown = shown;
$("no-music").hidden = tracks.length > 0;
$("music-list").replaceChildren(...tracks.map(track => {
const row = el("tr");
const name = el("td");
const player = el("audio");
player.controls = true;
player.preload = "none";
player.src = `${MUSIC}?play=${track.id}`;
player.style.cssText = "display:block;margin-top:6px;height:32px;max-width:260px";
name.append(el("strong", track.name), player);
const actions = el("td");
actions.append(button("Delete", async () => {
if (!confirm(`Delete "${track.name}"? It is taken from every player who has it. This cannot be undone.`)) {
return;
}
const result = await musicCall(`?delete=${track.id}`, new Uint8Array(0));
setStatus($("music-status"), result.ok || result.error || "That did not work.", !result.ok);
await loadMusic();
}, "danger"));
row.append(name, el("td", String(track.id), "num"), el("td", `${when(track.createdAt)} · ${track.createdBy}${track.inShop ? ` · on sale, ${track.cost} gems` : ""}`),
el("td", `${(track.bytes / 1048576).toFixed(1)} MB`, "num"), actions);
return row;
}));
};
const loadMusic = async () => {
try {
const response = await fetch(MUSIC);
const data = await response.json().catch(() => ({}));
if (response.ok) {
renderMusic(data);
}
}
catch (err) {
// shown again with the next refresh
}
};
// the name from the file's, until one is typed
$("music-file").addEventListener("change", () => {
const file = $("music-file").files[0];
if (file && !$("music-name").value.trim()) {
$("music-name").value = file.name.replace(/\.mp3$/i, "").replace(/[_]+/g, " ").slice(0, 40);
}
});
$("music-upload").addEventListener("click", async () => {
const file = $("music-file").files[0];
if (!file || !$("music-name").value.trim()) {
setStatus($("music-status"), file ? "Give the track a name." : "Choose an MP3 first.", true);
return;
}
$("music-upload").disabled = true;
setStatus($("music-status"), "Uploading...");
const query = `?name=${encodeURIComponent($("music-name").value.trim())}&cost=${encodeURIComponent($("music-cost").value || 0)}&inShop=${$("music-shop").checked ? 1 : 0}`;
const result = await musicCall(query, new Uint8Array(await file.arrayBuffer()));
$("music-upload").disabled = false;
setStatus($("music-status"), result.ok || result.error || "That did not work.", !result.ok);
if (result.ok) {
for (const id of ["music-file", "music-name", "music-cost"]) {
$(id).value = "";
}
$("music-shop").checked = false;
}
await loadMusic();
});
const refresh = async () => {
clearTimeout(timer);
if (!signedIn) {
@@ -2766,9 +2918,13 @@
const searchBy = $("player-search-by").value;
const byAddress = searchBy !== "name";
const query = $("player-search").value.trim();
const searchRun = ++playerSearchRun;
$("address-hint").hidden = searchBy !== "address";
$("player-only").hidden = byAddress;
if (byAddress && query === "") {
if (searchRun !== playerSearchRun || tab !== "players") {
return;
}
players = [];
renderPlayers();
$("players-more").hidden = true;
@@ -2777,6 +2933,12 @@
else {
const only = listOnly();
const result = await api(`players?q=${encodeURIComponent(query)}${byAddress ? `&by=${searchBy}` : only ? `&only=${only}` : ""}`);
if (searchRun !== playerSearchRun || tab !== "players"
|| searchBy !== $("player-search-by").value
|| query !== $("player-search").value.trim()
|| (!byAddress && only !== listOnly())) {
return;
}
players = result.ok ? result.data.players : [];
renderPlayers();
const total = result.ok && result.data.total ? result.data.total : players.length;
@@ -2817,6 +2979,19 @@
else if (shown === "stats") {
await window.statsView.load(api);
}
else if (shown === "mod-log") {
const result = await api("modlog");
if (result.ok) {
$("mod-log").replaceChildren(...result.data.log.map(entry => {
const row = el("tr");
const detail = el("td", entry.detail);
detail.style.whiteSpace = "normal";
row.append(el("td", when(entry.at)), el("td", entry.by), el("td", entry.action), el("td", entry.target || "—"), detail);
return row;
}));
$("no-mod-log").hidden = result.data.log.length > 0;
}
}
else if (shown === "bans") {
const [result, hits] = await Promise.all([api("bans"), api("filterhits")]);
if (result.ok) {
@@ -2835,6 +3010,9 @@
else if (shown === "wear-rules") {
await loadWearRules();
}
else if (shown === "music") {
await loadMusic();
}
else if (shown === "items") {
const result = await api("items");
if (result.ok) {
@@ -2964,7 +3142,7 @@
sub.hidden = !allowed.has(sub.dataset.needs);
}
// a role that does not judge paintings has approved none of them
$("recent-mine").closest("label").hidden = !allowed.has("items.approve");
$("recent-mine").closest("label").hidden = !allowed.has("masterpieces.approve");
// the pages the role may see; the first of them when the one open is not.
const pages = [...document.querySelectorAll("nav button")];
for (const page of pages) {
@@ -3023,6 +3201,38 @@
location.href = "/dashboard/staff/discord/login";
});
// after Discord: the 2FA code, which opens the panel (POST discord/code)
const showDiscordCode = message => {
showGate(message);
$("gate-form").hidden = true;
$("discord-code-form").hidden = false;
$("discord-sign-in").textContent = "Start again with Discord";
$("discord-code").focus();
};
$("discord-code-form").addEventListener("submit", async event => {
event.preventDefault();
$("discord-code-button").disabled = true;
const result = await api("discord/code", {code: $("discord-code").value.trim()});
$("discord-code-button").disabled = false;
$("discord-code").value = "";
if (result.ok) {
history.replaceState(null, "", location.pathname + location.hash);
$("discord-code-form").hidden = true;
$("gate-form").hidden = false;
showPanel(result.data.username);
}
else if (result.data.expired) {
history.replaceState(null, "", location.pathname + location.hash);
$("discord-code-form").hidden = true;
$("gate-form").hidden = false;
showGate(said(result));
}
else {
setStatus($("gate-status"), said(result), true);
}
});
$("sign-out").addEventListener("click", async () => {
await api("logout", {});
showGate("");
@@ -3043,7 +3253,12 @@
discord: "Discord could not confirm that sign-in. Try again.",
off: "Discord sign-in is not configured.",
}[discordResult] || "";
showGate(result.status === 0 ? result.data.error : discordMessage);
if (discordResult === "code" && result.status !== 0) {
showDiscordCode("");
}
else {
showGate(result.status === 0 ? result.data.error : discordMessage);
}
}
};
+1 -1
View File
@@ -242,7 +242,7 @@
<section>
<h2>7. Children</h2>
<p>Burrow is for people aged 13 and over, or the higher age at which the law of your country lets you agree to the use of your data on your own (up to 16 in parts of Europe). We do not knowingly collect data from anyone younger and we do not offer parental consent. If we learn that an account belongs to someone under that age we delete it. Parents and guardians can ask for this at {{legalEmail}}.</p>
<p>Burrow is for people aged 18 and over. We do not knowingly collect data from anyone younger and we do not offer parental consent. If we learn that an account belongs to someone under that age we delete it. Parents and guardians can ask for this at {{legalEmail}}.</p>
</section>
<section>
+2 -2
View File
@@ -4,5 +4,5 @@
<style>@font-face{font-family:d;src:url('/fonts/CCDigitalDelivery-Regular.otf')}*{box-sizing:border-box}body{margin:0;padding:48px 16px;background:#000;color:#fff;font:16px/1.45 d,system-ui}main{max-width:420px;margin:auto;padding:28px;background:#0d0d0d;border:1px solid #2e2e2e;border-radius:18px}.logo{height:62px}h1{font-size:25px;margin:10px 0}p,label{color:#aaa}label{display:block;margin:14px 0 5px}input,select,button{width:100%;font:inherit;color:#fff;background:#000;border:1px solid #444;border-radius:12px;padding:10px 12px}button{margin-top:20px;background:#fff;color:#000;font-weight:bold;cursor:pointer}.status{min-height:24px;margin:14px 0 0;color:#aaa}a{color:#fff}</style></head>
<body><main><img class="logo" src="/logo.png" alt=""><h1>Account recovery</h1>
<div id="request"><p>We’ll send a one-time recovery link to the email saved on your account.</p><form id="request-form"><label>Username<input id="username" autocomplete="username" required></label><label>Recovery email<input id="email" type="email" autocomplete="email" required></label><label>What do you need to recover?<select id="kind"><option value="password">Password</option><option value="twoStep">2FA</option></select></label><button>Send recovery link</button></form></div>
<div id="complete" hidden><p id="intro"></p><form id="complete-form"><label id="password-label">New password<input id="password" type="password" autocomplete="new-password" minlength="10"></label><button>Complete recovery</button></form></div><p class="status" id="status" role="status"></p><p><a href="/account">Back to sign in</a></p></main>
<script>"use strict";const $=id=>document.getElementById(id),token=new URLSearchParams(location.search).get('token');const post=async(path,body)=>{const r=await fetch(path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});return {ok:r.ok,data:await r.json()}};const status=(text)=>$('status').textContent=text;if(token){post('/account/api/recover/check',{token}).then(r=>{if(!r.ok){status(r.data.error);return}$('request').hidden=true;$('complete').hidden=false;const two=r.data.kind==='twoStep';$('intro').textContent=two?'Confirm that you want to remove 2FA from this account.':'Choose a new password.';$('password-label').hidden=two;$('password').required=!two}).catch(()=>status('The server did not answer.'))}$('request-form').addEventListener('submit',async e=>{e.preventDefault();const r=await post('/account/api/recover/request',{username:$('username').value,email:$('email').value,kind:$('kind').value});status(r.data.ok||'Could not start recovery.')});$('complete-form').addEventListener('submit',async e=>{e.preventDefault();const r=await post('/account/api/recover/complete',{token,password:$('password').value});status(r.data.ok||r.data.error||'Could not complete recovery.')});</script></body></html>
<div id="complete" hidden><p id="intro"></p><form id="complete-form"><label id="password-label"><span id="password-text">New password</span><input id="password" type="password" autocomplete="new-password" minlength="10" required></label><button>Complete recovery</button></form></div><p class="status" id="status" role="status"></p><p><a href="/account">Back to sign in</a></p></main>
<script>"use strict";const $=id=>document.getElementById(id),token=new URLSearchParams(location.search).get('token');const post=async(path,body)=>{const r=await fetch(path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});return {ok:r.ok,data:await r.json()}};const status=(text)=>$('status').textContent=text;if(token){post('/account/api/recover/check',{token}).then(r=>{if(!r.ok){status(r.data.error);return}$('request').hidden=true;$('complete').hidden=false;const two=r.data.kind==='twoStep';$('intro').textContent=two?'Enter your password to remove 2FA from this account.':'Choose a new password.';$('password-text').textContent=two?'Your password':'New password';$('password').autocomplete=two?'current-password':'new-password';$('password').minLength=two?1:10}).catch(()=>status('The server did not answer.'))}$('request-form').addEventListener('submit',async e=>{e.preventDefault();const r=await post('/account/api/recover/request',{username:$('username').value,email:$('email').value,kind:$('kind').value});status(r.data.ok||'Could not start recovery.')});$('complete-form').addEventListener('submit',async e=>{e.preventDefault();const r=await post('/account/api/recover/complete',{token,password:$('password').value});status(r.data.ok||r.data.error||'Could not complete recovery.')});</script></body></html>
+1 -1
View File
@@ -203,7 +203,7 @@
<label for="email">Recovery email <span class="hint">Used only to recover your password or 2FA</span></label>
<input id="email" name="email" type="email" autocomplete="email" maxlength="254" required>
<label class="agree"><input id="agreed" name="agreed" type="checkbox" required>
<span>I am 13 or older, and old enough in my country to agree to this myself. I agree to the <a href="/terms" target="_blank" rel="noopener">Terms of Service</a> and the <a href="/privacy" target="_blank" rel="noopener">Privacy Policy</a>.</span></label>
<span>I am 18 or older, and old enough in my country to agree to this myself. I agree to the <a href="/terms" target="_blank" rel="noopener">Terms of Service</a> and the <a href="/privacy" target="_blank" rel="noopener">Privacy Policy</a>.</span></label>
<div class="captcha" id="captcha"></div>
<button class="primary" id="submit" type="submit">Create account</button>
</form>
+2 -2
View File
@@ -168,8 +168,8 @@
<section>
<h2>2. Who may play</h2>
<ul>
<li>You must be at least 13 years old.</li>
<li>If the law where you live sets a higher age for agreeing to the use of your personal data on your own (up to 16 in parts of Europe), you must be at least that age.</li>
<li>You must be at least 18 years old.</li>
<li>If the law where you live sets a higher age for agreeing to the use of your personal data on your own, you must be at least that age.</li>
<li>Burrow is not directed at children and has no way to collect a parent's consent. If you are under the age above, do not create an account.</li>
</ul>
<p>By creating an account you confirm that you meet these requirements and that you agree to these terms and to the <a href="/privacy">Privacy Policy</a>. We delete accounts that we learn belong to someone under the required age.</p>
+7
View File
@@ -7,11 +7,14 @@ const accounts = require("./lib/accounts.js");
const bans = require("./lib/bans.js");
const devices = require("./lib/devices.js");
const discord = require("./lib/discord.js");
const discordBot = require("./lib/discordbot.js");
const roles = require("./lib/roles.js");
const chatlog = require("./lib/chatlog.js");
const modlog = require("./lib/modlog.js");
const retention = require("./lib/retention.js");
const colours = require("./lib/colours.js");
const customItems = require("./lib/customitems.js");
const customMusic = require("./lib/custommusic.js");
const config = require("./config.js");
const defpacks = require("./lib/defpacks.js");
const http = require("./lib/http.js");
@@ -41,6 +44,7 @@ const main = async () => {
accounts.startBackups();
colours.load();
customItems.load();
customMusic.load();
reports.load();
support.load();
bans.load();
@@ -51,14 +55,17 @@ const main = async () => {
masterpieces.load();
retention.load();
stats.load(() => world.players().length);
roles.load();
panel.load();
await http.start();
await sfs.start(world);
discordBot.startup();
console.log(`[server] ready at ${config.baseUrl}`);
};
// stopped on purpose: what is waiting to be written is written first.
const stop = code => {
discordBot.shutdown();
stats.flush();
try {
accounts.flush();
+462 -68
View File
@@ -1,5 +1,6 @@
package
{
import achievement.AchievementXtCommManager;
import avatar.AvatarManager;
import avatar.AvatarWorldView;
import buddy.Buddy;
@@ -22,6 +23,7 @@ package
import createAccountFlow.CreateAccount;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Shape;
@@ -45,6 +47,8 @@ package
import flash.text.TextField;
import flash.text.TextFormat;
import flash.events.UncaughtErrorEvent;
import flash.filters.DropShadowFilter;
import flash.filters.GlowFilter;
import flash.external.ExternalInterface;
import flash.system.Capabilities;
import flash.system.LoaderContext;
@@ -340,6 +344,181 @@ package
gMainFrame.stage.addEventListener("keyDown",onFinderKey,false,1000);
startEmojiButton();
placeTheatreButton();
gMainFrame.stage.addEventListener("enterFrame",reportTheatreScreen,false,0,true);
}
// where the theatre's screen is, for game.html to lay a web video over
// it exactly: the original player's 512 by 288 at the top left of the
// theatre layer's videoLayer (movie.VideoPlayerOSMF), in stage
// coordinates (900 by 550; the page scales them as "showAll" does).
// "x,y,width,height", or "" with no theatre screen shown; told only
// when it changes, as the room zooms and scrolls under it.
//
// a web video is always drawn over the whole game, so it also gets
// where the game draws something over the screen (the HUD, the buddy
// list, a Jammer Wall, chat balloons): "x,y,width,height|columns|rows",
// a hex row of bits per SCREEN_CELL stage pixels, top to bottom, over
// the screen and SCREEN_BELOW pixels under it (the page's own button
// sits there). the page cuts those cells out of the video.
private static const THEATRE_SCREEN_W:Number = 512;
private static const THEATRE_SCREEN_H:Number = 288;
private static const SCREEN_CELL:Number = 4;
private static const SCREEN_BELOW:Number = 44;
private static const SCREEN_COVER_EVERY:int = 4; // frames between looks
private static const SCREEN_COVER_ALPHA:uint = 64; // of 255: drawn on, as far as the video goes
private static var _theatreScreenTold:String = null;
private static var _theatreCover:String = "";
private static var _theatreCoverFrame:int = 0;
private static function reportTheatreScreen(param1:Event = null) : void
{
var _loc2_:String = "";
var _loc3_:Object = null;
var _loc4_:DisplayObject = null;
var _loc5_:Point = null;
var _loc6_:Point = null;
try
{
_loc3_ = RoomManagerWorld.instance != null ? RoomManagerWorld.instance.theaterWindow : null;
_loc4_ = _loc3_ != null && _loc3_.hasOwnProperty("videoLayer") ? _loc3_.videoLayer as DisplayObject : null;
if(_loc4_ != null && shownOnStage(_loc4_))
{
_loc5_ = _loc4_.localToGlobal(new Point(0,0));
_loc6_ = _loc4_.localToGlobal(new Point(THEATRE_SCREEN_W,THEATRE_SCREEN_H));
_loc2_ = [_loc5_.x,_loc5_.y,_loc6_.x - _loc5_.x,_loc6_.y - _loc5_.y].map(function(param1:Number, ... rest):String
{
return String(Math.round(param1 * 10) / 10);
}).join(",");
if(++_theatreCoverFrame >= SCREEN_COVER_EVERY || _theatreScreenTold == null || _theatreScreenTold.indexOf(_loc2_) != 0)
{
_theatreCoverFrame = 0;
_theatreCover = theatreCover(_loc3_ as DisplayObject,_loc5_.x,_loc5_.y,_loc6_.x - _loc5_.x,_loc6_.y - _loc5_.y);
}
if(_theatreCover != "")
{
_loc2_ += "|" + _theatreCover;
}
}
}
catch(e:Error)
{
_loc2_ = "";
}
if(_loc2_ == _theatreScreenTold || !ExternalInterface.available)
{
return;
}
_theatreScreenTold = _loc2_;
try
{
ExternalInterface.call("ajTheatreScreen",_loc2_);
}
catch(e:Error)
{
}
}
// what is drawn over the theatre screen, as above: the game's windows
// and buttons, and the room's chat balloons, drawn small, cell by cell.
// the rest is hidden for the moment of drawing, in between two frames:
// the screen, what lies under it, and the room itself (its seats and
// floor are drawn above the screen, and are no reason for the video or
// its button to step aside). "" for nothing, or when the game will not
// be drawn.
private static function theatreCover(param1:DisplayObject, param2:Number, param3:Number, param4:Number, param5:Number) : String
{
var _loc6_:Array = [];
var _loc7_:DisplayObject = param1;
var _loc8_:DisplayObjectContainer = null;
var _loc9_:int = 0;
var _loc10_:DisplayObject = null;
var _loc11_:int = Math.max(1,Math.ceil(param4 / SCREEN_CELL));
var _loc12_:int = Math.max(1,Math.ceil((param5 + SCREEN_BELOW) / SCREEN_CELL));
var _loc13_:BitmapData = null;
var _loc14_:Array = [];
var _loc15_:Boolean = false;
var _loc16_:int = 0;
var _loc17_:int = 0;
var _loc18_:int = 0;
var _loc19_:String = null;
try
{
if(_loc7_.visible)
{
_loc7_.visible = false;
_loc6_.push(_loc7_);
}
while(_loc7_.parent != null)
{
_loc8_ = _loc7_.parent;
_loc9_ = _loc8_.getChildIndex(_loc7_);
while(--_loc9_ >= 0)
{
_loc10_ = _loc8_.getChildAt(_loc9_);
if(_loc10_.visible)
{
_loc10_.visible = false;
_loc6_.push(_loc10_);
}
}
_loc7_ = _loc8_;
}
_loc8_ = RoomManagerWorld.instance.layerManager.bkg;
_loc9_ = _loc8_.numChildren;
while(--_loc9_ >= 0)
{
_loc10_ = _loc8_.getChildAt(_loc9_);
if(_loc10_ != RoomManagerWorld.instance.layerManager.room_chat && _loc10_.visible)
{
_loc10_.visible = false;
_loc6_.push(_loc10_);
}
}
_loc13_ = new BitmapData(_loc11_,_loc12_,true,0);
_loc13_.draw(gMainFrame.stage,new Matrix(1 / SCREEN_CELL,0,0,1 / SCREEN_CELL,-param2 / SCREEN_CELL,-param3 / SCREEN_CELL));
}
catch(e:Error)
{
if(_loc13_ != null)
{
_loc13_.dispose();
_loc13_ = null;
}
}
for each(_loc10_ in _loc6_)
{
_loc10_.visible = true;
}
if(_loc13_ == null)
{
return "";
}
_loc16_ = 0;
while(_loc16_ < _loc12_)
{
_loc19_ = "";
_loc17_ = 0;
while(_loc17_ < _loc11_)
{
_loc18_ = 0;
_loc9_ = 0;
while(_loc9_ < 4)
{
if(_loc17_ + _loc9_ < _loc11_ && _loc13_.getPixel32(_loc17_ + _loc9_,_loc16_) >>> 24 >= SCREEN_COVER_ALPHA)
{
_loc18_ |= 8 >> _loc9_;
_loc15_ = true;
}
_loc9_++;
}
_loc19_ += _loc18_.toString(16);
_loc17_ += 4;
}
_loc14_.push(_loc19_);
_loc16_++;
}
_loc13_.dispose();
return _loc15_ ? _loc11_ + "|" + _loc14_.join(",") : "";
}
public static function openTool(param1:int) : void
@@ -608,6 +787,14 @@ package
return settingOf(9006) != 1;
}
// the pet chooser's "play as your pet" switch (gui.PetInventory): the
// pet that is out stands in for the avatar in any room. user var 9008,
// which the server also reads to show the pet form to everyone.
public static function petFormOn() : Boolean
{
return settingOf(9008) == 1;
}
// an item's picture version, or null for none or with them hidden
private static function artOf(param1:String, param2:int) : String
{
@@ -919,54 +1106,127 @@ package
{
buildTheatreControl();
}
placeTheatreBox();
_theatreControl.visible = true;
setChildIndex(_theatreControl,numChildren - 1);
gMainFrame.stage.focus = _theatreInput;
_theatreInput.setSelection(0,_theatreInput.length);
}
// the Room Video box over the middle of the theatre's screen, as the
// page's Your Video box sits (game.html), or the stage's middle
private function placeTheatreBox() : void
{
var _loc1_:DisplayObject = _theatreControl.getChildByName("box");
var _loc2_:Object = RoomManagerWorld.instance != null ? RoomManagerWorld.instance.theaterWindow : null;
var _loc3_:DisplayObject = _loc2_ != null && _loc2_.hasOwnProperty("videoLayer") ? _loc2_.videoLayer as DisplayObject : null;
var _loc4_:Point = null;
var _loc5_:Point = null;
_loc1_.x = int((900 - THEATRE_BOX_W) * 0.5);
_loc1_.y = int((550 - THEATRE_BOX_H) * 0.5);
try
{
if(_loc3_ != null && shownOnStage(_loc3_))
{
_loc4_ = _theatreControl.globalToLocal(_loc3_.localToGlobal(new Point(0,0)));
_loc5_ = _theatreControl.globalToLocal(_loc3_.localToGlobal(new Point(THEATRE_SCREEN_W,THEATRE_SCREEN_H)));
_loc1_.x = int(_loc4_.x + (_loc5_.x - _loc4_.x - THEATRE_BOX_W) * 0.5);
_loc1_.y = int(Math.max(4,_loc4_.y + (_loc5_.y - _loc4_.y - THEATRE_BOX_H) * 0.5));
}
}
catch(e:Error)
{
}
}
// the staff's Room Video box, drawn as the page's Your Video box
// (game.html .aj-box): a cream panel with a brown edge, a white title
// outlined in brown, a white link box, green and red pill buttons and
// a red round close button. behind it the whole stage, unseen, so a
// click past it does nothing in the room.
private static const THEATRE_BOX_W:int = 360;
private static const THEATRE_BOX_H:int = 150;
private function buildTheatreControl() : void
{
_theatreControl = new Sprite();
_theatreControl.graphics.beginFill(0,0.55);
_theatreControl.graphics.beginFill(0,0);
_theatreControl.graphics.drawRect(0,0,900,550);
_theatreControl.graphics.endFill();
var _loc1_:Sprite = new Sprite();
_loc1_.x = 225;
_loc1_.y = 170;
_loc1_.graphics.lineStyle(2,0x7B4D24);
_loc1_.graphics.beginFill(0x27221D);
_loc1_.graphics.drawRoundRect(0,0,450,210,22,22);
_loc1_.name = "box";
_loc1_.graphics.beginFill(0,0.35);
_loc1_.graphics.drawRoundRect(0,4,THEATRE_BOX_W,THEATRE_BOX_H,36,36);
_loc1_.graphics.endFill();
_loc1_.graphics.lineStyle(4,0x7F6744);
_loc1_.graphics.beginFill(0xFFF2C4);
_loc1_.graphics.drawRoundRect(0,0,THEATRE_BOX_W,THEATRE_BOX_H,36,36);
_loc1_.graphics.endFill();
_loc1_.graphics.lineStyle(2,0xFFE39A);
_loc1_.graphics.drawRoundRect(3,3,THEATRE_BOX_W - 6,THEATRE_BOX_H - 6,30,30);
_theatreControl.addChild(_loc1_);
theatreCloseButton(_loc1_);
var _loc2_:TextField = modText("THEATRE VIDEO",22,0xFFFFFF);
_loc2_.x = 24;
_loc2_.y = 22;
var _loc2_:TextField = modText("Room Video",20,0xFFFFFF);
_loc2_.filters = [new GlowFilter(0x6D4330,1,4,4,12)];
_loc2_.x = 16;
_loc2_.y = 12;
_loc1_.addChild(_loc2_);
var _loc3_:TextField = modText("Paste a YouTube link. Everyone in this theatre will see it.",12,0xD5C5AE,false);
_loc3_.x = 24;
_loc3_.y = 58;
var _loc3_:TextField = modText("Everyone in this theatre sees it.",12,0x8A6A45,false);
_loc3_.x = 17;
_loc3_.y = 41;
_loc1_.addChild(_loc3_);
var _loc4_:Sprite = new Sprite();
_loc4_.x = 24;
_loc4_.y = 94;
_loc4_.graphics.lineStyle(1,0x7B4D24);
_loc4_.graphics.beginFill(0x111111);
_loc4_.graphics.drawRoundRect(0,0,402,34,10,10);
_loc4_.x = 16;
_loc4_.y = 62;
_loc4_.graphics.lineStyle(2,0xC9A86A);
_loc4_.graphics.beginFill(0xFFFFFF);
_loc4_.graphics.drawRoundRect(0,0,THEATRE_BOX_W - 32,30,18,18);
_loc4_.graphics.endFill();
_loc1_.addChild(_loc4_);
var _loc5_:TextField = new TextField();
_loc5_.selectable = false;
_loc5_.mouseEnabled = false;
_loc5_.defaultTextFormat = new TextFormat("Arial",13,0xA88F6A);
_loc5_.text = "Paste a YouTube link";
_loc5_.x = 9;
_loc5_.y = 6;
_loc5_.width = THEATRE_BOX_W - 50;
_loc5_.height = 20;
_loc4_.addChild(_loc5_);
_theatreInput = new TextField();
_theatreInput.type = "input";
_theatreInput.embedFonts = hasGameFont();
_theatreInput.defaultTextFormat = new TextFormat("CCDigitalDelivery",13,0xFFFFFF,false);
_theatreInput.defaultTextFormat = new TextFormat("Arial",13,0x3D2716);
_theatreInput.maxChars = 200;
_theatreInput.x = 10;
_theatreInput.y = 7;
_theatreInput.width = 382;
_theatreInput.height = 22;
_theatreInput.x = 9;
_theatreInput.y = 6;
_theatreInput.width = THEATRE_BOX_W - 50;
_theatreInput.height = 20;
_loc4_.addChild(_theatreInput);
theatreControlButton(_loc1_,"play","Play for room",24,150,186,0x357A45);
theatreControlButton(_loc1_,"stop","Stop video",240,150,186,0x8E3D3D);
_theatreInput.addEventListener("change",function(param1:Event):void
{
_loc5_.visible = _theatreInput.length == 0;
});
_theatreInput.addEventListener("keyDown",onTheatreKey,false,0,true);
theatreControlButton(_loc1_,"play","Play for room",55,104,150,0xA6E05A,0x4FA52F,0x2F7420);
theatreControlButton(_loc1_,"stop","Stop",215,104,90,0xF59A6A,0xD4482A,0x8E2B16);
var _loc6_:Sprite = new Sprite();
_loc6_.buttonMode = true;
_loc6_.useHandCursor = true;
_loc6_.graphics.beginFill(0x7F6744);
_loc6_.graphics.drawCircle(0,0,17);
_loc6_.graphics.beginFill(0xFFFFFF);
_loc6_.graphics.drawCircle(0,0,15);
_loc6_.graphics.beginFill(0xD9452A);
_loc6_.graphics.drawCircle(0,0,12);
_loc6_.graphics.endFill();
_loc6_.graphics.lineStyle(2.5,0xFFFFFF);
_loc6_.graphics.moveTo(-4.5,-4.5);
_loc6_.graphics.lineTo(4.5,4.5);
_loc6_.graphics.moveTo(4.5,-4.5);
_loc6_.graphics.lineTo(-4.5,4.5);
_loc6_.x = THEATRE_BOX_W - 5;
_loc6_.y = 5;
_loc6_.addEventListener("mouseDown",onTheatreClose,false,0,true);
_loc1_.addChild(_loc6_);
_theatreControl.addEventListener("mouseDown",onFinderMouse);
_theatreControl.addEventListener("mouseUp",onFinderMouse);
_theatreControl.addEventListener("click",onFinderMouse);
@@ -974,33 +1234,68 @@ package
addChild(_theatreControl);
}
private function theatreControlButton(param1:Sprite, param2:String, param3:String, param4:Number, param5:Number, param6:Number, param7:uint) : void
// a pill button of the page's .aj-button: a gradient from `param6` to
// `param7` with a `param8` edge and a step of it underneath
private function theatreControlButton(param1:Sprite, param2:String, param3:String, param4:Number, param5:Number, param6:Number, param7:uint, param8:uint, param9:uint) : void
{
var _loc1_:Sprite = new Sprite();
var _loc2_:Matrix = new Matrix();
_loc1_.name = param2;
_loc1_.x = param4;
_loc1_.y = param5;
_loc1_.buttonMode = true;
_loc1_.useHandCursor = true;
_loc1_.mouseChildren = false;
paintFlatButton(_loc1_,param6,param7);
var _loc2_:TextField = modText(param3,14,0xFFFFFF);
_loc2_.name = "label";
_loc1_.addChild(_loc2_);
paintFlatButton(_loc1_,param6,param7);
_loc2_.createGradientBox(param6,32,Math.PI / 2);
_loc1_.graphics.beginFill(param9);
_loc1_.graphics.drawRoundRect(0,2,param6,32,32,32);
_loc1_.graphics.endFill();
_loc1_.graphics.lineStyle(2,param9);
_loc1_.graphics.beginGradientFill("linear",[param7,param8],[1,1],[0,255],_loc2_);
_loc1_.graphics.drawRoundRect(0,0,param6,32,32,32);
_loc1_.graphics.endFill();
_loc1_.graphics.lineStyle(2,0xFFFFFF,0.45);
_loc1_.graphics.moveTo(14,3);
_loc1_.graphics.lineTo(param6 - 14,3);
var _loc3_:TextField = modText(param3,15,0xFFFFFF);
_loc3_.filters = [new DropShadowFilter(1.5,90,0,0.45,0,0,1)];
_loc3_.x = int((param6 - _loc3_.width) * 0.5);
_loc3_.y = int((32 - _loc3_.height) * 0.5);
_loc1_.addChild(_loc3_);
_loc1_.addEventListener("mouseDown",onTheatreControl,false,0,true);
_loc1_.addEventListener("mouseOver",onFlatHover);
_loc1_.addEventListener("mouseOut",onFlatHover);
param1.addChild(_loc1_);
}
// Enter plays, Escape closes, as in the page's box
private function onTheatreKey(param1:KeyboardEvent) : void
{
if(param1.keyCode == 13)
{
sendTheatreVideo("play");
}
else if(param1.keyCode == 27)
{
_theatreControl.visible = false;
gMainFrame.stage.focus = null;
}
}
private function onTheatreControl(param1:MouseEvent) : void
{
param1.stopPropagation();
var _loc1_:String = Sprite(param1.currentTarget).name;
if(_loc1 == "play" && _theatreInput.text.replace(/^\s+|\s+$/g,"").length == 0)
sendTheatreVideo(Sprite(param1.currentTarget).name);
}
private function sendTheatreVideo(param1:String) : void
{
if(param1 == "play" && _theatreInput.text.replace(/^\s+|\s+$/g,"").length == 0)
{
gMainFrame.stage.focus = _theatreInput;
return;
}
gMainFrame.server.setXtObject_Str("xtv",[_loc1,_loc1 == "play" ? _theatreInput.text.split("%").join("") : ""]);
gMainFrame.server.setXtObject_Str("xtv",[param1,param1 == "play" ? _theatreInput.text.split("%").join("") : ""]);
_theatreControl.visible = false;
gMainFrame.stage.focus = null;
}
@@ -1537,11 +1832,15 @@ package
// 9004 Frame rate: 1 is 60; anything else is Max, as fast as the
// timer goes (about 80 a second on the owner's machine, where
// the 120 and 144 this once offered came to the same).
// 9005 Camera: 1 Smooth (room.RoomManagerWorld.easeCamera), else the
// game's own.
// 9007 Performance profile: 1 Low-end, 2 High, unset Balanced. A
// 9005 Camera: 2 the game's own, else Smooth
// (room.RoomManagerWorld.easeCamera).
// 9007 Performance profile: 1 Low-end, 3 Balanced, else (unset) High:
// the best the game can look, which most machines manage. A
// profile changes only optional rendering work, never the
// game's native 24 FPS (which would slow its animations).
// 9008 Play as your pet (gui.PetInventory, lib/pets.js): 1 on.
// 9009 Expanded Inventory (expandedInventoryOn): 1 on.
// 9010 Items a row with it on: 3, 4 or 5; unset is 5.
private static var _smoothTimer:Timer;
@@ -1576,12 +1875,13 @@ package
return settingOf(9003) != 1;
}
// 0 Balanced, 1 Low-end, 2 High. It is persisted with the other client
// settings, so the preference follows the player to another computer.
// 0 Balanced, 1 Low-end, 2 High (kept as 3, 1, and 2 or nothing). It
// is persisted with the other client settings, so the preference
// follows the player to another computer.
public static function performanceProfile() : int
{
var _loc1_:int = settingOf(9007);
return _loc1_ == 1 || _loc1_ == 2 ? _loc1_ : 0;
return _loc1_ == 1 ? 1 : (_loc1_ == 3 ? 0 : 2);
}
public static function performanceProfileLabel() : String
@@ -1612,7 +1912,7 @@ package
var _loc1_:Boolean = false;
try
{
_loc1_ = smoothOn() && settingOf(9005) == 1;
_loc1_ = smoothOn() && settingOf(9005) != 2;
}
catch(e:Error)
{
@@ -1773,6 +2073,33 @@ package
{
return gMainFrame.userInfo.userVarCache.getUserVarValueById(9002) == 1;
}
// "Expanded Inventory" (Strawberry Jam's): the clothes and item
// pickers show more, smaller items a row. user var 9009, 1 on; the
// + and - by the avatar editor's item counter pick 3, 4 or 5 a row,
// user var 9010 (unset is 5, the widest, so turning it on shows).
public static function expandedInventoryOn() : Boolean
{
return settingOf(9009) == 1;
}
public static function inventoryColumns() : int
{
var _loc1_:int = settingOf(9010);
if(!expandedInventoryOn())
{
return 3;
}
return _loc1_ >= 3 && _loc1_ <= 5 ? _loc1_ : 5;
}
// the next of 3, 4 and 5 a row, round about; param1 is 1 or -1.
public static function stepInventoryColumns(param1:int) : void
{
var _loc2_:int = (inventoryColumns() - 3 + param1 + 3) % 3 + 3;
gMainFrame.userInfo.userVarCache.updateUserVar(9010,_loc2_);
AchievementXtCommManager.requestSetUserVar(9010,_loc2_);
}
// the arrow key a key stands for: itself, or with the setting on and
// nothing being typed, the arrow W, A, S or D stands for.
@@ -2046,7 +2373,7 @@ package
// what the player is to see of something another player wrote: the
// text as it was, the text with stars over the filtered words, or
// null when it is to be left out altogether.
public static function filterText(param1:String) : String
public static function filterText(param1:String, param2:Boolean = false) : String
{
var _loc2_:Array = _filterOwnEntries;
var _loc3_:Array = [];
@@ -2116,7 +2443,14 @@ package
{
return param1;
}
return filterMode == 1 ? null : _loc12_.join("");
return filterMode == 1 && !param2 ? null : _loc12_.join("");
}
// an animal's or a pet's typed name: a name cannot be left out, so its
// filtered words are starred whichever the player chose.
public static function filterName(param1:String) : String
{
return filterText(param1,true);
}
// the same for text that has a place of its own (a Jam-A-Gram, a wall
@@ -2289,8 +2623,55 @@ package
drawChatFilter();
}
// the server's rules, word for word as the owner gave them
private static const RULES_HTML:String = "<font size=\"16\" color=\"#563421\"><b>[1] Be Respectful / Have Common Sense</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>This is quite self explanatory. Be kind, treat people how you would want to be treated. If someone is uncomfortable with something you are saying and or doing, please respect that of them and do not argue against it, even if it may seem ridiculous in your eyes.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[2] No Direct Harassment / Bullying</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>If you are being disrespectful towards another person, Moderators have every right to punish you. Please don't be an asshole. Thank you.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[3] Keep Personal Information for Yourself.</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>As friendly that people may seem on this platform, never share personal identifying details with ANYONE. This leads to a lot of unsafe situations. Please be safe and responsible with the information you give to other people.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[4] Keep Drama OUT</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>If you have personal issues with another person, it is not our responsibility unless said person is confirmed to be problematic towards something against the rules of our server. Please do not bring arguments into our public chat, you will be muted until things clear up. Keep it in DMS.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[5] No NSFW!</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>NSFW and Suggestive Content are entirely banned from the server, period. We do not want to be a place that allows predatory behavior to fester. If you are unsure of what specific details this goes under, feel free to ask in a ticket.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[8] Report Any Issues</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>Issues can be anything from harassment, a person you are uncomfortable with, bugs, etc. Moderators are always happy to help!</b></font><br><br><font size=\"13\" color=\"#6E4A2E\"><b>Burrow gives players more freedom than the original game, including free chat. If you do not want to see certain content you may utilise the client side chat filter and block players, which has an option to completely hide them on your side.</b></font><br><br><font size=\"13\" color=\"#6E4A2E\"><b>These options are found in the in-game settings or player cards.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>burrow.moe/terms</b></font>";
// the rules come from the server's data/rules.txt (GET /rules.txt), read
// each time the window opens, so they change without a new client: a
// line starting "# " is a heading, the rest is shown as it is written.
private static const RULES_HEADING:String = "<font size=\"16\" color=\"#563421\"><b>";
private static const RULES_BODY:String = "<font size=\"13\" color=\"#6E4A2E\"><b>";
private static function rulesHtml(param1:String) : String
{
var _loc2_:Array = param1.replace(/\r/g,"").split("\n");
var _loc3_:Array = [];
var _loc4_:String = null;
var _loc5_:int = 0;
while(_loc5_ < _loc2_.length)
{
_loc4_ = String(_loc2_[_loc5_]).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
if(_loc4_.indexOf("# ") == 0)
{
_loc3_.push(RULES_HEADING + _loc4_.substr(2) + "</b></font>");
}
else
{
_loc3_.push(RULES_BODY + _loc4_ + "</b></font>");
}
_loc5_++;
}
return _loc3_.join("<br>");
}
private function loadRules() : void
{
var _loc1_:URLLoader = new URLLoader();
_rulesText.htmlText = rulesHtml("Loading...");
_loc1_.addEventListener("complete",onRulesLoaded);
_loc1_.addEventListener("ioError",onRulesFailed);
_loc1_.addEventListener("securityError",onRulesFailed);
_loc1_.load(new URLRequest(gMainFrame.clientInfo.websiteURL + "rules.txt?t=" + new Date().getTime()));
}
private function onRulesLoaded(param1:Event) : void
{
_rulesText.htmlText = rulesHtml(String(URLLoader(param1.currentTarget).data));
_rulesText.scrollV = 1;
}
private function onRulesFailed(param1:Event) : void
{
_rulesText.htmlText = rulesHtml("The rules could not be loaded. Try again in a moment.");
}
private var _rulesWin:Sprite;
@@ -2338,7 +2719,6 @@ package
_rulesText.y = -158;
_rulesText.width = 462;
_rulesText.height = 338;
_rulesText.htmlText = RULES_HTML;
_loc5_ = GETDEFINITIONBYNAME("arrow_r_btnContOld");
_loc5_.rotation = -90;
_loc5_.x = 236;
@@ -2370,6 +2750,7 @@ package
_rulesWin.visible = param1;
if(param1)
{
loadRules();
_rulesText.scrollV = 1;
setChildIndex(_rulesWin,numChildren - 1);
}
@@ -3121,7 +3502,6 @@ package
private var _emojiCaret:int = -1;
private var _emojiTimer:Timer;
// the characters of code points in hex ("1f468-200d-1f469")
public static function charsOfHex(param1:String) : String
@@ -3163,7 +3543,8 @@ package
// a line about to be sent: each ":name:" of an emoji above becomes it,
// but not the game's own emote codes (":happy:", ":joy:"), which the
// bubble shows as the game's.
// bubble shows as the game's, nor one after a "\" ("\:fire:"), which
// the bubble shows as typed (ChatBalloon.inlineEmotes).
public static function emojiShortcodes(param1:String) : String
{
if(param1.indexOf(":") == -1)
@@ -3171,13 +3552,13 @@ package
return param1;
}
emojiTable();
return param1.replace(/:([a-z0-9_]{1,30}):/g,function(param1:String, param2:String, ... rest):String
return param1.replace(/(\\?):([a-z0-9_]{1,30}):/g,function(param1:String, param2:String, param3:String, ... rest):String
{
if(EmoticonUtility.doesStringMatchAnEmote(param1) || _emojiByName[param2] == null)
if(param2 != "" || EmoticonUtility.doesStringMatchAnEmote(":" + param3 + ":") || _emojiByName[param3] == null)
{
return param1;
}
return _emojiByName[param2];
return _emojiByName[param3];
});
}
@@ -3723,9 +4104,9 @@ package
private function startEmojiButton() : void
{
_emojiTimer = new Timer(500);
_emojiTimer.addEventListener("timer",placeEmojiButton);
_emojiTimer.start();
// every frame: on a timer it went a moment after the HUD did, when
// a window opened over it
gMainFrame.stage.addEventListener("enterFrame",placeEmojiButton,false,0,true);
gMainFrame.stage.addEventListener("mouseDown",onEmojiStageDown,false,0,true);
}
@@ -4174,7 +4555,7 @@ package
_loc3_.currTxt.text = (_loc5_ ? "> " : "") + makerShort(String(_loc4_.name || "(no name)"),24) + (_makerMode == "mine" ? (_loc4_.waiting == "item" ? " (waiting)" : _loc4_.waiting == "picture" ? " (picture waiting)" : _loc4_.art ? (_loc4_.kind == "clothing" ? (_loc4_.artMode == "texture" ? " (texture)" : " (sticker)") : " (picture)") : "") : " #" + _loc4_.id);
_loc3_.addEventListener("mouseDown",onMakerButton);
_makerRowsSprite.addChild(_loc3_);
_makerRowsSprite.addChild(finderPreview(_loc4_,_loc2_,186,_loc3_.y));
_makerRowsSprite.addChild(finderPreview(_loc4_,_loc2_,186,_loc3_.y,false));
_loc2_++;
}
if(_makerMode == "mine" && _loc1_.length == 0)
@@ -4370,9 +4751,9 @@ package
// the picture read: sent as it is when the server takes it so (a PNG,
// JPEG or GIF small enough, or a BMP, which the server makes a PNG); one
// too big is drawn smaller here and sent as a PNG.
private static const MAKER_PICTURE_SIDE:int = 512;
private static const MAKER_PICTURE_SIDE:int = 256;
private static const MAKER_PICTURE_BYTES:int = 300 * 1024;
private static const MAKER_PICTURE_BYTES:int = 100 * 1024;
private function onMakerPictureRead(param1:Event) : void
{
@@ -4412,7 +4793,7 @@ package
private static function shrunkPng(param1:BitmapData) : ByteArray
{
var _loc2_:ByteArray = null;
for each(var _loc3_:int in [MAKER_PICTURE_SIDE,384,256,128])
for each(var _loc3_:int in [MAKER_PICTURE_SIDE,192,128,96])
{
var _loc4_:Number = Math.min(1,_loc3_ / param1.width,_loc3_ / param1.height);
var _loc5_:BitmapData = new BitmapData(Math.max(1,Math.round(param1.width * _loc4_)),Math.max(1,Math.round(param1.height * _loc4_)),true,0);
@@ -4841,6 +5222,17 @@ package
return _loc4_;
}
// the item's own colour that a row is on (param1.colorIndex), or 0
private function itemOwnColour(param1:Object) : uint
{
var _loc2_:Object = ItemXtCommManager.getItemDef(int(param1.id));
if(_loc2_ == null || _loc2_.colors == null || _loc2_.colors.length == 0)
{
return 0;
}
return uint(_loc2_.colors[Math.min(int(param1.colorIndex),_loc2_.colors.length - 1)]);
}
// the colour a clothing row is drawn in: the box's colour id or hex
// colour, else the item's own colour that the row is on
private function finderPreviewColour(param1:Object) : uint
@@ -4869,16 +5261,15 @@ package
// a negative id is the same colour written signed
return uint(Number(_loc2_));
}
_loc4_ = ItemXtCommManager.getItemDef(int(param1.id));
if(_loc4_ == null || _loc4_.colors == null || _loc4_.colors.length == 0)
{
return 0;
}
return uint(_loc4_.colors[Math.min(int(param1.colorIndex),_loc4_.colors.length - 1)]);
return itemOwnColour(param1);
}
// the row's item as the game draws it in a shop, in a box at the row's end
private function finderPreview(param1:Object, param2:int, param3:Number, param4:Number) : Sprite
// param5: a row of the item giver's, drawn in its colour box's colour
// and recoloured as that changes. the Item Maker's rows are drawn by
// this too, in the item's own colour: the giver's box coloured them,
// and its colour turned up in the maker.
private function finderPreview(param1:Object, param2:int, param3:Number, param4:Number, param5:Boolean = true) : Sprite
{
var _loc5_:Sprite = new Sprite();
var _loc6_:Sprite = new Sprite();
@@ -4918,7 +5309,7 @@ package
return _loc5_;
}
_loc8_ = new Item();
Item(_loc8_).init(int(param1.id),0,finderPreviewColour(param1),null,true);
Item(_loc8_).init(int(param1.id),0,param5 ? finderPreviewColour(param1) : itemOwnColour(param1),null,true);
}
// fitted to the box once drawn, which may be before the icon is
// handed back when its picture was loaded already
@@ -4944,7 +5335,10 @@ package
_loc8_.imageLoadedCallback();
}
}
_finderIcons[param2] = _loc8_;
if(param5)
{
_finderIcons[param2] = _loc8_;
}
}
catch(e:Error)
{
-13
View File
@@ -700,19 +700,6 @@ package gui
{
var _loc2_:WorldPet = null;
param1.stopPropagation();
// Outside a play-as-your-pet event this button is the personal
// pet-form switch. The server echoes the change to everybody in
// the room, so this is not merely a local visual effect.
if(!GuiManager.isBeYourPetRoom())
{
if(AvatarManager.playerAvatarWorldView && AvatarManager.playerAvatarWorldView.getActivePet())
{
UserCommXtCommManager.sendPetPlayerMode(!GuiManager.isPlayingAsPet());
}
actionBtn.dispatchEvent(new MouseEvent("mouseDown"));
param1.currentTarget.downToUpState();
return;
}
if(AvatarManager.playerAvatarWorldView)
{
_loc2_ = AvatarManager.playerAvatarWorldView.getActivePet();
+234 -4
View File
@@ -38,6 +38,8 @@ package gui
import flash.events.MouseEvent;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.text.TextField;
import flash.text.TextFormat;
import gui.itemWindows.ItemWindowNameBarIcon;
import gui.itemWindows.ItemWindowOriginal;
import inventory.Iitem;
@@ -222,6 +224,17 @@ package gui
private var _colorTableColor2:ColorTable;
private var _colorTablePatterns:ColorTable;
// a special animal's pattern has four colours, a byte each of its
// colour number (its presets set all four; LayerBitmap draws them and
// the blends between them): the tables of the second, third and
// fourth, each shown in place of the first's while its number beside
// them is chosen
private var _patternColorTables:Array;
private var _patternColorBtns:Array;
private var _patternColorSlot:int;
private var _colorTableEyes:ColorTable;
@@ -242,6 +255,10 @@ package gui
private var _itemClothingWindows:WindowAndScrollbarGenerator;
private var _itemTradeWindows:WindowAndScrollbarGenerator;
private var _inventoryPlusBtn:Sprite;
private var _inventoryMinusBtn:Sprite;
public var numClothingItemsInTradeListInitially:int;
@@ -428,6 +445,15 @@ package gui
_colorTableColor1.destroy();
_colorTableColor2.destroy();
_colorTablePatterns.destroy();
for each(var _loc9_:ColorTable in _patternColorTables)
{
if(_loc9_ != _colorTablePatterns)
{
_loc9_.destroy();
}
}
_patternColorTables = null;
_patternColorBtns = null;
_colorTableEyes.destroy();
_namebarBadgeMediaIds = null;
_nameBars = null;
@@ -549,6 +575,7 @@ package gui
{
createItemWindows(_currClothesArray,avEditor.itemBlock);
}
setupInventoryControls();
addListeners();
KeepAlive.startKATimer(avEditor);
_loadingMediaHelper.destroy();
@@ -615,6 +642,17 @@ package gui
_colorTableColor2.init(1,240,150,10,5,_gamePalette,_avatarPalette2,_loc10_,onColorChanged,102);
_colorTablePatterns = new ColorTable();
_colorTablePatterns.init(3,240,150,10,5,_gamePalette,_avatarPalette1,_loc8_,onColorChanged,102);
_patternColorTables = [_colorTablePatterns];
var _loc13_:int = 1;
while(_loc13_ < 4)
{
_patternColorTables[_loc13_] = new ColorTable();
ColorTable(_patternColorTables[_loc13_]).init(3 + _loc13_,240,150,10,5,_gamePalette,_avatarPalette1,_loc2_[1] >> 24 - _loc13_ * 8 & 0xFF,onColorChanged,102);
ColorTable(_patternColorTables[_loc13_]).x = 21;
ColorTable(_patternColorTables[_loc13_]).y = 176;
_loc13_++;
}
_patternColorSlot = 0;
_colorTableEyes = new ColorTable();
_colorTableEyes.init(2,240,150,10,5,_gamePalette,_avatarPalette1,_loc5_,onColorChanged,102);
_colorTableColor1.x = 21;
@@ -909,9 +947,16 @@ package gui
_loc9_ = _loc6_ >> 8 & 0xFF;
_loc3_ = _loc6_ & 0xFF;
_loc6_ = uint(_loc5_ << 24 | _loc7_ << 16 | _loc9_ << 8 | _loc3_);
break;
case 4:
case 5:
case 6:
// a special animal's pattern's second, third or fourth colour
_loc5_ = 24 - (param1 - 3) * 8;
_loc6_ = uint(_loc6_ & ~(0xFF << _loc5_) | (param2 & 0xFF) << _loc5_);
}
_avatarEditorView.colors = [_loc4_,_loc6_,_loc8_];
if(param1 == 2 || param1 == 3)
if(param1 >= 2)
{
colorCurrEyePattIcon();
}
@@ -1256,6 +1301,7 @@ package gui
avEditor.colorTableBlock.patternsAndEyes.removeChild(_colorTableEyes);
}
avEditor.colorTableBlock.patternsAndEyes.addChild(_colorTablePatterns);
showPatternColorChoice(_worldAvatar.customAvId != -1);
if(_patterns.length > 0)
{
if(_patterns.length <= 1 && _worldAvatar.customAvId == -1)
@@ -1286,6 +1332,7 @@ package gui
{
avEditor.colorTableBlock.patternsAndEyes.removeChild(_colorTablePatterns);
}
showPatternColorChoice(false);
if(_customAvtIcon && avEditor.colorTableBlock.patternsAndEyes.specialAvtIconCont.contains(_customAvtIcon))
{
avEditor.colorTableBlock.patternsAndEyes.specialAvtIconCont.removeChild(_customAvtIcon);
@@ -1316,6 +1363,77 @@ package gui
avEditor.colorTableBlock.colors.visible = false;
}
// the "1" to "4" left of the pattern's colour table, choosing which of
// its four colours it sets, with that colour's table (param1), or
// neither, and the first's table back
private function showPatternColorChoice(param1:Boolean) : void
{
var _loc2_:MovieClip = avEditor.colorTableBlock.patternsAndEyes;
var _loc3_:int = 0;
var _loc4_:Sprite = null;
if(_patternColorBtns == null)
{
_patternColorBtns = [];
while(_loc3_ < 4)
{
_loc4_ = createSmallButton(String(_loc3_ + 1));
_loc4_.name = "patternColor" + _loc3_;
_loc4_.x = 2;
_loc4_.y = 176 + _loc3_ * 20;
_loc4_.addEventListener("mouseDown",onPatternColorBtn,false,0,true);
_patternColorBtns.push(_loc4_);
_loc3_++;
}
}
_loc3_ = 0;
while(_loc3_ < _patternColorBtns.length)
{
_loc4_ = _patternColorBtns[_loc3_];
if(param1)
{
_loc2_.addChild(_loc4_);
_loc4_.alpha = _loc3_ == _patternColorSlot ? 1 : 0.45;
}
else if(_loc4_.parent)
{
_loc4_.parent.removeChild(_loc4_);
}
_loc3_++;
}
// the first's table is added and taken away with the tab
_loc3_ = 1;
while(_loc3_ < _patternColorTables.length)
{
if(_loc2_.contains(_patternColorTables[_loc3_]))
{
_loc2_.removeChild(_patternColorTables[_loc3_]);
}
_loc3_++;
}
if(param1)
{
if(_patternColorSlot == 0)
{
_loc2_.addChild(_colorTablePatterns);
}
else
{
if(_loc2_.contains(_colorTablePatterns))
{
_loc2_.removeChild(_colorTablePatterns);
}
_loc2_.addChild(_patternColorTables[_patternColorSlot]);
}
}
}
private function onPatternColorBtn(param1:MouseEvent) : void
{
param1.stopPropagation();
_patternColorSlot = int(Sprite(param1.currentTarget).name.charAt(12));
showPatternColorChoice(true);
}
private function onCustomIconLoaded(param1:MovieClip) : void
{
if(_avatarEditorView)
@@ -1920,6 +2038,7 @@ package gui
var _loc7_:Boolean = false;
var _loc4_:Number = NaN;
var _loc5_:Object = null;
var _loc9_:int = 0;
_loc6_ = param1 == _currTradesArray;
if(_loc6_)
{
@@ -1979,7 +2098,9 @@ package gui
}
_loc5_ = generateItemAndIndexArray(param1);
_loc8_ = new WindowAndScrollbarGenerator();
_loc8_.init(param2.width,param2.height,3,_loc4_,3,4,12,2,2,2 * 0.5,0,ItemWindowOriginal,_loc5_.items,"icon",0,{
// Expanded Inventory: more, smaller items a row (AJClient.inventoryColumns)
_loc9_ = AJClient.inventoryColumns();
_loc8_.init(param2.width,param2.height,3,_loc4_,_loc9_,4,_loc9_ * 4,2,2,2 * 0.5,0,ItemWindowOriginal,_loc5_.items,"icon",0,{
"mouseDown":winMouseClick,
"mouseOver":winMouseOver,
"mouseOut":winMouseOut,
@@ -1990,7 +2111,8 @@ package gui
"showAddRemoveBtns":_loc6_,
"isChoosingForTradeList":_loc7_,
"indexArray":_loc5_.indexes,
"mannequinInvIdx":(_mannequinDenItemHelper != null ? _mannequinDenItemHelper.mannequin.invIdx : -1)
"mannequinInvIdx":(_mannequinDenItemHelper != null ? _mannequinDenItemHelper.mannequin.invIdx : -1),
"itemScale":3 / _loc9_
});
if(param2 == avEditor.itemBlock)
{
@@ -2201,6 +2323,15 @@ package gui
if(!DenAndClothesItemSelect.moreToCome)
{
openCloseTradeWindow();
// the list drawn again with all of it: each item added went into
// an empty window of the list, and with many picked at once
// there were too few of those, so the rest were not shown
if(_itemTradeWindows && avEditor.tradeBtnUp.visible)
{
_itemTradeWindows.destroy();
_itemTradeWindows = null;
createItemWindows(_currTradesArray,avEditor.itemBlock);
}
}
}
@@ -2656,7 +2787,106 @@ package gui
avEditor.sortPopup.visible = false;
createItemWindows(_currClothesArray,avEditor.itemBlock);
}
// Expanded Inventory's + and - (Strawberry Jam's), by the item counter:
// 3, 4 or 5 items a row (AJClient.inventoryColumns). they are put in
// the counter, where Strawberry Jam puts them by it, so they are shown
// and hidden with it.
private function setupInventoryControls() : void
{
var _loc1_:MovieClip = null;
var _loc2_:Point = null;
if(_inventoryPlusBtn && _inventoryPlusBtn.parent)
{
_inventoryPlusBtn.parent.removeChild(_inventoryPlusBtn);
}
if(_inventoryMinusBtn && _inventoryMinusBtn.parent)
{
_inventoryMinusBtn.parent.removeChild(_inventoryMinusBtn);
}
_inventoryPlusBtn = null;
_inventoryMinusBtn = null;
if(!AJClient.expandedInventoryOn() || !avEditor || !("itemCounter" in avEditor) || !avEditor.itemCounter)
{
return;
}
_loc1_ = avEditor.itemCounter;
_loc2_ = _loc1_.globalToLocal(avEditor.localToGlobal(new Point(_loc1_.x + _loc1_.counterTxt.width - 30,_loc1_.y - 7)));
_inventoryPlusBtn = createSmallButton("+");
_inventoryMinusBtn = createSmallButton("-");
_inventoryPlusBtn.x = _loc2_.x;
_inventoryPlusBtn.y = _loc2_.y;
_inventoryMinusBtn.x = _loc2_.x + 18;
_inventoryMinusBtn.y = _loc2_.y;
_inventoryPlusBtn.addEventListener("mouseDown",onInventoryPlus,false,0,true);
_inventoryMinusBtn.addEventListener("mouseDown",onInventoryMinus,false,0,true);
_loc1_.addChild(_inventoryPlusBtn);
_loc1_.addChild(_inventoryMinusBtn);
}
private function createSmallButton(param1:String) : Sprite
{
var _loc2_:Sprite = new Sprite();
var _loc3_:TextField = new TextField();
_loc2_.graphics.beginFill(3355443,0.8);
_loc2_.graphics.drawRoundRect(0,0,16,16,3,3);
_loc2_.graphics.endFill();
_loc2_.graphics.lineStyle(1,16777215,0.5);
_loc2_.graphics.drawRoundRect(0,0,16,16,3,3);
_loc3_.defaultTextFormat = new TextFormat("_sans",12,16777215,true);
_loc3_.text = param1;
_loc3_.x = 4;
_loc3_.y = 1;
_loc3_.width = 12;
_loc3_.height = 16;
_loc3_.selectable = false;
_loc3_.mouseEnabled = false;
_loc2_.addChild(_loc3_);
_loc2_.buttonMode = true;
_loc2_.mouseChildren = false;
return _loc2_;
}
private function onInventoryPlus(param1:MouseEvent) : void
{
param1.stopPropagation();
stepInventoryColumns(1);
}
private function onInventoryMinus(param1:MouseEvent) : void
{
param1.stopPropagation();
stepInventoryColumns(-1);
}
private function stepInventoryColumns(param1:int) : void
{
AJClient.stepInventoryColumns(param1);
refreshInventoryLayout();
}
// the clothes drawn again as many a row as now asked for, and the + and
// - put up or taken away (also when Settings turns the switch). only
// while the clothes are shown (the counter is, then): the trade list's
// windows take the new count when they are next made.
public function refreshInventoryLayout() : void
{
if(!avEditor)
{
return;
}
if(_itemClothingWindows && "itemCounter" in avEditor && avEditor.itemCounter && avEditor.itemCounter.visible)
{
_itemClothingWindows.destroy();
_itemClothingWindows = null;
if(_currClothesArray)
{
createItemWindows(_currClothesArray,avEditor.itemBlock);
}
}
setupInventoryControls();
}
private static function sortByName(param1:Object, param2:Object) : int
{
var _loc3_:String = String(param1.name).toLowerCase();
File diff suppressed because it is too large. Load diff
+142 -29
View File
@@ -65,9 +65,9 @@ package avatar
private static const SLIDE_FRAME_TIME:Number = 41.666666666666664;
// name tag badges everyone sees, buddy or not, as the game shows its
// News Crew camera (NameBar.isVIPBadge): the Owner, Moderator and
// Verified badges of lib/badges.js, by their def ids.
private static const PUBLIC_BADGE_IDS:Array = [63,64,76];
// News Crew camera (NameBar.isVIPBadge): the Owner, Moderator,
// Developer and Verified badges of lib/badges.js, by their def ids.
private static const PUBLIC_BADGE_IDS:Array = [63,64,66,76];
private static const GLOW_LAND_DEFAULT_COLOR:int = 5586479;
@@ -229,6 +229,11 @@ package avatar
private var _chatBalloon:ChatBalloon;
// Set while the normal uc packet is handled, immediately before its
// message is drawn. Keeping setMessage's original arguments preserves
// the game's pending-message and chat-history behaviour.
private var _nextChatStyle:String = "";
// "..." where the chat bubble goes, while the player is typing
// (AJClient.onTyping). gone when a line arrives, when they stop, or
// TYPING_SHOWN ms after they last said they were, if a "stopped" is lost.
@@ -335,6 +340,12 @@ package avatar
private var _currPetName:String;
private var _shouldShowPetOnly:Boolean;
// the pet chooser's switch as last heard for this avatar (type-13 user
// communication), and the pet last set, to make it again in either form
private var _petPlayerMode:Boolean;
private var _petArgs:Array;
private var _emitParticles:Boolean;
@@ -552,7 +563,7 @@ package avatar
_loc12_ = 1;
}
_chatBalloon = GETDEFINITIONBYNAME("ChatBalloonAsset",false);
_chatBalloon.init(_avatar.avTypeId,AvatarUtility.getAvatarEmoteBgOffset,false,_loc12_,RoomManagerWorld.instance.layerManager.bkg.scaleX,SBTextField,onChatBallonAdventureDown,onChatBalloonPVPDown);
_chatBalloon.init(_avatar.avTypeId,emoteBgOffset,false,_loc12_,RoomManagerWorld.instance.layerManager.bkg.scaleX,SBTextField,onChatBallonAdventureDown,onChatBalloonPVPDown);
_chatLayer.addChild(_chatBalloon);
_moving = 0;
_lastMoveAngle = 2;
@@ -605,7 +616,7 @@ package avatar
_hudViewHolder.mouse.gotoAndStop(offScreenDefaultMouseFrameLabel());
}
}
_shouldShowPetOnly = GuiManager.isBeYourPetRoom() || userId == AvatarManager.playerSfsUserId && GuiManager.isPlayingAsPet();
_shouldShowPetOnly = GuiManager.isBeYourPetRoom() || (userId == AvatarManager.playerSfsUserId ? GuiManager.isPlayingAsPet() : _petPlayerMode);
if(_shouldShowPetOnly)
{
_layerAnim.alpha = 0;
@@ -799,9 +810,34 @@ package avatar
return false;
}
// plays an animation and keeps it as this avatar's idle, so the client's
// own idle refreshes don't put the avatar back to standing. Walking or
// an action replaces it, as with any idle.
public function holdIdleAnim(param1:int, param2:Boolean) : void
{
_lastIdleAnim = param1;
_lastIdleFlip = param2;
playAnim(param1,param2);
}
public function getBaseIdle() : int
{
return _roomType == 1 ? 32 : 14;
return drawnSwimming() ? 32 : 14;
}
// whether the animal is drawn with its swimming animations: the
// room's kind when it has art for both, else the one it has. a land
// animal in water (or a sea one on land) asked for art it has none of,
// and stood invisible until it did something it had art for.
private function drawnSwimming() : Boolean
{
var _loc1_:Boolean = _avatar == null || Utility.isLand(_avatar.enviroTypeFlag);
var _loc2_:Boolean = _avatar == null || Utility.isOcean(_avatar.enviroTypeFlag);
if(_loc1_ == _loc2_)
{
return _roomType == 1;
}
return _loc2_;
}
public function setPath(param1:Array) : void
@@ -1160,6 +1196,11 @@ package avatar
}
}
public function setChatStyle(param1:String) : void
{
_nextChatStyle = param1;
}
public function setMessage(param1:String, param2:int) : void
{
var _loc3_:Boolean = false;
@@ -1175,8 +1216,9 @@ package avatar
}
_loc3_ = true;
}
_chatBalloon.setText(param1,_loc3_);
updateOffScreenChat(param1,_loc3_);
_chatBalloon.setText(param1,_loc3_,true,_nextChatStyle);
updateOffScreenChat(param1,_loc3_,_nextChatStyle);
_nextChatStyle = "";
}
public function setCustomAdventureMessage(param1:String, param2:String, param3:int, param4:int, param5:Boolean = false) : void
@@ -2066,6 +2108,7 @@ package avatar
public function setActivePet(param1:Number, param2:uint, param3:uint, param4:uint, param5:String, param6:int, param7:int, param8:int, param9:int = 0) : void
{
_petArgs = [param1,param2,param3,param4,param5,param6,param7,param8,param9];
if(_pet)
{
if(_pet.parent == this)
@@ -2088,12 +2131,23 @@ package avatar
_splash.showShadow(false);
}
_currPetName = LocalizationManager.translatePetName(param5);
_namebar.setAvName(_currPetName);
setPetFormName();
}
else
{
_splash.showShadow(true);
}
// another pet out in the pet form: the HUD shows the new one
if(_shouldShowPetOnly && userId == AvatarManager.playerSfsUserId)
{
GuiManager.setPersonalPetMode(true);
}
}
// a pet that cannot come into this room leaves the avatar shown
if(_shouldShowPetOnly && !_pet && !GuiManager.isBeYourPetRoom())
{
_shouldShowPetOnly = false;
showPetForm();
}
}
@@ -2102,8 +2156,30 @@ package avatar
// own state instead of asking the room-wide GuiManager predicate.
public function setPetPlayerMode(param1:Boolean) : void
{
var _loc2_:Boolean = param1 && _pet != null;
_shouldShowPetOnly = _loc2_ || GuiManager.isBeYourPetRoom();
var _loc2_:Boolean = false;
_petPlayerMode = param1;
_loc2_ = GuiManager.isBeYourPetRoom() || param1 && _petArgs != null && _petArgs[1] != 0;
if(_loc2_ != _shouldShowPetOnly)
{
_shouldShowPetOnly = _loc2_;
// WorldPet takes its size and place from the form when it is
// made, so the pet is made again
if(_petArgs != null)
{
setActivePet.apply(this,_petArgs);
}
}
showPetForm();
if(userId == AvatarManager.playerSfsUserId)
{
GuiManager.setPersonalPetMode(_shouldShowPetOnly);
}
}
// the avatar or its pet, as _shouldShowPetOnly says
private function showPetForm() : void
{
var _loc1_:UserInfo = null;
_layerAnim.alpha = _shouldShowPetOnly ? 0 : 1;
_layerAnim.avatarEnabled = !_shouldShowPetOnly;
if(_shouldShowPetOnly && _pet)
@@ -2112,17 +2188,52 @@ package avatar
{
_splash.showShadow(false);
}
_namebar.setAvName(_currPetName);
setPetFormName();
}
else
{
_splash.showShadow(true);
_namebar.setAvName(_avatar.avName);
_loc1_ = gMainFrame.userInfo.getUserInfoByUserName(_avatar.userName);
_namebar.setAvName(_avatar,Utility.isSettingOn(MySettings.SETTINGS_USERNAME_BADGE),_loc1_);
}
if(userId == AvatarManager.playerSfsUserId)
placeChatBalloon();
updateChatBallonBgOffsets();
}
// the pet stands in for this avatar: the party's or quest's form, or
// the pet chooser's switch (WorldPet asks)
public function isPetForm() : Boolean
{
return _shouldShowPetOnly;
}
// the name over the pet in its form, as the settings menu's Usernames /
// Animal Names switch says: the player's username (the default), or
// the pet's name
private function setPetFormName() : void
{
if(Utility.isSettingOn(MySettings.SETTINGS_USERNAME_BADGE))
{
GuiManager.setPersonalPetMode(_loc2_);
_namebar.setAvName(_avatar,true,gMainFrame.userInfo.getUserInfoByUserName(_avatar.userName));
}
else
{
_namebar.setAvName(_currPetName ? _currPetName : _avatar.avName);
}
}
// chat balloons and emotes sit over the pet in its form, as the
// party's do (AvatarUtility's pet offsets)
private function placeChatBalloon() : void
{
var _loc1_:Point = _shouldShowPetOnly ? new Point(10,-80) : AvatarUtility.getAvatarChatOffset(_avatar.avTypeId);
_chatBalloon.x = this.x + _loc1_.x;
_chatBalloon.y = this.y + _loc1_.y;
}
private function emoteBgOffset(param1:int) : Point
{
return _shouldShowPetOnly ? new Point(-5,-25) : AvatarUtility.getAvatarEmoteBgOffset(param1);
}
public function getActivePet() : WorldPet
@@ -2281,9 +2392,7 @@ package avatar
param2 *= _scale.y;
this.x = param1;
this.y = param2;
var _loc3_:Point = AvatarUtility.getAvatarChatOffset(_avatar.avTypeId);
_chatBalloon.x = this.x + _loc3_.x;
_chatBalloon.y = this.y + _loc3_.y;
placeChatBalloon();
if(_avSwitchedNPC)
{
_avSwitchedNPC.x = param1;
@@ -2359,9 +2468,9 @@ package avatar
{
_hudViewHolder.mouse.gotoAndStop(offScreenDefaultMouseFrameLabel());
}
if(GuiManager.isBeYourPetRoom())
_loc7_ = gMainFrame.userInfo.getAvatarInfoByUsernamePerUserAvId(userName,perUserAvId);
if(_shouldShowPetOnly && _loc7_ && _loc7_.currPet)
{
_loc7_ = gMainFrame.userInfo.getAvatarInfoByUsernamePerUserAvId(userName,perUserAvId);
_hudAvtOrPetView = new GuiPet(_loc7_.currPet.createdTs,0,_loc7_.currPet.lBits,_loc7_.currPet.uBits,_loc7_.currPet.eBits,_loc7_.currPet.type,_loc7_.currPet.name,_loc7_.currPet.personalityDefId,_loc7_.currPet.favoriteToyDefId,_loc7_.currPet.favoriteFoodDefId,onHudAvtOrPetView);
}
else
@@ -2479,7 +2588,7 @@ package avatar
var _loc3_:Number = NaN;
if(_hudAvtOrPetView)
{
if(GuiManager.isBeYourPetRoom())
if(_hudAvtOrPetView is GuiPet)
{
_hudAvtOrPetView.y = 15;
}
@@ -2510,11 +2619,11 @@ package avatar
_secondaryEmot.y = -235 * _loc1_;
}
private function updateOffScreenChat(param1:String, param2:Boolean) : void
private function updateOffScreenChat(param1:String, param2:Boolean, param3:String = "") : void
{
if(shouldShowOffscreen() && gMainFrame.userInfo.myUserName != _avatar.userName && _hudViewHolder)
{
_hudViewHolder.questChatBalloon.setText(param1,param2,false);
_hudViewHolder.questChatBalloon.setText(param1,param2,false,param3);
}
}
@@ -2538,7 +2647,7 @@ package avatar
_lastMoveAngle = _loc7_;
var _loc8_:Object = convertToIdle(_lastMoveAngle);
_lastIdleAnim = _loc8_.anim;
if(_roomType == 1)
if(drawnSwimming())
{
_lastIdleAnim = getBaseIdle();
}
@@ -2605,7 +2714,7 @@ package avatar
_loc9_ = 14;
}
}
if(_roomType == 1)
if(drawnSwimming())
{
_loc9_ = 29;
}
@@ -2629,7 +2738,11 @@ package avatar
public function updateNameBarName() : void
{
if(_namebar)
if(_namebar && _shouldShowPetOnly)
{
setPetFormName();
}
else if(_namebar)
{
_namebar.setAvName(_avatar,Utility.isSettingOn(MySettings.SETTINGS_USERNAME_BADGE),gMainFrame.userInfo.getUserInfoByUserName(_avatar.userName));
}
@@ -2656,9 +2769,9 @@ package avatar
{
_namebar.setColorAndBadge(0);
_namebar.setColorBadgeAndXp(0,0,_isMember);
if(_shouldShowPetOnly && _currPetName)
if(_shouldShowPetOnly)
{
_namebar.setAvName(_currPetName);
setPetFormName();
}
else
{
@@ -2694,7 +2807,7 @@ package avatar
public function preload(param1:Function) : void
{
var _loc2_:Array = [];
if(_roomType == 1)
if(drawnSwimming())
{
_loc2_.push(29);
_loc2_.push(32);
+7 -1
View File
@@ -133,6 +133,11 @@ package buddy
private var _joinLabel:Sprite;
// the animal's box as the card's art has it, measured before an animal
// is put in it: measured with one in, a tall animal (or the one still
// there from the card's last opening) put the label up on the name
private var _charBoxRect:Rectangle;
private var _badgeRow:Sprite;
private var _discordIcon:Sprite;
@@ -829,6 +834,7 @@ package buddy
_bioMediaHelper = new MediaHelper();
_bioMediaHelper.init(BIO_TAB_MEDIA_ID,onBioTabLoaded);
charBox = _buddyCardMC.charBox;
_charBoxRect = charBox.getBounds(_buddyCardMC);
userNameTxt = _buddyCardMC.userName_txt;
avatarNameTxt = _buddyCardMC.avatarNameTxt;
shamanTag = _buddyCardMC.shamanTag;
@@ -993,7 +999,7 @@ package buddy
}
_joinLabel = AJClient.makePill(_loc3_,9067051,6044183,false,11);
_joinLabel.mouseEnabled = false;
_loc2_ = charBox.getBounds(_buddyCardMC);
_loc2_ = _charBoxRect != null ? _charBoxRect : charBox.getBounds(_buddyCardMC);
_joinLabel.x = int(_loc2_.right - _joinLabel.width - 8);
_joinLabel.y = int(_loc2_.top + 8);
_buddyCardMC.addChild(_joinLabel);
+4 -2
View File
@@ -167,7 +167,7 @@ package buddy
private static function onHasReferralAssociationResponse(param1:int) : void
{
_hasRequestedReferralAssociation = true;
_buddyListReferFriendBg.visible = true;
_buddyListReferFriendBg.visible = param1 == 1;
if(param1 == 1)
{
_buddyListReferAFriendBtn.visible = true;
@@ -175,8 +175,10 @@ package buddy
}
else
{
// "How did you hear?" is never offered here: its window soft
// locked the game, and nothing reads its answer.
_buddyListReferAFriendBtn.visible = false;
_buddyListHowDidYouHearBtn.visible = true;
_buddyListHowDidYouHearBtn.visible = false;
}
if(_buddyListPopup.visible)
{
+407 -11
View File
@@ -1,12 +1,19 @@
package gui
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.MovieClip;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.display.GradientType;
import flash.display.SpreadMethod;
import flash.events.MouseEvent;
import flash.events.TextEvent;
import flash.filters.ConvolutionFilter;
import flash.geom.ColorTransform;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.geom.Matrix;
import flash.text.TextField;
import flash.utils.setTimeout;
import loader.MediaHelper;
@@ -66,18 +73,47 @@ package gui
private var _emoteBGOffsetFunc:Function;
// emotes drawn inside a line of chat, small, where they were typed: an
// emote's code standing as a word of its own ("hi :) there", ":fever:"),
// or anywhere after a "\" ("yay\:)"). and emoji (typed with Windows'
// emote's code standing as a word of its own ("hi :) there", ":fever:").
// a "\" before one keeps it as typed ("\:)" shows ":)"), as it does a
// ":name:" of an emoji (AJClient.emojiShortcodes). and emoji (typed with Windows'
// emoji panel, say), which the game's font has none of: each is drawn
// as a picture of it, from the server (/emoji/<code points>.png,
// Twemoji's). each is {at, clip}: where its gap starts in the text shown.
// Three spaces fit the line-height-sized emoji without the noticeably
// wide hole four spaces left between neighbouring words or emoji.
private static const INLINE_GAP:String = " ";
// Four spaces reserve a full inline cell. placeInline() scales wide
// artwork to this measured slot with a one-pixel gutter on each side,
// so consecutive emoji neither overlap nor touch surrounding text.
private static const INLINE_GAP:String = " ";
// after each gap: a gap ending the text was trailing spaces, which a
// centred line leaves out, so the text sat off centre and its last
// emoji past it. this is no space, and has no width.
private static const INLINE_END:String = "\u200B";
private static const LONGEST_EMOTE_CODE:int = 16;
private var _inline:Array = [];
// The server appends this compact style to spoken chat packets. It is
// deliberately drawn over the stock balloon rather than requiring new
// artwork, so every combination of the account-page colour controls is
// available at once.
private var _styleFill:Sprite;
private var _styleMask:Bitmap;
private var _styleBorderLayer:Bitmap;
private var _styleBackground:uint;
private var _styleAccent:uint;
private var _styleText:uint;
private var _styleBorder:uint;
private var _styleOpacity:Number;
private var _styleAnimation:String = "none";
private var _styleSpeed:Number = 100;
private var _styleGradient:String = "linear";
private var _styleAngle:Number = 45;
private var _styleStrength:Number = 100;
private var _styleOutline:Number = 1;
private var _styleStops:Array = [];
private var _styleElapsed:int = 0;
private var _hasStyle:Boolean = false;
public function ChatBalloon()
{
@@ -112,7 +148,7 @@ package gui
setEmoteBgOffsets();
}
public function setText(param1:String, param2:Boolean = false, param3:Boolean = true) : void
public function setText(param1:String, param2:Boolean = false, param3:Boolean = true, param4:String = "") : void
{
if(_emote)
{
@@ -142,7 +178,8 @@ package gui
_msgTxt.height;
// AJClient.whisperNext is set by the server's "xw" just ahead of a
// whispered line.
_balloonBG.transform.colorTransform = AJClient.whisperNext ? AJClient.whisperTint() : new ColorTransform();
var _loc10_:Boolean = AJClient.whisperNext;
_balloonBG.transform.colorTransform = _loc10_ ? AJClient.whisperTint() : new ColorTransform();
AJClient.whisperNext = false;
if(!_hasSbTextfield)
{
@@ -172,6 +209,10 @@ package gui
{
_msgTxt.textColor = 4477529;
}
// Emoji-window choices are inline chat content, so even a lone one
// keeps the selected chat style. Standalone game emotes use
// setEmote(), where any previous custom bubble is cleared.
applyStyle(param4,param2,_loc10_);
// tags (AJClient.resolveMentions): once the server says which "@"s
// are players', light blue and underlined, each a link to that
// player's card, if the balloon still says the same. (the field is
@@ -181,6 +222,8 @@ package gui
var field:TextField = TextField(_msgTxt);
var shown:String = field.text;
field.addEventListener("link",onMentionLink,false,0,true);
field.addEventListener("mouseDown",onMentionMouse,false,0,true);
field.addEventListener("mouseUp",onMentionMouse,false,0,true);
AJClient.resolveMentions(shown,function(param1:Array):void
{
if(field.text == shown)
@@ -199,6 +242,12 @@ package gui
}
});
}
// The stock balloon has now stretched to the measured text height;
// redraw the custom body at its final size (also for still styles).
if(_hasStyle)
{
drawStyle();
}
_timeout = 8000;
if(param3 && this.parent)
{
@@ -212,6 +261,311 @@ package gui
setTimeout(placeInline,42);
}
}
// `background,accent,text,border,opacity,animation,speed,gradient,angle,
// strength,outline,stops`, emitted by
// lib/chatstyles.js. Staff warnings and whispers intentionally retain
// their existing colours, so those states are never made ambiguous.
private function applyStyle(param1:String, param2:Boolean, param3:Boolean) : void
{
clearStyle();
if(param1 == "" || param2 || param3 || !GuiManager.customChatBubblesEnabled())
{
return;
}
var _loc4_:Array = param1.split(",");
if((_loc4_.length != 7 && _loc4_.length != 10 && _loc4_.length != 11 && _loc4_.length != 12) || !/^[0-9a-fA-F]{6}$/.test(_loc4_[0]) || !/^[0-9a-fA-F]{6}$/.test(_loc4_[1]) || !/^[0-9a-fA-F]{6}$/.test(_loc4_[2]) || !/^[0-9a-fA-F]{6}$/.test(_loc4_[3]) || !/^(?:2[5-9]|[3-9][0-9]|100)$/.test(_loc4_[4]) || !/^(?:[4-9][0-9]|[12][0-9]{2}|300)$/.test(_loc4_[6]))
{
return;
}
_styleBackground = uint(parseInt(_loc4_[0],16));
_styleAccent = uint(parseInt(_loc4_[1],16));
_styleText = uint(parseInt(_loc4_[2],16));
_styleBorder = uint(parseInt(_loc4_[3],16));
_styleOpacity = Math.max(0.25,Math.min(1,Number(_loc4_[4]) / 100));
_styleAnimation = GuiManager.chatBubbleAnimationsEnabled() && (_loc4_[5] == "pulse" || _loc4_[5] == "shimmer" || _loc4_[5] == "flow" || _loc4_[5] == "rainbow") ? _loc4_[5] : "none";
_styleSpeed = Math.max(40,Math.min(300,Number(_loc4_[6])));
_styleGradient = _loc4_.length > 7 && (_loc4_[7] == "solid" || _loc4_[7] == "radial") ? _loc4_[7] : "linear";
_styleAngle = _loc4_.length > 8 && int(_loc4_[8]) >= 0 && int(_loc4_[8]) <= 315 && int(_loc4_[8]) % 45 == 0 ? int(_loc4_[8]) : 45;
_styleStrength = _loc4_.length > 9 ? Math.max(0,Math.min(100,int(_loc4_[9]))) : 100;
_styleOutline = _loc4_.length > 10 ? Math.max(0,Math.min(4,int(_loc4_[10]))) : 1;
_styleStops = parseStyleStops(_loc4_.length > 11 ? String(_loc4_[11]) : "");
_styleElapsed = 0;
_hasStyle = true;
_msgTxt.textColor = _styleText;
// The native artwork remains underneath as the exact outer border;
// drawStyle masks the custom fill to that artwork's silhouette.
_balloonBG.transform.colorTransform = colourTransform(_styleBorder,1);
}
private function clearStyle() : void
{
if(_styleFill)
{
_styleFill.mask = null;
}
if(_styleFill && _styleFill.parent)
{
_styleFill.parent.removeChild(_styleFill);
}
if(_styleMask)
{
if(_styleMask.parent)
{
_styleMask.parent.removeChild(_styleMask);
}
if(_styleMask.bitmapData)
{
_styleMask.bitmapData.dispose();
}
}
if(_styleBorderLayer)
{
if(_styleBorderLayer.parent)
{
_styleBorderLayer.parent.removeChild(_styleBorderLayer);
}
if(_styleBorderLayer.bitmapData)
{
_styleBorderLayer.bitmapData.dispose();
}
}
_styleFill = null;
_styleMask = null;
_styleBorderLayer = null;
_styleAnimation = "none";
_styleGradient = "linear";
_styleStops = [];
_hasStyle = false;
}
private static function colourTransform(param1:uint, param2:Number) : ColorTransform
{
return new ColorTransform(0,0,0,param2,param1 >> 16 & 255,param1 >> 8 & 255,param1 & 255,0);
}
private static function blendColour(param1:uint, param2:uint, param3:Number) : uint
{
var _loc4_:Number = 1 - param3;
var _loc5_:uint = uint((param1 >> 16 & 255) * _loc4_ + (param2 >> 16 & 255) * param3);
var _loc6_:uint = uint((param1 >> 8 & 255) * _loc4_ + (param2 >> 8 & 255) * param3);
var _loc7_:uint = uint((param1 & 255) * _loc4_ + (param2 & 255) * param3);
return _loc5_ << 16 | _loc6_ << 8 | _loc7_;
}
private static function rainbowColour(param1:Number) : uint
{
var _loc2_:int = int(param1 * 6) % 6;
var _loc3_:Number = param1 * 6 - int(param1 * 6);
var _loc4_:uint = uint(255 * _loc3_);
var _loc5_:uint = 255 - _loc4_;
if(_loc2_ == 0)
{
return 0xFF0000 | _loc4_ << 8;
}
if(_loc2_ == 1)
{
return _loc5_ << 16 | 0xFF00;
}
if(_loc2_ == 2)
{
return 0x00FF00 | _loc4_;
}
if(_loc2_ == 3)
{
return _loc5_ << 8 | 0xFF;
}
if(_loc2_ == 4)
{
return _loc4_ << 16 | 0xFF;
}
return 0xFF0000 | _loc5_ << 8;
}
private function parseStyleStops(param1:String) : Array
{
var _loc1_:Array = [];
var _loc2_:Array = String(param1 || "").split(";");
var _loc3_:int = 0;
var _loc4_:Array = null;
var _loc5_:int = -1;
while(_loc3_ < _loc2_.length && _loc2_.length >= 2 && _loc2_.length <= 5)
{
_loc4_ = String(_loc2_[_loc3_]).split(":");
if(_loc4_.length != 2 || !/^[0-9a-fA-F]{6}$/.test(String(_loc4_[0])) || !/^100$|^[1-9]?\d$/.test(String(_loc4_[1])) || int(_loc4_[1]) <= _loc5_)
{
_loc1_ = [];
break;
}
_loc5_ = int(_loc4_[1]);
_loc1_.push({"color":uint(parseInt(_loc4_[0],16)),"position":_loc5_});
_loc3_++;
}
if(_loc1_.length < 2 || int(_loc1_[0].position) != 0 || int(_loc1_[_loc1_.length - 1].position) != 100)
{
_loc1_ = [{"color":_styleBackground,"position":0},{"color":_styleAccent,"position":100}];
}
return _loc1_;
}
private function drawStyle() : void
{
if(!_hasStyle || !_balloonBG || !_msgTxt)
{
return;
}
if(_styleFill == null)
{
_styleFill = new Sprite();
_styleFill.mouseEnabled = false;
_styleFill.mouseChildren = false;
// Flash uses a Bitmap mask's alpha channel only when both sides
// are cached. Without this it masks to the bitmap's rectangle.
_styleFill.cacheAsBitmap = true;
// The stock background contains masks and nested timeline layers.
// Put this beside it, directly below the text, so those masks
// cannot hide custom colours or animated gradients.
var _loc8_:DisplayObject = _msgTxt as DisplayObject;
while(_loc8_ && _loc8_.parent != this)
{
_loc8_ = _loc8_.parent;
}
if(_loc8_ && _loc8_.parent == this)
{
addChildAt(_styleFill,getChildIndex(_loc8_));
}
else
{
addChildAt(_styleFill,Math.min(numChildren,getChildIndex(_balloonBG) + 1));
}
}
var _loc9_:Rectangle = _balloonBG.getBounds(this);
if(_styleMask == null)
{
// Snapshot only the native bubble's alpha and use it as a mask.
// Eroding that silhouette by the chosen outline width leaves the
// tinted native artwork visible as an even border, including the
// speech tail. A rounded-rectangle inset cannot match that shape.
var _loc10_:BitmapData = new BitmapData(Math.max(1,Math.ceil(_loc9_.width)),Math.max(1,Math.ceil(_loc9_.height)),true,0);
var _loc11_:Matrix = _balloonBG.transform.matrix.clone();
_loc11_.translate(-_loc9_.x,-_loc9_.y);
_loc10_.draw(_balloonBG,_loc11_,null,null,null,true);
var _loc20_:BitmapData = new BitmapData(_loc10_.width,_loc10_.height,true,0);
_loc20_.threshold(_loc10_,_loc10_.rect,new Point(),">",0x08000000,0xFFFFFFFF,0xFF000000,false);
_loc10_.dispose();
var _loc32_:BitmapData = _loc20_.clone();
if(_styleOutline > 0)
{
var _loc21_:int = int(_styleOutline) * 2 + 1;
var _loc22_:Array = [];
var _loc23_:int = 0;
var _loc24_:int = 0;
var _loc25_:int = 0;
while(_loc24_ < _loc21_)
{
_loc25_ = 0;
while(_loc25_ < _loc21_)
{
if(Math.abs(_loc24_ - int(_styleOutline)) + Math.abs(_loc25_ - int(_styleOutline)) <= _styleOutline)
{
_loc22_.push(1);
_loc23_++;
}
else
{
_loc22_.push(0);
}
_loc25_++;
}
_loc24_++;
}
var _loc26_:BitmapData = new BitmapData(_loc20_.width,_loc20_.height,true,0);
// Outside the snapshot must be transparent. Clamping repeats
// opaque edge pixels and prevents the top/side of the mask
// from shrinking, which made thick outlines appear only at
// the lower edge and corners.
_loc26_.applyFilter(_loc20_,_loc20_.rect,new Point(),new ConvolutionFilter(_loc21_,_loc21_,_loc22_,_loc23_,0,false,false,0,0));
_loc20_.fillRect(_loc20_.rect,0);
_loc20_.threshold(_loc26_,_loc26_.rect,new Point(),">",0xFE000000,0xFFFFFFFF,0xFF000000,false);
_loc26_.dispose();
// Keep only the pixels removed from the inner mask. This is a
// solid, even ring and does not inherit the stock art's uneven
// border opacity.
_loc32_.threshold(_loc20_,_loc20_.rect,new Point(),">",0x00000000,0x00000000,0xFF000000,false);
_loc32_.colorTransform(_loc32_.rect,colourTransform(_styleBorder,1));
_styleBorderLayer = new Bitmap(_loc32_,"auto",true);
_styleBorderLayer.x = _loc9_.x;
_styleBorderLayer.y = _loc9_.y;
_styleBorderLayer.cacheAsBitmap = true;
addChildAt(_styleBorderLayer,getChildIndex(_styleFill));
}
else
{
_loc32_.dispose();
}
_styleMask = new Bitmap(_loc20_,"auto",true);
_styleMask.x = _loc9_.x;
_styleMask.y = _loc9_.y;
_styleMask.cacheAsBitmap = true;
addChildAt(_styleMask,getChildIndex(_styleFill));
_styleFill.mask = _styleMask;
}
var _loc1_:Number = _loc9_.x;
var _loc2_:Number = _loc9_.y;
var _loc3_:Number = Math.max(12,_loc9_.width);
var _loc4_:Number = Math.max(12,_loc9_.height);
var _loc5_:Number = (_styleElapsed * _styleSpeed / 100000) % 1;
var _loc27_:Array = [];
var _loc28_:Array = [];
var _loc29_:Array = [];
var _loc30_:int = 0;
var _loc31_:uint = 0;
while(_loc30_ < _styleStops.length)
{
_loc31_ = uint(_styleStops[_loc30_].color);
if(_loc30_ > 0)
{
_loc31_ = blendColour(_styleBackground,_loc31_,_styleStrength / 100);
}
if(_styleAnimation == "shimmer")
{
_loc31_ = blendColour(_loc31_,_styleBackground,(Math.sin(_loc5_ * Math.PI * 2) + 1) * 0.5);
}
_loc27_.push(_loc31_);
_loc28_.push(_styleOpacity);
_loc29_.push(int(Number(_styleStops[_loc30_].position) * 2.55));
_loc30_++;
}
_styleFill.graphics.clear();
var _loc7_:Matrix = new Matrix();
var _loc12_:Number = _styleAngle * Math.PI / 180;
var _loc13_:String = _styleGradient == "radial" ? GradientType.RADIAL : GradientType.LINEAR;
_loc7_.createGradientBox(_loc3_,_loc4_,_loc12_,_loc1_,_loc2_);
if(_styleGradient == "solid" && _styleAnimation != "rainbow")
{
_styleFill.graphics.beginFill(_styleBackground,_styleOpacity);
}
else if(_styleAnimation == "flow")
{
_loc7_.createGradientBox(_loc3_ * 0.75,_loc4_ * 0.75,_loc12_,_loc1_ + Math.cos(_loc12_) * (_loc5_ * 2 - 1) * _loc3_,_loc2_ + Math.sin(_loc12_) * (_loc5_ * 2 - 1) * _loc4_);
_styleFill.graphics.beginGradientFill(_loc13_,_loc27_,_loc28_,_loc29_,_loc7_,SpreadMethod.REFLECT);
}
else if(_styleAnimation == "rainbow" && _styleGradient == "solid")
{
_styleFill.graphics.beginFill(rainbowColour(_loc5_),_styleOpacity);
}
else if(_styleAnimation == "rainbow")
{
_styleFill.graphics.beginGradientFill(_loc13_,[rainbowColour(_loc5_),rainbowColour((_loc5_ + 0.18) % 1),rainbowColour((_loc5_ + 0.36) % 1)],[_styleOpacity,_styleOpacity,_styleOpacity],[0,128,255],_loc7_);
}
else
{
_styleFill.graphics.beginGradientFill(_loc13_,_loc27_,_loc28_,_loc29_,_loc7_);
}
_styleFill.graphics.drawRect(_loc1_,_loc2_,_loc3_,_loc4_);
_styleFill.graphics.endFill();
_styleFill.alpha = _styleAnimation == "pulse" ? 0.55 + 0.45 * (Math.sin(_loc5_ * Math.PI * 2) + 1) * 0.5 : 1;
}
// the text with each emote code and emoji (above) replaced by a gap, the
// picture for it kept in _inline. what is neither stays as typed.
@@ -231,7 +585,7 @@ package gui
"at":_loc2_.length,
"clip":emojiClip(param1.substr(_loc3_,_loc8_))
});
_loc2_ += INLINE_GAP;
_loc2_ += INLINE_GAP + INLINE_END;
_loc3_ += _loc8_;
continue;
}
@@ -246,14 +600,26 @@ package gui
"at":_loc2_.length,
"clip":emojiClipNamed(_loc9_[1])
});
_loc2_ += INLINE_GAP;
_loc2_ += INLINE_GAP + INLINE_END;
_loc3_ += String(_loc9_[0]).length;
continue;
}
}
if(param1.charAt(_loc3_) == "\\")
{
// "\" and an emote's code, or ":name:": that, as typed
_loc5_ = emoteCodeAt(param1,_loc3_ + 1,false);
var _loc10_:Array = /^:[a-z0-9_]{1,30}:/.exec(param1.substr(_loc3_ + 1,32));
if(_loc5_ == null && _loc10_ != null)
{
_loc5_ = _loc10_[0];
}
if(_loc5_ != null)
{
_loc2_ += _loc5_;
_loc3_ += 1 + _loc5_.length;
continue;
}
}
else if(_loc3_ == 0 || param1.charAt(_loc3_ - 1) == " ")
{
@@ -268,8 +634,8 @@ package gui
"at":_loc2_.length,
"clip":_loc7_
});
_loc2_ += INLINE_GAP;
_loc3_ += (param1.charAt(_loc3_) == "\\" ? 1 : 0) + _loc5_.length;
_loc2_ += INLINE_GAP + INLINE_END;
_loc3_ += _loc5_.length;
}
else
{
@@ -428,6 +794,8 @@ package gui
var _loc1_:Object = null;
var _loc2_:Rectangle = null;
var _loc3_:Rectangle = null;
var _loc4_:Number = 0;
var _loc5_:Number = 1;
for each(_loc1_ in _inline)
{
_loc2_ = _msgTxt.getCharBoundaries(_loc1_.at);
@@ -445,6 +813,13 @@ package gui
_loc1_.clip.scaleX = _loc1_.clip.scaleY = 1;
_loc1_.clip.height = _loc2_.height;
_loc1_.clip.scaleX = _loc1_.clip.scaleY;
_loc4_ = Math.max(1,_loc3_.x + _loc3_.width - _loc2_.x - 2);
if(_loc1_.clip.width > _loc4_)
{
_loc5_ = _loc4_ / _loc1_.clip.width;
_loc1_.clip.scaleX *= _loc5_;
_loc1_.clip.scaleY *= _loc5_;
}
_loc1_.clip.x = _msgTxt.x + (_loc2_.x + _loc3_.x + _loc3_.width) / 2;
_loc1_.clip.y = _msgTxt.y + _loc2_.y + _loc2_.height / 2;
if(_loc1_.clip.parent != this)
@@ -624,6 +999,18 @@ package gui
}
}
// a press on a tag goes no further: the room under the balloon would
// take it for a click on the floor and walk the player there.
private function onMentionMouse(param1:MouseEvent) : void
{
var _loc2_:TextField = param1.currentTarget as TextField;
var _loc3_:int = _loc2_ != null ? _loc2_.getCharIndexAtPoint(param1.localX,param1.localY) : -1;
if(_loc3_ >= 0 && _loc2_.getTextFormat(_loc3_,_loc3_ + 1).url)
{
param1.stopPropagation();
}
}
// a tag clicked: "@name" (setText)
private function onMentionLink(param1:TextEvent) : void
{
@@ -662,6 +1049,10 @@ package gui
public function setEmote(param1:Sprite, param2:int = -1) : void
{
// Native one-emote messages hide balloon_bg. Remove any independent
// custom fill left by the preceding text message as well.
clearStyle();
_balloonBG.transform.colorTransform = new ColorTransform();
clearMentionBacks();
if(this.currentFrameLabel != "advBtn")
{
@@ -718,6 +1109,11 @@ package gui
public function heartbeat(param1:int) : void
{
if(_styleAnimation != "none" && visible)
{
_styleElapsed += param1;
drawStyle();
}
if(_timeout && _permEmoteMediaId < 0)
{
if(param1 >= _timeout)
+16 -2
View File
@@ -15,6 +15,7 @@ package gui
import flash.text.StyleSheet;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.getTimer;
import flash.ui.Mouse;
import gui.itemWindows.ItemWindowTextNode;
import localization.LocalizationManager;
@@ -50,6 +51,13 @@ package gui
private var _chatRepeatArray:Array;
// a repeat list line (emoji as names) -> {line: as it was said, with
// its emoji, at: getTimer() then}. the names were sent instead, and the
// server says nothing to a line said again within REPEAT_MS (lib/chatspam.js)
private var _chatRepeatSaid:Object = {};
private static const REPEAT_MS:int = 20000;
private var _hasSetupChatRepeatBtn:Boolean;
private var _isOverChatText:Boolean;
@@ -288,6 +296,7 @@ package gui
public function addMessage(param1:String, param2:String, param3:String, param4:String) : void
{
var said:String = param4;
// emoji as their names here: this list has no pictures (AJClient.emojiAsNames)
param4 = AJClient.emojiAsNames(param4);
var _loc5_:Boolean = false;
@@ -298,6 +307,10 @@ package gui
addLine("<a href=\"event:" + plain(param2) + "\">" + plain(Utility.isSettingOn(MySettings.SETTINGS_USERNAME_BADGE) ? param3 : param1) + ": " + "</a>",param4,"\n");
if(_chatRepeatWindow && AvatarManager.playerAvatar && param2.toLowerCase() == AvatarManager.playerAvatar.userName.toLowerCase())
{
_chatRepeatSaid[param4] = {
"line":said,
"at":getTimer()
};
_loc7_ = 0;
while(_loc7_ < _chatRepeatArray.length)
{
@@ -991,9 +1004,10 @@ package gui
private function onRepeatChatSelected(param1:MouseEvent) : void
{
if(!AvatarManager.playerAvatarWorldView.isSameMessage(param1.currentTarget.text))
var _loc2_:Object = _chatRepeatSaid[param1.currentTarget.text];
if(!AvatarManager.playerAvatarWorldView.isSameMessage(param1.currentTarget.text) && !(_loc2_ && getTimer() - _loc2_.at < REPEAT_MS))
{
sendMsgCallback(null,param1.currentTarget.text);
sendMsgCallback(null,_loc2_ ? _loc2_.line : param1.currentTarget.text);
SBTracker.trackPageview("/game/play/popup/repeatChat/#repeat",-1,1);
}
else
+279
View File
@@ -0,0 +1,279 @@
package gameRedemption
{
import com.sbi.popup.SBOkPopup;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.text.TextField;
import gui.DarkenManager;
import gui.GuiManager;
import loader.MediaHelper;
import localization.LocalizationManager;
public class CodeRedemptionPopup
{
private const POPUP_MEDIA_ID:int = 4625;
private const HELP_POPUP_MEDIA_ID:int = 4628;
private var _mediaHelper:MediaHelper;
private var _closeCallback:Function;
private var _guiLayer:DisplayLayer;
private var _redemptionPopup:MovieClip;
private var _closeBtn:MovieClip;
private var _continueBtn:MovieClip;
private var _codeInput:TextField;
private var _helpBtn:MovieClip;
private var _helpPopup:MovieClip;
private var _captchaPopup:CaptchaPopup;
private var _chosenCaptchaAnswer:String;
private var _captchaQuestion:String;
public function CodeRedemptionPopup()
{
super();
}
public function init(param1:Function) : void
{
DarkenManager.showLoadingSpiral(true);
_closeCallback = param1;
_guiLayer = GuiManager.guiLayer;
_mediaHelper = new MediaHelper();
_mediaHelper.init(4625,onRedemptionPopupLoaded);
}
public function destroy() : void
{
var _loc1_:Function = null;
if(_closeCallback != null)
{
_loc1_ = _closeCallback;
_closeCallback = null;
_loc1_();
_loc1_ = null;
return;
}
if(_mediaHelper)
{
_mediaHelper.destroy();
_mediaHelper = null;
}
if(_redemptionPopup)
{
removeEventListeners();
DarkenManager.unDarken(_redemptionPopup);
_guiLayer.removeChild(_redemptionPopup);
}
if(_helpPopup)
{
removeHelpPopupEventListeners();
DarkenManager.unDarken(_helpPopup);
_guiLayer.removeChild(_helpPopup);
_helpPopup = null;
}
_guiLayer = null;
_redemptionPopup = null;
}
private function loadHelpPopup() : void
{
DarkenManager.showLoadingSpiral(true);
_mediaHelper = new MediaHelper();
_mediaHelper.init(4628,onHelpPopupLoaded);
}
private function onRedemptionPopupLoaded(param1:MovieClip) : void
{
DarkenManager.showLoadingSpiral(false);
_redemptionPopup = param1.getChildAt(0) as MovieClip;
_redemptionPopup.x = 900 * 0.5;
_redemptionPopup.y = 550 * 0.5;
_guiLayer.addChild(_redemptionPopup);
DarkenManager.darken(_redemptionPopup);
_closeBtn = _redemptionPopup.bx;
_continueBtn = _redemptionPopup.continueBtn;
_codeInput = _redemptionPopup.codeTxt;
_codeInput.restrict = "A-Za-z0-9\\-";
_helpBtn = _redemptionPopup.helpBtn;
if(gMainFrame.clientInfo.redemptionCode != undefined && gMainFrame.clientInfo.redemptionCode.length > 0)
{
_codeInput.text = gMainFrame.clientInfo.redemptionCode;
}
else
{
_continueBtn.activateGrayState(true);
}
gMainFrame.stage.focus = _codeInput;
_codeInput.setSelection(_codeInput.text.length,_codeInput.text.length);
addEventListeners();
}
private function onHelpPopupLoaded(param1:MovieClip) : void
{
DarkenManager.showLoadingSpiral(false);
_helpPopup = param1.getChildAt(0) as MovieClip;
_helpPopup.x = 900 * 0.5;
_helpPopup.y = 550 * 0.5;
_guiLayer.addChild(_helpPopup);
DarkenManager.unDarken(_redemptionPopup);
DarkenManager.darken(_helpPopup);
addHelpPopupEventListeners();
}
private function addEventListeners() : void
{
gMainFrame.stage.addEventListener("keyDown",onKeyDown,false,0,true);
_redemptionPopup.addEventListener("mouseDown",onPopup,false,0,true);
_closeBtn.addEventListener("mouseDown",onCloseBtn,false,0,true);
_continueBtn.addEventListener("mouseDown",onContinueBtn,false,0,true);
_codeInput.addEventListener("change",onCodeInputChange,false,0,true);
_helpBtn.addEventListener("mouseDown",onHelpBtn,false,0,true);
}
private function addHelpPopupEventListeners() : void
{
_helpPopup.addEventListener("mouseDown",onPopup,false,0,true);
_helpPopup.bx.addEventListener("mouseDown",onHelpClose,false,0,true);
}
private function removeEventListeners() : void
{
gMainFrame.stage.removeEventListener("keyDown",onKeyDown);
_redemptionPopup.removeEventListener("mouseDown",onPopup);
_closeBtn.removeEventListener("mouseDown",onCloseBtn);
_continueBtn.removeEventListener("mouseDown",onContinueBtn);
_codeInput.removeEventListener("change",onCodeInputChange);
_helpBtn.removeEventListener("mouseDown",onHelpBtn);
}
private function removeHelpPopupEventListeners() : void
{
_helpPopup.removeEventListener("mouseDown",onPopup);
_helpPopup.bx.removeEventListener("mouseDown",onHelpClose);
}
private function onPopup(param1:MouseEvent) : void
{
param1.stopPropagation();
}
private function onCloseBtn(param1:MouseEvent) : void
{
param1.stopPropagation();
destroy();
}
private function onContinueBtn(param1:MouseEvent) : void
{
if(param1)
{
param1.stopPropagation();
}
if(!_continueBtn.isGray && _codeInput.length > 0)
{
if(GameRedemptionXtCommManager.captchaToShowData != null)
{
_captchaPopup = new CaptchaPopup();
_captchaPopup.init(GameRedemptionXtCommManager.captchaToShowData.question,GameRedemptionXtCommManager.captchaToShowData.options,onCaptchaClose);
}
else
{
DarkenManager.showLoadingSpiral(true);
GameRedemptionXtCommManager.requestRedeemCode(_codeInput.text,_captchaQuestion,_chosenCaptchaAnswer,onCodeRedeemResponse);
}
}
}
private function onCodeInputChange(param1:Event) : void
{
if(_codeInput.length <= 0)
{
_continueBtn.activateGrayState(true);
}
else
{
_continueBtn.activateGrayState(false);
}
}
// what codes are on this server, in the game's own message box: the
// official help window (media 4628) loaded and showed nothing
private function onHelpBtn(param1:MouseEvent) : void
{
param1.stopPropagation();
new SBOkPopup(_guiLayer,"Codes are given out by the Burrow team: in announcements, at events and on our Discord. Type the code in the box and press Continue. Each code works once for each account.");
}
private function onHelpClose(param1:MouseEvent) : void
{
_helpPopup.visible = false;
DarkenManager.unDarken(_helpPopup);
DarkenManager.darken(_redemptionPopup);
}
private function onKeyDown(param1:KeyboardEvent) : void
{
param1.stopPropagation();
if(param1.keyCode == 13)
{
onContinueBtn(null);
}
}
private function onCodeRedeemResponse(param1:String, param2:Object) : void
{
DarkenManager.showLoadingSpiral(false);
_captchaQuestion = "";
_chosenCaptchaAnswer = "";
switch(param1)
{
case "1":
gMainFrame.clientInfo.redemptionCode = undefined;
destroy();
break;
case "-3":
GuiManager.initEmailConfirmation(null,null,true);
break;
case "-4":
case "-5":
new SBOkPopup(_guiLayer,LocalizationManager.translateIdOnly(25352));
break;
case "-6":
GameRedemptionXtCommManager.captchaToShowData = param2;
onContinueBtn(null);
break;
case "-7":
GameRedemptionXtCommManager.captchaToShowData = param2;
default:
new SBOkPopup(_guiLayer,LocalizationManager.translateIdOnly(24878));
}
}
private function onCaptchaClose(param1:Boolean, param2:String, param3:String) : void
{
_captchaPopup.destroy();
_captchaPopup = null;
if(param3 != null && param3 != "")
{
_captchaQuestion = param2;
_chosenCaptchaAnswer = param3;
}
GameRedemptionXtCommManager.captchaToShowData = null;
}
}
}
+6 -2
View File
@@ -438,6 +438,7 @@ package gui
var _loc6_:int = 0;
var _loc9_:int = 0;
var _loc7_:int = 0;
var _loc17_:int = 0;
while(_popup.itemBlock.numChildren > 1)
{
_popup.itemBlock.removeChildAt(_popup.itemBlock.numChildren - 1);
@@ -627,7 +628,9 @@ package gui
_itemDenWindows = _currItemWindow;
}
_popup.searchBar.mouse.searchTxt.text = "";
_currItemWindow.init(_popup.itemBlock.width,_popup.itemBlock.height,2,_loc11_,3,4,12,2,2,0,2 * 0.5,ItemWindowOriginal,_loc3_,"icon",0,{
// Expanded Inventory: more, smaller items a row (AJClient.inventoryColumns)
_loc17_ = AJClient.inventoryColumns();
_currItemWindow.init(_popup.itemBlock.width,_popup.itemBlock.height,2,_loc11_,_loc17_,4,_loc17_ * 4,2,2,0,2 * 0.5,ItemWindowOriginal,_loc3_,"icon",0,{
"mouseDown":winMouseDown,
"mouseOver":winMouseOver,
"mouseOut":winMouseOut
@@ -635,7 +638,8 @@ package gui
"giftItemIdx":_giftItemIdx,
"isECard":_type == 1,
"isChoosingForTradeList":_type == 0 || _type == 3,
"indexArray":_loc5_
"indexArray":_loc5_,
"itemScale":3 / _loc17_
},onListLoaded);
}
else
+9 -91
View File
@@ -15,13 +15,10 @@ package gui
import den.DenStateItem;
import den.DenXtCommManager;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.geom.Point;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.Timer;
import gui.itemWindows.ItemWindowOriginal;
import localization.LocalizationManager;
@@ -142,8 +139,6 @@ package gui
private var _privacyId:int;
private var _itemSetEvent:DenItemHolderEvent;
private var _layerControls:Sprite;
public function DenEditor()
{
@@ -162,7 +157,6 @@ package gui
_roomMgr = RoomManagerWorld.instance;
_denItemHolder = _roomMgr.denItemHolder;
_guiLayer.addChild(_denEditor);
createLayerControls();
initAssetVisibility();
setupPlayerItems();
DenXtCommManager.denEditorDIResponseCallback = diResponseCallback;
@@ -176,7 +170,6 @@ package gui
_denItemHolder.removeEventListener("OnItemRemoved",onDenItemRemoved);
_denItemHolder.removeEventListener("OnSaveState",onDenSaveState);
removeListeners();
destroyLayerControls();
_guiLayer.removeChild(_denEditor);
if(_denLockPopup)
{
@@ -242,14 +235,8 @@ package gui
public function updateSwitchRecycleBtnVisibility() : void
{
if(!_denEditor.switchDenBtn.visible)
{
if(gMainFrame.userInfo.numLogins >= 2 || gMainFrame.userInfo.userVarCache.getUserVarValueById(3) > 1)
{
_denEditor.switchDenBtn.visible = true;
_denEditor.recycleBtn.visible = true;
}
}
_denEditor.switchDenBtn.visible = true;
_denEditor.recycleBtn.visible = true;
}
public function clearItemWindows() : void
@@ -440,11 +427,11 @@ package gui
{
_denEditor.petBtnDn.visible = false;
}
if(gMainFrame.userInfo.numLogins < 2 && gMainFrame.userInfo.userVarCache.getUserVarValueById(3) <= 1)
{
_denEditor.switchDenBtn.visible = false;
_denEditor.recycleBtn.visible = false;
}
// the switch den and recycle buttons are not kept from a new
// player any more: the game hid them before a second login (or a
// den tutorial var), and players found them gone
_denEditor.switchDenBtn.visible = true;
_denEditor.recycleBtn.visible = true;
_denEditor.denAudioPopup.visible = false;
_denEditor.itemBlock.glowCont.glow.visible = false;
_denEditor.lockBtn.denLock.initToolTip(_guiLayer,LocalizationManager.translateIdOnly(14639),900 * 0.5,105);
@@ -697,7 +684,8 @@ package gui
{
_denEditor.itemBlock.itemBlock.addChild(_itemWindow);
}
if(_numItems <= 10 + 1)
// ten to a page: with eleven the last could not be scrolled to
if(_numItems <= 10)
{
_denEditor.lArrowBtn.activateGrayState(true);
_denEditor.rArrowBtn.activateGrayState(true);
@@ -1203,76 +1191,6 @@ package gui
_roomMgr.spawnNewDenItem(_loc3_);
}
// Small controls added at runtime so every den item can be stacked
// deliberately, instead of relying solely on where its feet land.
private function createLayerControls() : void
{
_layerControls = new Sprite();
_layerControls.x = _denEditor.width - 258;
_layerControls.y = 12;
_layerControls.addChild(makeLayerLabel("Selected item layer",0,0,230,22,13,16774041));
addLayerButton("Send behind",0,onSendBehind);
addLayerButton("Bring on top",116,onBringOnTop);
addLayerButton("Use natural depth",0,onResetLayer,62,230,30);
_denEditor.addChild(_layerControls);
}
private function addLayerButton(param1:String, param2:Number, param3:Function, param4:Number = 26, param5:Number = 110, param6:Number = 30) : void
{
var _loc6_:Sprite = new Sprite();
_loc6_.x = param2;
_loc6_.y = param4;
_loc6_.buttonMode = true;
_loc6_.mouseChildren = false;
_loc6_.graphics.beginFill(5986842,0.96);
_loc6_.graphics.drawRoundRect(0,0,param5,param6,8,8);
_loc6_.graphics.endFill();
_loc6_.addChild(makeLayerLabel(param1,0,5,param5,param6 - 5,12,16777215));
_loc6_.addEventListener("mouseDown",param3,false,0,true);
_layerControls.addChild(_loc6_);
}
private function makeLayerLabel(param1:String, param2:Number, param3:Number, param4:Number, param5:Number, param6:int, param7:uint) : TextField
{
var _loc8_:TextField = new TextField();
_loc8_.x = param2;
_loc8_.y = param3;
_loc8_.width = param4;
_loc8_.height = param5;
_loc8_.selectable = false;
_loc8_.mouseEnabled = false;
_loc8_.defaultTextFormat = new TextFormat("Arial",param6,param7,true,null,null,null,null,"center");
_loc8_.text = param1;
return _loc8_;
}
private function onSendBehind(param1:MouseEvent) : void
{
param1.stopImmediatePropagation();
_denItemHolder.sendSelectedBehind();
}
private function onBringOnTop(param1:MouseEvent) : void
{
param1.stopImmediatePropagation();
_denItemHolder.bringSelectedToFront();
}
private function onResetLayer(param1:MouseEvent) : void
{
param1.stopImmediatePropagation();
_denItemHolder.resetSelectedStacking();
}
private function destroyLayerControls() : void
{
if(_layerControls && _layerControls.parent)
{
_layerControls.parent.removeChild(_layerControls);
}
_layerControls = null;
}
private function onClose(param1:MouseEvent) : void
{
SBTracker.pop();
+49 -2
View File
@@ -3,6 +3,7 @@ package loader
import Enums.DenItemDef;
import avatar.AvatarManager;
import avatar.MannequinData;
import com.sbi.graphics.PaletteHelper;
import com.sbi.loader.FileServerEvent;
import den.DenItem;
import den.DenStateItem;
@@ -13,6 +14,7 @@ package loader
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filters.ColorMatrixFilter;
import pet.PetItem;
import pet.PetManager;
@@ -467,7 +469,7 @@ package loader
{
_version = getVersions()[0];
}
_loader.content["setVersion"](param1);
_loader.content["setVersion"](artVersion(param1));
}
else if(_loader.content.hasOwnProperty("pet"))
{
@@ -483,6 +485,50 @@ package loader
}
}
}
applyTint();
}
// a den item's version (the server's lib/admin.js): the art's own
// variant in the low 8 bits, and above them 1 + the number of a custom
// colour entry (PaletteHelper.customColors, [rgb, strength 1-100, 0,
// 0]) the whole item is tinted with. the art is only ever given its
// variant.
private static const CUSTOM_BASE:uint = 0xFD000000;
private function artVersion(param1:int) : int
{
return param1 < 0 ? param1 : param1 & 0xFF;
}
private function applyTint() : void
{
if(!_loader || !_loader.content || _loader.content.hasOwnProperty("pet"))
{
return;
}
var _loc1_:int = _version > 0 ? _version >> 8 & 0x7FFFFF : 0;
var _loc2_:Array = _loc1_ > 0 ? PaletteHelper.customColors[uint(CUSTOM_BASE + _loc1_ - 1)] : null;
_loader.filters = _loc2_ != null ? [new ColorMatrixFilter(tintMatrix(uint(_loc2_[0]),Math.min(100,Math.max(1,_loc2_[1])) / 100))] : [];
}
// the item in shades of `param1`, `param2` of the way (0-1): each
// pixel's brightness, times the colour (made as bright as white would
// be, up to twice), mixed with the pixel as it was.
private static function tintMatrix(param1:uint, param2:Number) : Array
{
var _loc3_:Array = [(param1 >> 16 & 0xFF) / 255,(param1 >> 8 & 0xFF) / 255,(param1 & 0xFF) / 255];
var _loc4_:Number = 0.299 * _loc3_[0] + 0.587 * _loc3_[1] + 0.114 * _loc3_[2];
var _loc5_:Number = Math.min(2,1 / Math.max(0.001,_loc4_));
var _loc6_:Array = [];
var _loc7_:int = 0;
while(_loc7_ < 3)
{
var _loc8_:Number = _loc3_[_loc7_] * _loc5_ * param2;
_loc6_.push(0.299 * _loc8_ + (_loc7_ == 0 ? 1 - param2 : 0),0.587 * _loc8_ + (_loc7_ == 1 ? 1 - param2 : 0),0.114 * _loc8_ + (_loc7_ == 2 ? 1 - param2 : 0),0,0);
_loc7_++;
}
_loc6_.push(0,0,0,1,0);
return _loc6_;
}
public function rebuildMannequinView() : void
@@ -567,7 +613,7 @@ package loader
}
if(_loader.content.hasOwnProperty("setVersion") && _version >= 0)
{
MovieClip(_loader.content).setVersion(_version);
MovieClip(_loader.content).setVersion(artVersion(_version));
}
else if(_loader.content.hasOwnProperty("pet"))
{
@@ -582,6 +628,7 @@ package loader
}
}
}
applyTint();
if(MovieClip(_loader.content).isMoveToDisabled)
{
_loader.name = "moveToDisabled";
+13 -1
View File
@@ -391,12 +391,19 @@ package den
}
_loc26_ = int(param1[_loc23_++]);
_loc18_.init(_loc28_,_loc31_,_loc32_,_loc24_,0,null,_loc14_,_loc33_,"",_loc17_,_loc30_,_loc4_,_loc26_);
_loc6_.setDenItem(_loc21_,_loc18_);
// pushed, not set at its place: one skipped left a hole, and
// the inventory's windows scrolled over an empty one
_loc6_.pushDenItem(_loc18_);
if(_loc18_.minigameDefId > 0 && !MinigameManager.minigameInfoCache.getMinigameInfo(_loc18_.minigameDefId))
{
_loc20_.push(_loc18_.minigameDefId);
}
}
else
{
// its last field (the den shop's), read past as above
_loc23_++;
}
_loc21_++;
}
_loc6_.getCoreArray().sortOn("invIdx",0x10 | 2);
@@ -846,6 +853,11 @@ package den
_loc19_ = getDenItemDef(_loc27_);
if(!_loc19_)
{
// the rest of its fields, read past: left there, every item
// after it was read from the wrong place (lib/dens.js
// sendDenState: placed, x, y, version, flip, link, image,
// creator id, creator uuid, eco state)
_loc20_ += 10;
_loc9_.setDenStateItem(_loc21_,new DenStateItem(0,_loc38_,0,0,0,0,0,0,0,0,0,0,0,0,0,"",0,"",0,0,"","",-1,"",false,null,0,0,null,null,2));
}
else
+318
View File
@@ -0,0 +1,318 @@
package ecard
{
import buddy.BuddyManager;
import com.sbi.client.SFEvent;
import com.sbi.popup.SBOkPopup;
import gui.DarkenManager;
import gui.GuiManager;
import gui.SafeChatManager;
import localization.LocalizationManager;
public class ECardXtCommManager
{
private static var _requestCallback:Function;
private static var _readResponseCallback:Function;
private static var _sendResponseCallback:Function;
private static var _privacyResponseCallback:Function;
private static var _giftResponseCallback:Function;
private static var _giftRequestCallbackQueue:Object;
public static var _deleteResponseCallback:Function;
private static var NUM_JAGS_PER_NON_BUDDY_PER_SESSION:int = 5;
private static var NUM_JAGS_PER_BUDDY_PER_SESSION:int = 25;
private static var _jaggedPlayers:Object;
private static var _privacySettingId:int;
public function ECardXtCommManager()
{
super();
}
public static function init() : void
{
_jaggedPlayers = {};
_giftRequestCallbackQueue = {};
}
public static function sendECardListRequest(param1:Function = null) : void
{
var _loc2_:int = 0;
if(param1 != null)
{
_loc2_ = 1;
_requestCallback = param1;
}
gMainFrame.server.setXtObject_Str("el",[_loc2_]);
}
public static function sendECardReadRequest(param1:int, param2:Function = null) : void
{
if(!gMainFrame.clientInfo.invisMode)
{
if(param2 != null)
{
_readResponseCallback = param2;
}
DarkenManager.showLoadingSpiral(true);
gMainFrame.server.setXtObject_Str("er",[param1]);
}
}
public static function sendECardSendRequest(param1:String, param2:String, param3:int, param4:int, param5:int, param6:String, param7:int, param8:int, param9:int, param10:Function = null) : Boolean
{
if(_jaggedPlayers[param1] == null)
{
_jaggedPlayers[param1] = 0;
}
var _loc11_:int = BuddyManager.isBuddy(param1) ? NUM_JAGS_PER_BUDDY_PER_SESSION : NUM_JAGS_PER_NON_BUDDY_PER_SESSION;
// Moderators need to be able to send follow-up cards while helping
// players, so do not apply the local per-recipient session cap.
if(gMainFrame.userInfo.isModerator || _jaggedPlayers[param1] < _loc11_)
{
_jaggedPlayers[param1]++;
if(param10 != null)
{
_sendResponseCallback = param10;
}
gMainFrame.server.setXtObject_Str("es",[param1,param3,param4,param5,param6,param7,param8,param9]);
return true;
}
DarkenManager.showLoadingSpiral(false);
new SBOkPopup(GuiManager.guiLayer,LocalizationManager.translateIdAndInsertOnly(14691,param2));
return false;
}
public static function sendECardDeleteRequest(param1:int, param2:Function = null) : void
{
if(param2 != null)
{
_deleteResponseCallback = param2;
}
DarkenManager.showLoadingSpiral(true);
gMainFrame.server.setXtObject_Str("ed",[param1]);
}
public static function sendECardBuddyRequest(param1:int, param2:Boolean) : void
{
gMainFrame.server.setXtObject_Str("eb",[param1,param2 ? 1 : 0]);
}
public static function sendECardAcceptDiscardGiftRequest(param1:int, param2:Boolean, param3:Function, param4:int = -1, param5:ECard = null) : void
{
if(!gMainFrame.clientInfo.invisMode)
{
if(param3 != null)
{
_giftResponseCallback = param3;
}
_giftRequestCallbackQueue[param1] = param5;
gMainFrame.server.setXtObject_Str("eg",param4 >= 0 ? [param1,param2 ? 1 : 0,param4] : [param1,param2 ? 1 : 0]);
}
else if(param3 != null)
{
param3(0,true,param5);
}
}
public static function sendECardClearCache() : void
{
gMainFrame.server.setXtObject_Str("ec",[]);
}
public static function sendECardPrivacySettingUpdateRequest(param1:int, param2:Function) : void
{
DarkenManager.showLoadingSpiral(true);
_privacyResponseCallback = param2;
_privacySettingId = param1;
gMainFrame.server.setXtObject_Str("ei",[param1]);
}
public static function handleXtReply(param1:SFEvent) : void
{
var _loc2_:Object = param1.obj;
DarkenManager.showLoadingSpiral(false);
switch(_loc2_[0])
{
case "el":
eCardListResponse(_loc2_);
break;
case "er":
eCardReadResponse(_loc2_);
break;
case "ed":
eCardDeleteResponse(_loc2_);
break;
case "es":
eCardSendResponse(_loc2_);
break;
case "eg":
eCardGiftResponse(_loc2_);
break;
case "eb":
eCardBuddyResponse(_loc2_);
break;
case "ep":
eCardPushHandler(_loc2_);
break;
case "eu":
eCardUpdateHandler(_loc2_);
break;
case "ei":
eCardIsolationHandler(_loc2_);
break;
default:
throw new Error("ECardXtCommManager: Received illegal cmd: " + _loc2_[0]);
}
}
private static function eCardListResponse(param1:Object) : void
{
var _loc7_:ECard = null;
var _loc5_:int = 0;
if(!SafeChatManager.hasLoadedLists)
{
SafeChatManager.safeChatStringForCode(eCardListResponse,[param1],"",1);
return;
}
var _loc2_:int = int(param1[2]);
var _loc3_:Array = new Array(_loc2_);
if(_loc2_ == -1)
{
_loc2_ = 0;
}
var _loc4_:int = 0;
var _loc6_:int = 3;
_loc5_ = 0;
while(_loc5_ < _loc2_)
{
_loc7_ = new ECard();
_loc7_.init(int(param1[_loc6_++]),param1[_loc6_++],int(param1[_loc6_++]),int(param1[_loc6_++]),param1[_loc6_++] == "1",param1[_loc6_++],int(param1[_loc6_++]),int(param1[_loc6_++]),uint(param1[_loc6_++]),param1[_loc6_++],int(param1[_loc6_++]),int(param1[_loc6_++]),int(param1[_loc6_++]),int(param1[_loc6_++]),int(param1[_loc6_++]),param1[_loc6_++],param1[_loc6_++]);
setGiftName(_loc7_);
_loc3_[_loc2_ - 1 - _loc5_] = _loc7_;
if(!_loc7_.isRead)
{
_loc4_++;
}
_loc5_++;
}
ECardManager.processECardList(_loc3_,_loc4_);
if(_requestCallback != null)
{
_requestCallback(_loc3_);
_requestCallback = null;
}
}
private static function setGiftName(param1:ECard) : void
{
if(param1.msg.match("(^[0-9]{1,2},[0-9]{1,2}$)|(^[0-9]{1,2}$)"))
{
param1.msg = SafeChatManager.safeChatStringForCode(null,null,param1.msg,1);
}
if(param1.type == 4)
{
param1.giftName = LocalizationManager.translateIdAndInsertOnly(param1.giftName == "1" ? 11114 : 11097,Utility.convertNumberToString(int(param1.giftName)));
}
else if(param1.type == 9)
{
param1.giftName = LocalizationManager.translateIdAndInsertOnly(param1.giftName == "1" ? 11116 : 11103,Utility.convertNumberToString(int(param1.giftName)));
}
else if(param1.type == 5)
{
param1.giftName = LocalizationManager.translateIdAndInsertOnly(15000,LocalizationManager.translateIdOnly(int(param1.giftName)));
}
else
{
param1.giftName = LocalizationManager.translateIdOnly(int(param1.giftName));
}
}
private static function eCardReadResponse(param1:Object) : void
{
if(_readResponseCallback != null)
{
_readResponseCallback(int(param1[2]),param1[3] == "1");
}
}
private static function eCardDeleteResponse(param1:Object) : void
{
var _loc2_:int = 0;
var _loc6_:Boolean = param1[2] == "1" ? true : false;
var _loc4_:int = int(param1[3]);
var _loc3_:int = 4;
var _loc5_:Array = new Array(_loc4_);
_loc2_ = 0;
while(_loc2_ < _loc4_)
{
_loc5_[_loc2_] = param1[_loc3_++];
_loc2_++;
}
if(_deleteResponseCallback != null)
{
_deleteResponseCallback(_loc5_,_loc6_);
}
}
private static function eCardSendResponse(param1:Object) : void
{
if(_sendResponseCallback != null)
{
_sendResponseCallback(param1[2]);
}
}
private static function eCardGiftResponse(param1:Object) : void
{
var _loc2_:ECard = null;
if(_giftResponseCallback != null)
{
_loc2_ = _giftRequestCallbackQueue[int(param1[2])];
delete _giftRequestCallbackQueue[int(param1[2])];
_giftResponseCallback(int(param1[2]),param1[3] == "1",_loc2_);
}
}
private static function eCardBuddyResponse(param1:Object) : void
{
if(param1[2] == -1)
{
DarkenManager.showLoadingSpiral(false);
new SBOkPopup(GuiManager.guiLayer,LocalizationManager.translateIdOnly(14692));
}
}
private static function eCardIsolationHandler(param1:Object) : void
{
DarkenManager.showLoadingSpiral(false);
var _loc2_:Boolean = param1[2] == "1";
if(_loc2_)
{
gMainFrame.userInfo.eCardPrivacySettings = _privacySettingId;
}
if(_privacyResponseCallback != null)
{
_privacyResponseCallback(_loc2_,_privacySettingId);
_privacyResponseCallback = null;
}
}
private static function eCardPushHandler(param1:Object) : void
{
if(!SafeChatManager.hasLoadedLists)
{
SafeChatManager.safeChatStringForCode(eCardPushHandler,[param1],"",1);
return;
}
var _loc2_:ECard = new ECard();
var _loc3_:int = 2;
_loc2_.init(int(param1[_loc3_++]),param1[_loc3_++],int(param1[_loc3_++]),int(param1[_loc3_++]),param1[_loc3_++] == "1",param1[_loc3_++],int(param1[_loc3_++]),int(param1[_loc3_++]),uint(param1[_loc3_++]),param1[_loc3_++],int(param1[_loc3_++]),int(param1[_loc3_++]),int(param1[_loc3_++]),int(param1[_loc3_++]),int(param1[_loc3_++]),param1[_loc3_++],param1[_loc3_++]);
setGiftName(_loc2_);
ECardManager.processECardPush(_loc2_);
}
private static function eCardUpdateHandler(param1:Object) : void
{
ECardManager.processECardUpdate(param1[2],param1[3]);
}
}
}
+592
View File
@@ -0,0 +1,592 @@
package gui
{
import achievement.AchievementXtCommManager;
import com.sbi.analytics.SBTracker;
import com.sbi.client.KeepAlive;
import com.sbi.popup.SBStandardTitlePopup;
import flash.display.DisplayObjectContainer;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.external.ExternalInterface;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.utils.ByteArray;
import loader.FeedbackDefHelper;
import loader.MediaHelper;
import localization.LocalizationManager;
public class FeedbackManager
{
public static const TYPE_ASK_BRADY:int = 1;
public static const TYPE_ITEMS:int = 2;
public static const TYPE_HOWL:int = 3;
public static const TYPE_WORK:int = 4;
public static const TYPE_GENERIC:int = 5;
public static const TYPE_FLAGS:int = 6;
public static const TYPE_PETS:int = 7;
public static const TYPE_PARTIES:int = 8;
public static const TYPE_EPIC_ITEMS:int = 9;
public static const TYPE_ARCADE:int = 10;
public static const TYPE_ASK_TIERNEY:int = 11;
public static const TYPE_DONATION:int = 12;
public static const TYPE_CARNIVAL:int = 13;
public static const TYPE_ARTSTUDIO:int = 14;
public static const TYPE_JAMSESSION:int = 15;
public static const TYPE_DIAMOND:int = 16;
public static const TYPE_ADVENTURE:int = 17;
public static const TYPE_DICTIONARY:int = 18;
public static const TYPE_CHAT_EXPERIENCE:int = 19;
public static const TYPE_MASTERPIECES:int = 20;
public static const TYPE_ASK_CAMI:int = 21;
public static const TYPE_ASK_GABBY:int = 22;
private static const TAB_MEDIA_ID:int = 153;
private static const POPUP_MEDIA_ID:int = 457;
private static const TAB_FRAME_LABEL:String = "answer";
private static var _feedbackDefCache:Array;
private static var _feedbackLocs:Array;
private static var _feedbackDefHelpers:Array;
private static var _tabMediaHelper:MediaHelper;
private static var _tabTemplate:MovieClip;
private static var _popupMediaHelper:MediaHelper;
private static var _popup:MovieClip;
private static var _imageUploader:UserImageUpload;
private static var _guiLayer:DisplayLayer;
private static var _worldLayer:DisplayLayer;
private static var _secondaryType:int;
public function FeedbackManager()
{
super();
}
public static function init(param1:DisplayLayer, param2:DisplayLayer) : void
{
_feedbackDefCache = [];
_guiLayer = param1;
_worldLayer = param2;
_popupMediaHelper = new MediaHelper();
_tabMediaHelper = new MediaHelper();
_tabMediaHelper.init(153,mediaHelperCallback,true);
_imageUploader = new UserImageUpload();
_imageUploader.init();
if(ExternalInterface.available)
{
ExternalInterface.addCallback("openFeedback",handleOpenDefaultFeedback);
}
}
public static function setUpOrbs(param1:Array, param2:Array) : void
{
var _loc4_:int = 0;
var _loc3_:Object = null;
var _loc5_:FeedbackDefHelper = null;
_feedbackLocs = param2;
_feedbackDefHelpers = [];
_loc4_ = 0;
while(_loc4_ < param1.length)
{
if(param1[_loc4_] == 0)
{
DarkenManager.showLoadingSpiral(false);
throw new Error("Id == 0");
}
_loc3_ = _feedbackDefCache[param1[_loc4_]];
if(!_loc3_)
{
_loc5_ = new FeedbackDefHelper();
_loc5_.init(param1[_loc4_],onDefReceived);
_feedbackDefHelpers[param1[_loc4_]] = _loc5_;
}
else
{
setUpOrb(_loc3_);
}
_loc4_++;
}
}
public static function openFeedbackPopup(param1:int) : void
{
var _loc3_:FeedbackDefHelper = null;
if(param1 == 0)
{
DarkenManager.showLoadingSpiral(false);
throw new Error("Id == 0");
}
DarkenManager.showLoadingSpiral(true);
if(!_feedbackDefHelpers)
{
_feedbackDefHelpers = [];
}
var _loc2_:Object = _feedbackDefCache[param1];
if(!_loc2_)
{
_loc3_ = new FeedbackDefHelper();
_loc3_.init(param1,onDefReceived);
_feedbackDefHelpers[param1] = _loc3_;
}
else
{
displayFeedbackPopup(_loc2_);
}
}
private static function handleOpenDefaultFeedback() : void
{
openFeedbackPopup(5);
}
private static function onDefReceived(param1:FeedbackDefHelper) : void
{
var _loc5_:Object = param1.def;
var _loc4_:String = LocalizationManager.translateIdOnly(int(_loc5_.defaultStrRef));
var _loc3_:RegExp = /\r\n/g;
_loc4_ = _loc4_.replace(_loc3_,"\n");
_loc3_ = /\r/g;
_loc4_ = _loc4_.replace(_loc3_,"\n");
var _loc2_:Object = {
"id":int(_loc5_.id),
"titleTxt":LocalizationManager.translateIdOnly(int(_loc5_.titleStrRef)),
"defaultTxt":_loc4_,
"thanksTxt":LocalizationManager.translateIdOnly(int(_loc5_.thankStrRef)),
"allowImg":Boolean(int(_loc5_.bAcceptImage)),
"userVarId":int(_loc5_.userVarRef),
"bitIdx":int(_loc5_.bitIndex)
};
_feedbackDefCache[_loc2_.id] = _loc2_;
_feedbackDefHelpers[_loc2_.id] = null;
_loc2_.seen = gMainFrame.userInfo.userVarCache.isBitSet(_loc2_.userVarId,_loc2_.bitIdx);
if(_loc2_.id == 1 || _loc2_.id == 11 || _loc2_.id == 3 || _loc2_.id == 4 || _loc2_.id == 5 || _loc2_.id == 18 || _loc2_.id == 19 || _loc2_.id == 21 || _loc2_.id == 22)
{
displayFeedbackPopup(_loc2_);
}
else
{
setUpOrb(_loc2_);
}
}
private static function setUpOrb(param1:Object) : void
{
var _loc3_:MovieClip = null;
var _loc2_:int = 0;
if(_tabTemplate)
{
_loc3_ = new _tabTemplate.constructor();
_loc3_.def = param1;
_loc2_ = int(_loc3_.id = int(param1.id));
_loc3_.x = _feedbackLocs[_loc2_].x;
_loc3_.y = _feedbackLocs[_loc2_].y;
if(param1.seen)
{
_loc3_.gotoAndPlay("answerDim");
}
else
{
_loc3_.gotoAndPlay("answer");
}
_loc3_.addEventListener("mouseDown",onTabMouseDown,false,0,true);
_worldLayer.addChild(_loc3_);
}
}
private static function mediaHelperCallback(param1:MovieClip) : void
{
var _loc2_:int = 0;
if(param1)
{
if(param1.mediaHelper.id == 153)
{
_loc2_ = int(param1.mediaHelper.id);
_tabTemplate = MovieClip(param1.getChildAt(0));
_tabMediaHelper.destroy();
_tabMediaHelper = null;
}
else if(param1.mediaHelper.id == 457)
{
_popup = param1;
_popupMediaHelper.destroy();
_popupMediaHelper = null;
_popup.x = 900 * 0.5;
_popup.y = 550 * 0.5;
_popup.parent.x = _popup.x;
_popup.parent.y = _popup.y;
displayFeedbackPopup(param1.passback);
}
}
}
private static function onTabMouseDown(param1:MouseEvent) : void
{
param1.stopPropagation();
var _loc2_:MovieClip = MovieClip(param1.currentTarget);
var _loc3_:Object = _loc2_.def;
SBTracker.push();
SBTracker.trackPageview("/game/play/popup/feedback/" + _loc3_.id);
DarkenManager.showLoadingSpiral(true);
if(!_loc3_.seen)
{
_loc2_.gotoAndPlay("answerDim");
}
displayFeedbackPopup(_loc3_);
}
public static function displayFeedbackPopup(param1:Object) : void
{
var _loc3_:Array = null;
var _loc2_:int = int(param1.id);
if(!_popup)
{
_popupMediaHelper.init(457,mediaHelperCallback,param1);
return;
}
if(!param1.seen)
{
param1.seen = true;
AchievementXtCommManager.requestSetUserVar(param1.userVarId,param1.bitIdx);
}
removePopup();
_popup.gotoAndStop(frameLabelForType(_loc2_));
_popup.submitBtn.addEventListener("mouseDown",onMouseDown,false,0,true);
_popup.bx.addEventListener("mouseDown",onMouseDown,false,0,true);
_popup.addEventListener("mouseDown",onMouseDown,false,0,true);
_popup.txt.addEventListener("mouseDown",onMouseDown,false,0,true);
_popup.def = param1;
if(_popup["descTxt"])
{
_loc3_ = param1.defaultTxt.split("|");
LocalizationManager.updateToFit(_popup.descTxt,_loc3_[0]);
LocalizationManager.updateToFit(_popup.txt,_loc3_[1]);
}
else
{
LocalizationManager.updateToFit(_popup.txt,param1.defaultTxt);
}
_popup.defaultTxt = _popup.txt.text;
_popup.titleTxt.text = param1.titleTxt;
if(param1.allowImg)
{
_popup.addFileBtn.visible = true;
_imageUploader.setUploadBtn(_popup.addFileBtn);
_popup.removeFileBtn.addEventListener("mouseDown",onRemoveFileBtn,false,0,true);
}
else
{
if(_popup.addFileBtn)
{
_popup.addFileBtn.visible = false;
}
if(_popup.removeFileBtn)
{
_popup.removeFileBtn.visible = false;
}
}
_popup.txt.maxChars = maxCharsForType(_loc2_);
if(_loc2_ == 18)
{
_popup.txt.restrict = "^ ";
}
else
{
_popup.txt.restrict = null;
}
_popup.visible = true;
_popup.clickedTextBox = false;
KeepAlive.startKATimer(_popup);
DarkenManager.showLoadingSpiral(false);
DarkenManager.darken(DisplayObjectContainer(_popup));
_guiLayer.addChild(DisplayObjectContainer(_popup));
}
private static function frameLabelForType(param1:int) : int
{
switch(param1)
{
case 1:
return 1;
case 3:
case 19:
return 2;
case 4:
case 2:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 13:
case 15:
case 16:
case 17:
break;
case 11:
return 4;
case 18:
return 6;
case 21:
return 7;
case 22:
return 8;
default:
return 1;
}
return 3;
}
private static function maxCharsForType(param1:int) : int
{
switch(param1)
{
case 1:
case 11:
case 21:
case 22:
return 150;
case 3:
return 50;
case 4:
return 3000;
case 2:
case 9:
case 16:
case 10:
case 17:
case 5:
return 300;
case 12:
case 8:
case 7:
case 15:
case 6:
case 13:
case 14:
break;
case 19:
return 200;
case 18:
return 25;
default:
return 1;
}
return 100;
}
private static function onRemoveFileBtn(param1:MouseEvent) : void
{
param1.stopPropagation();
_imageUploader.resetUploader();
_popup.addFileBtn.visible = true;
}
private static function onMouseDown(param1:MouseEvent) : void
{
var _loc3_:String = null;
var _loc2_:RegExp = null;
param1.stopPropagation();
if(param1.currentTarget == _popup)
{
return;
}
if(param1.currentTarget == _popup.txt)
{
if(!_popup.clickedTextBox)
{
_popup.txt.text = "";
_popup.clickedTextBox = true;
gMainFrame.stage.focus = _popup.txt;
_popup.txt.setSelection(0,0);
}
return;
}
if(param1.currentTarget.name == "submitBtn")
{
_loc3_ = _popup.txt.text;
_loc2_ = /\r\n/g;
_loc3_ = _loc3_.replace(_loc2_,"\n");
_loc2_ = /\r/g;
_loc3_ = _loc3_.replace(_loc2_,"\n");
if(_loc3_.length > 0 && _loc3_ != _popup.defaultTxt || _imageUploader.fileName != "")
{
if(_loc3_ == _popup.def.defaultTxt)
{
_loc3_ = _popup.txt.text = "";
}
setupRequest(_imageUploader,_loc3_,_popup.def.id,_secondaryType,onSendComplete,onSendError);
}
}
removePopup(param1.currentTarget.name == "bx");
}
private static function removePopup(param1:Boolean = true) : void
{
if(_popup)
{
_popup.removeEventListener("mouseDown",onMouseDown);
_popup.bx.removeEventListener("mouseDown",onMouseDown);
_popup.submitBtn.removeEventListener("mouseDown",onMouseDown);
_popup.txt.removeEventListener("mouseDown",onMouseDown);
if(_popup.def && _popup.def.allowImg)
{
_imageUploader.resetUploader();
_popup.addFileBtn.visible = true;
_popup.removeFileBtn.removeEventListener("mouseDown",onRemoveFileBtn);
}
DarkenManager.unDarken(_popup);
_popup.visible = false;
SBTracker.pop();
if(!param1)
{
new SBStandardTitlePopup(_guiLayer,_popup.def.thanksTxt);
}
KeepAlive.stopKATimer(_popup);
}
}
// feedback goes to this server's staff (lib/world.js xfb) over the
// game's own connection, which says who wrote it: it went to the
// official moderation server's "fb", which here answered nothing. a
// museum donation (type 12) is the gems themselves
// (ItemXtCommManager.requestDonateGems): nothing more goes. pictures
// are not taken.
public static function setupRequest(param1:UserImageUpload, param2:String, param3:int, param4:int, param5:Function, param6:Function) : void
{
var _loc7_:String = param2 != null ? param2.split("%").join("").replace(/[\r\n]+/g," ") : "";
if(param3 != 12 && _loc7_.replace(/\s+/g,"").length > 0)
{
gMainFrame.server.setXtObject_Str("xfb",[param3,_loc7_.substr(0,1000)]);
}
if(param5 != null)
{
param5(new Event("complete"));
}
}
public static function createPostData(param1:String, param2:ByteArray, param3:String, param4:Object = null) : ByteArray
{
var _loc5_:String = null;
var _loc7_:int = 0;
var _loc8_:ByteArray = new ByteArray();
_loc8_.endian = "bigEndian";
if(param4 == null)
{
param4 = {};
}
for(var _loc6_:String in param4)
{
writeBoundary(_loc8_,param3);
writeLineBreak(_loc8_);
_loc5_ = "Content-Disposition: form-data; name=\"" + _loc6_ + "\"";
_loc7_ = 0;
while(_loc7_ < _loc5_.length)
{
_loc8_.writeByte(_loc5_.charCodeAt(_loc7_));
_loc7_++;
}
writeLineBreak(_loc8_);
writeLineBreak(_loc8_);
_loc8_.writeUTFBytes(param4[_loc6_]);
writeLineBreak(_loc8_);
}
if(param2)
{
writeBoundary(_loc8_,param3);
writeLineBreak(_loc8_);
_loc5_ = "Content-Disposition: form-data; name=\"image\"; filename=\"" + param1 + "\"";
_loc7_ = 0;
while(_loc7_ < _loc5_.length)
{
_loc8_.writeByte(_loc5_.charCodeAt(_loc7_));
_loc7_++;
}
writeLineBreak(_loc8_);
_loc5_ = "Content-Type: image/jpeg";
_loc7_ = 0;
while(_loc7_ < _loc5_.length)
{
_loc8_.writeByte(_loc5_.charCodeAt(_loc7_));
_loc7_++;
}
writeLineBreak(_loc8_);
writeLineBreak(_loc8_);
_loc8_.writeBytes(param2,0,param2.length);
writeLineBreak(_loc8_);
}
writeBoundary(_loc8_,param3);
writeDoubleDash(_loc8_);
writeLineBreak(_loc8_);
return _loc8_;
}
private static function writeLineBreak(param1:ByteArray) : void
{
param1.writeShort(3338);
}
private static function writeDoubleDash(param1:ByteArray) : void
{
param1.writeShort(11565);
}
private static function writeBoundary(param1:ByteArray, param2:String) : void
{
var _loc3_:int = 0;
writeDoubleDash(param1);
_loc3_ = 0;
while(_loc3_ < param2.length)
{
param1.writeByte(param2.charCodeAt(_loc3_));
_loc3_++;
}
}
private static function onSendComplete(param1:Event) : void
{
trace("w00t!");
}
private static function onSendError(param1:Event) : void
{
trace("Argh! Error sending....");
}
}
}
+30 -1
View File
@@ -1,6 +1,7 @@
package gui
{
import collection.StreamDefCollection;
import flash.external.ExternalInterface;
import movie.MovieManager;
import quest.QuestManager;
import room.RoomManagerWorld;
@@ -50,10 +51,17 @@ package gui
var _loc4_:Boolean = false;
// the video lists came from the official server; this one answers
// them empty, and a player with nothing to play threw (#1009 in
// VideoPlayerOSMF.playNonStreaming)
// VideoPlayerOSMF.playNonStreaming). a video spot clicked opens the
// game page's video box instead (game.html ajVideoSpot), for a link
// of the player's own; the trade list's help plays a video of ours.
// a list the room plays by itself ("autoplay") opens nothing.
if(param2 == null || param2.length == 0)
{
DarkenManager.showLoadingSpiral(false);
if(param3 == null || param3.msg == null || String(param3.msg).indexOf("autoplay") == -1)
{
openVideoSpot(param1 == TRADE_HELP_LIST ? TRADE_HELP_VIDEO : "");
}
return;
}
if(param2.length > 1)
@@ -143,6 +151,27 @@ package gui
movieSelector.destroy();
movieSelector = null;
}
openVideoSpot("close");
}
// the trade list's "how to trade" video (AvatarEditor.onInfoBtnDown)
private static const TRADE_HELP_LIST:int = 22;
private static const TRADE_HELP_VIDEO:String = "dQw4w9WgXcQ";
// the game page's video box (game.html ajVideoSpot): a YouTube id to
// play, "" for a link of the player's choosing, "close" to put it away
public static function openVideoSpot(param1:String) : void
{
try
{
if(ExternalInterface.available)
{
ExternalInterface.call("ajVideoSpot",param1);
}
}
catch(e:Error)
{
}
}
public static function togglePlayPauseVideoPlayer(param1:Boolean) : void
+71 -11
View File
@@ -181,10 +181,6 @@ package gui
private static var _petInventory:PetInventory;
// A player's voluntary pet form. Party and quest pet forms remain
// room-wide and are still reported by isBeYourPetRoom().
private static var _personalPetMode:Boolean = false;
private static var _joeyPopup:MovieClip;
private static var _secondaryJoeyPopup:MovieClip;
@@ -274,6 +270,10 @@ package gui
private static var _namebarBadgeList:Array;
private static var _sharedObj:SharedObject;
private static var _customChatBubbles:Boolean = true;
private static var _chatBubbleAnimations:Boolean = true;
private static var _giftGemsMediaHelper:MediaHelper;
@@ -369,11 +369,15 @@ package gui
public static function setupSharedObject() : void
{
_sharedObj = null;
_customChatBubbles = true;
_chatBubbleAnimations = true;
if(gMainFrame.myFlashVarUserName != null)
{
try
{
_sharedObj = SharedObject.getLocal(gMainFrame.myFlashVarUserName);
_customChatBubbles = _sharedObj.data.customChatBubbles !== false;
_chatBubbleAnimations = _sharedObj.data.chatBubbleAnimations !== false;
if(_sharedObj.data.cursor == null || _sharedObj.data.cursor == "custom")
{
CursorManager.switchToCursor("custom_cursor");
@@ -463,6 +467,55 @@ package gui
{
return _sharedObj;
}
// A local accessibility/preference switch: players can keep their own
// saved style visible to others while rendering every bubble normally
// on this installation.
public static function customChatBubblesEnabled() : Boolean
{
return _customChatBubbles;
}
public static function setCustomChatBubblesEnabled(param1:Boolean) : void
{
_customChatBubbles = param1;
if(_sharedObj == null)
{
return;
}
_sharedObj.data.customChatBubbles = param1;
try
{
_sharedObj.flush();
}
catch(e:Error)
{
}
}
// the same, for custom bubbles' animations (pulse, shimmer, flow,
// rainbow): off, every bubble keeps its colours and stands still.
public static function chatBubbleAnimationsEnabled() : Boolean
{
return _chatBubbleAnimations;
}
public static function setChatBubbleAnimationsEnabled(param1:Boolean) : void
{
_chatBubbleAnimations = param1;
if(_sharedObj == null)
{
return;
}
_sharedObj.data.chatBubbleAnimations = param1;
try
{
_sharedObj.flush();
}
catch(e:Error)
{
}
}
public static function startFFM(param1:Boolean = false) : void
{
@@ -970,6 +1023,15 @@ package gui
public static function initMoviePlayer(param1:int, param2:StreamDefCollection, param3:Boolean = true, param4:int = 512, param5:int = 288) : void
{
// nothing to play (the official server's video lists are gone; a
// tutorial video that never came): the game page's video box
// instead, as GenericListGuiManager.launchMovies does.
if(param2 == null || param2.length == 0 || param2.getStreamDefItem(0) == null)
{
DarkenManager.showLoadingSpiral(false);
GenericListGuiManager.openVideoSpot("");
return;
}
if(_videoPlayer)
{
_videoPlayer.destroy();
@@ -2616,7 +2678,7 @@ package gui
{
mainHud.charWindow.charLayer.removeChildAt(0);
}
if(isBeYourPetRoom())
if(isPlayingAsPet())
{
_loc1_ = PetManager.myActivePet;
if(_loc1_)
@@ -2911,18 +2973,16 @@ package gui
return QuestManager.isBeYourPetQuest() || PartyManager.isBeYourPetParty();
}
// A player's own pet form: the party's and the quest's for everyone in
// the room, or the pet chooser's switch with a pet out.
public static function isPlayingAsPet() : Boolean
{
return _personalPetMode || isBeYourPetRoom();
return isBeYourPetRoom() || AJClient.petFormOn() && PetManager.myActivePet != null;
}
// the player's own avatar came into or out of its pet form
public static function setPersonalPetMode(param1:Boolean) : void
{
if(_personalPetMode == param1)
{
return;
}
_personalPetMode = param1;
if(mainHud)
{
showHudAvt();
+22 -1
View File
@@ -61,7 +61,11 @@ package gui.itemWindows
private var _hasSetState:Boolean;
private var _isSellShop:Boolean;
// smaller with Expanded Inventory on (AJClient.inventoryColumns): 3
// over the items a row, so a row is as wide as the game's three.
private var _itemScale:Number = 1;
public function ItemWindowOriginal(param1:Function, param2:Object, param3:String, param4:int, param5:Function = null, param6:Function = null, param7:Function = null, param8:Function = null, param9:Object = null)
{
var _loc11_:int = 0;
@@ -89,6 +93,10 @@ package gui.itemWindows
_loc11_ = int(param9.indexArray.length);
_loc10_ = int(_loc11_ - 1 >= param4 ? param9.indexArray[param4] : param4);
}
if(param9.itemScale > 0)
{
_itemScale = param9.itemScale;
}
}
super("itemWindow",param1,param2,param3,_loc10_,param5,param6,param7,param8,true);
}
@@ -576,6 +584,19 @@ package gui.itemWindows
override protected function onWindowLoadCallback() : void
{
// the generator spaces the windows by their width and height,
// which are sizeCont's (ItemWindowBase) and do not shrink with the
// window, so sizeCont is made as much smaller.
if(_itemScale != 1 && _window)
{
if(_window.hasOwnProperty("sizeCont") && _window.sizeCont)
{
_window.sizeCont.width *= _itemScale;
_window.sizeCont.height *= _itemScale;
}
this.scaleX = _itemScale;
this.scaleY = _itemScale;
}
if(_windowLoadedCallback != null)
{
resetVisibility();
File diff suppressed because it is too large. Load diff
+37 -14
View File
@@ -171,8 +171,10 @@ package com.sbi.graphics
private var _receivedData:Array;
// each requested image's place in _layers: items worn in the same
// slot are drawn in that order, the later over the earlier
// each requested image's places in _layers: different items can use
// the same art layer, so one image response can paint several pieces.
// Items worn in the same slot are drawn in their original order, the
// later over the earlier.
private var _order:Object;
private var _requestedIds:Set;
@@ -738,10 +740,16 @@ package com.sbi.graphics
param2.push(_loc4_);
if(param3)
{
param3[_loc4_] = _loc5_.c;
if(_order)
{
_order[_loc4_] = _loc6_;
if(!_order[_loc4_])
{
_order[_loc4_] = [];
}
_order[_loc4_].push({
"p":_loc6_,
"c":_loc5_.c
});
}
}
_loc6_++;
@@ -761,6 +769,8 @@ package com.sbi.graphics
{
var _loc2_:* = 0;
var _loc3_:int = 0;
var _loc8_:Array = null;
var _loc9_:Object = null;
if(_preloadRequestedIds.remove(param1.id))
{
if(_preloadRequestedIds.isEmpty())
@@ -778,18 +788,31 @@ package com.sbi.graphics
if(_requestedIds.remove(param1.id))
{
_loc3_ = param1.layer;
if(_loc3_ > 0)
{
_loc2_ = uint(_colors[param1.id]);
}
if(param1.success)
{
_receivedData.push({
"l":_loc3_,
"d":param1.imageData,
"c":_loc2_,
"p":(_order && _order.hasOwnProperty(param1.id) ? int(_order[param1.id]) : -1)
});
_loc8_ = _order && _order.hasOwnProperty(param1.id) ? _order[param1.id] as Array : null;
if(_loc8_ && _loc8_.length > 0)
{
for each(_loc9_ in _loc8_)
{
_receivedData.push({
"l":_loc3_,
"d":param1.imageData,
"c":uint(_loc9_.c),
"p":int(_loc9_.p)
});
}
}
else
{
// the animal's base has no entry in _order
_receivedData.push({
"l":_loc3_,
"d":param1.imageData,
"c":_loc2_,
"p":-1
});
}
}
if(_requestedIds.isEmpty())
{
+1000
View File
@@ -0,0 +1,1000 @@
package localization
{
import com.sbi.debug.DebugUtility;
import flash.events.Event;
import flash.text.TextField;
import flash.text.TextFormat;
public class LocalizationManager
{
public static var LANG_ENG:int = 0;
public static var LANG_SPA:int = 1;
public static var LANG_POR:int = 2;
public static var LANG_FRE:int = 3;
public static var LANG_DE:int = 4;
public static var LANG_BLANK:int = 5;
public static var accountLanguage:int;
public static const ADVENTURE_CONFIRMEXIT:int = 10683;
public static const NEW_JAMMER_USERNAME:int = 11098;
public static const GEM_CAPITALIZED:int = 11114;
public static const GEM_EXCLAMATION:int = 11433;
public static const TICKET_CAPITALIZED:int = 11115;
public static const DIAMOND_CAPITALIZED:int = 11116;
public static const CRYSTAL_CAPITALIZED:int = 11104;
public static const GEMS_CAPITALIZED:int = 11097;
public static const GEMS_EXCLAMATION:int = 11432;
public static const TICKETS_CAPITALIZED:int = 11102;
public static const DIAMONDS_CAPITALIZED:int = 11103;
public static const CRYSTALS_CAPITALIZED:int = 11117;
public static const MEMBERS:int = 11376;
public static const UNUSABLE_PASSWORDS:int = 21913;
private static var _staticLocalizations:Object;
private static var _preferredLocalizations:Object;
private static var _currentLanguage:int;
private static var _hasLocalizations:Boolean;
private static var _countryCode:String;
public function LocalizationManager()
{
super();
}
public static function setLocalizations(param1:Object, param2:Function) : void
{
_staticLocalizations = param1;
_hasLocalizations = true;
if(param2 != null)
{
param2();
}
}
public static function setPreferredLocalizations(param1:Object) : void
{
_preferredLocalizations = param1;
}
public static function getLanguageIdForLocale(param1:String) : int
{
var _loc2_:String = param1;
if(param1.indexOf("-") != -1)
{
_loc2_ = param1.substr(0,param1.indexOf("-"));
}
switch(_loc2_)
{
case "en":
case "eng":
return LANG_ENG;
case "es":
case "spa":
return LANG_SPA;
case "pt":
case "por":
return LANG_POR;
case "fr":
case "fra":
case "fre":
break;
case "de":
case "deu":
case "ger":
return LANG_DE;
default:
DebugUtility.debugTrace("WARNING - Unknown locale:" + param1 + " - returning -1");
return -1;
}
return LANG_FRE;
}
public static function get localeForSorting() : String
{
switch(_currentLanguage)
{
case LANG_ENG:
return "en-US";
case LANG_DE:
return "de-DE@collation=phonebook";
case LANG_FRE:
return "fr-FR";
case LANG_POR:
return "pt-BR";
case LANG_SPA:
return "es-ES";
default:
return "i-default";
}
}
public static function get localeForNumberFormatting() : String
{
switch(_currentLanguage)
{
case LANG_ENG:
return "en-US";
case LANG_DE:
return "de-DE";
case LANG_FRE:
return "fr-FR";
case LANG_POR:
return "pt-BR";
case LANG_SPA:
return "es-ES";
default:
return "i-default";
}
}
public static function set countryCode(param1:String) : void
{
_countryCode = param1;
}
public static function get hasLocalizations() : Boolean
{
return _hasLocalizations;
}
public static function set hasLocalizations(param1:Boolean) : void
{
_hasLocalizations = param1;
}
public static function get currentLanguage() : int
{
return _currentLanguage;
}
public static function set currentLanguage(param1:int) : void
{
_currentLanguage = param1;
}
public static function numberOfWordsInString() : int
{
var _loc4_:Array = null;
var _loc3_:int = 0;
var _loc2_:int = 0;
for each(var _loc1_:String in _staticLocalizations)
{
_loc4_ = _loc1_.split(" ");
_loc3_ = 0;
while(_loc3_ < _loc4_.length)
{
if(_loc4_[_loc3_] != "" && _loc4_[_loc3_] != " " && _loc4_[_loc3_] != "\n" && _loc4_[_loc3_] != "\r" && _loc4_[_loc3_] != "\r\n")
{
_loc2_++;
}
_loc3_++;
}
}
return _loc2_;
}
public static function onLocalizationEvent(param1:Event) : void
{
param1.stopPropagation();
findAllTextfields(param1.target);
}
public static function translateIdOnly(param1:int) : String
{
if(_staticLocalizations[param1])
{
return _staticLocalizations[param1];
}
return "";
}
public static function translatePreferredIdOnly(param1:int) : String
{
if(_preferredLocalizations[param1])
{
return _preferredLocalizations[param1];
}
return "";
}
public static function translateId(param1:TextField, param2:int, param3:Boolean = false, param4:Boolean = true) : void
{
var _loc5_:String = translateIdOnly(param2);
if(_loc5_ != "")
{
updateToFit(param1,_loc5_,param3,false,param4);
return;
}
throw new Error("Error translating string with id = " + param2);
}
public static function translateIdAndInsertOnly(param1:int, ... rest) : String
{
var _loc3_:Array = null;
var _loc5_:String = null;
var _loc6_:int = 0;
var _loc4_:String = translateIdOnly(param1);
if(_loc4_ != "" && rest.length > 0)
{
_loc3_ = _loc4_.split("%s");
if(_loc3_.length - 1 != rest.length)
{
DebugUtility.debugTrace("Num splits does not match num args. Id = " + param1 + " Num splits in translation = " + (_loc3_.length - 1) + " and args length = " + rest.length);
return "";
}
_loc5_ = "";
_loc6_ = 0;
while(_loc6_ < _loc3_.length)
{
if(_loc6_ < rest.length)
{
_loc5_ += _loc3_[_loc6_] + rest[_loc6_];
}
else
{
_loc5_ += _loc3_[_loc6_];
}
_loc6_++;
}
return _loc5_;
}
throw new Error("Error translating string with id = " + param1 + " and args length = " + rest.length);
}
public static function translateIdAndInsert(param1:TextField, param2:int, ... rest) : void
{
var _loc4_:Array = null;
var _loc6_:String = null;
var _loc7_:int = 0;
var _loc5_:String = translateIdOnly(param2);
if(_loc5_ != "" && rest.length > 0)
{
_loc4_ = _loc5_.split("%s");
if(_loc4_.length - 1 != rest.length)
{
throw new Error("Num splits does not match num args. Id = " + param2 + " Num splits in translation = " + (_loc4_.length - 1) + " and args length = " + rest.length);
}
_loc6_ = "";
_loc7_ = 0;
while(_loc7_ < _loc4_.length)
{
if(_loc7_ < rest.length)
{
_loc6_ += _loc4_[_loc7_] + rest[_loc7_];
}
else
{
_loc6_ += _loc4_[_loc7_];
}
_loc7_++;
}
updateToFit(param1,_loc6_);
return;
}
throw new Error("Error translating string with id = " + param2 + " and args length = " + rest.length);
}
public static function updateToFit(param1:TextField, param2:String, param3:Boolean = false, param4:Boolean = false, param5:Boolean = true, param6:Boolean = false) : void
{
var _loc8_:Array = null;
var _loc34_:String = null;
var _loc16_:String = null;
var _loc13_:Object = null;
var _loc40_:Number = NaN;
var _loc24_:TextFormat = null;
var _loc39_:Object = null;
var _loc31_:int = 0;
var _loc32_:Boolean = false;
var _loc7_:Number = NaN;
var _loc18_:Number = NaN;
var _loc25_:int = 0;
var _loc28_:String = null;
var _loc14_:String = null;
var _loc19_:Array = null;
var _loc10_:int = 0;
var _loc11_:int = 0;
var _loc21_:int = 0;
var _loc36_:int = 0;
var _loc35_:TextField = null;
var _loc33_:int = 0;
var _loc15_:String = null;
var _loc37_:String = null;
var _loc20_:int = 0;
var _loc22_:String = null;
var _loc17_:int = 0;
var _loc38_:Number = NaN;
var _loc29_:Number = NaN;
var _loc26_:Number = NaN;
if(param1 == null)
{
return;
}
if(param4)
{
_loc34_ = param2.match(/<a href='.*'>/g)[0];
_loc16_ = param2.match(/(?<=<u>).*?(?=<\/u>)/g)[0];
param1.text = _loc16_ != null ? _loc16_ : param2;
param1.htmlText = param2;
}
else if(param3)
{
_loc13_ = {};
_loc13_.array = _loc8_;
_loc13_.text = param2;
findSpecialTagPositions(_loc13_);
_loc8_ = _loc13_.array;
param2 = _loc13_.text;
param1.text = param2;
}
else
{
param1.text = param2;
}
var _loc9_:Boolean = param1.multiline && param2.split(/\s/g).length < 2;
if(_loc9_)
{
param1.multiline = false;
param1.wordWrap = false;
}
var _loc30_:TextFormat = param1.getTextFormat();
if(param1.text.charAt(0) == "#" || param1.name == "text01_chatHistory")
{
param5 = false;
}
if(param5)
{
if(param1.borderColor != 0 && !param1.border)
{
if(param1.borderColor > 16711680)
{
param1.y = 0 - ((2147483647 - param1.borderColor & 0xFFFF) + 1);
}
else
{
param1.y = param1.borderColor;
}
if(param1.y == 1)
{
param1.y = 0;
}
}
_loc40_ = param1.y;
param1.borderColor = _loc40_ != 0 ? _loc40_ : _loc40_ + 1;
}
if(param1.backgroundColor != 16777215)
{
_loc30_.size = param1.backgroundColor;
}
else if(_loc30_.size != null)
{
param1.backgroundColor = uint(_loc30_.size);
}
param1.styleSheet = null;
param1.setTextFormat(_loc30_);
var _loc23_:Number = param1.rotation;
if(_loc23_ != 0)
{
param1.rotation = 0;
}
var _loc12_:TextField = param1.parent[param1.name + "Multiline"];
var _loc27_:Boolean = hasBrokenWord(param1,param2);
if(param1.textWidth >= param1.width - 4 && param1.maxScrollV <= param1.scrollV || param1.textHeight > param1.height - 4 || _loc27_)
{
_loc7_ = param1.textHeight;
_loc18_ = Number(_loc30_.size);
if(!param1.multiline)
{
if(_loc12_)
{
_loc25_ = _loc18_ * 0.8;
}
if(param6)
{
_loc30_.size = _loc18_;
param1.setTextFormat(_loc30_);
updateToFit(param1,param2.substr(0,param2.length - 4) + "...",param3,param4,param5,param6);
return;
}
while(Number(_loc30_.size) > 5 && param1.textWidth > param1.width - 4)
{
_loc30_.size = Number(_loc30_.size) - 1;
param1.setTextFormat(_loc30_);
if(_loc12_ && Number(_loc30_.size) < _loc25_)
{
updateToFit(_loc12_,param2,param3,param4,param5);
param1.visible = false;
return;
}
if(param3 && _loc8_ != null)
{
_loc31_ = 0;
while(_loc31_ < _loc8_.length)
{
_loc39_ = _loc8_[_loc31_];
_loc24_ = new TextFormat("CCDigitalDelivery",_loc39_.bold ? _loc30_.size + 2 : _loc30_.size,_loc39_.color == "" ? _loc30_.color : _loc39_.color,_loc39_.bold,null,_loc39_.underline);
param1.setTextFormat(_loc24_,_loc39_.startIndex,_loc39_.endIndex);
_loc31_++;
}
}
}
}
else if(param1.multiline)
{
param2 = param2.replace(/\r\n|\r/gm,"\n");
while(Number(_loc30_.size) > 5 && (param1.textWidth > param1.width && !isDifference99PercentOrGreater(param1.width,param1.textWidth,_loc8_ != null) || param1.textHeight > param1.height - 4 && !isDifference99PercentOrGreater(param1.height - 4,param1.textHeight,_loc8_ != null) || _loc35_ != null && _loc35_.numLines > 1 && !isLastLetterAReturn(_loc35_.text) || _loc27_))
{
_loc28_ = param2;
_loc19_ = [];
_loc10_ = 0;
_loc11_ = 0;
_loc21_ = 0;
_loc36_ = 0;
_loc35_ = new TextField();
_loc35_.defaultTextFormat = param1.defaultTextFormat;
_loc35_.width = param1.width;
_loc35_.height = param1.height;
_loc35_.setTextFormat(_loc30_);
_loc35_.antiAliasType = param1.antiAliasType;
_loc35_.embedFonts = param1.embedFonts;
_loc35_.gridFitType = param1.gridFitType;
_loc35_.maxChars = param1.maxChars;
_loc35_.wordWrap = param1.wordWrap;
_loc35_.multiline = param1.multiline;
_loc33_ = 0;
while(_loc33_ < _loc28_.length)
{
_loc14_ = _loc28_.charAt(_loc33_);
if(_loc33_ + 1 == _loc28_.length)
{
_loc35_.appendText(_loc14_);
_loc35_.setTextFormat(_loc30_);
_loc19_[_loc10_] = _loc35_.text;
}
else if(_loc35_.textWidth > _loc35_.width && !isDifference99PercentOrGreater(_loc35_.width,_loc35_.textWidth,_loc8_ != null) || _loc35_.textHeight > _loc35_.height - 4 && !isDifference99PercentOrGreater(_loc35_.height - 4,_loc35_.textHeight,_loc8_ != null) || _loc35_.numLines > 1 && !isLastLetterAReturn(_loc35_.text))
{
if(_loc14_ == " " || _loc14_ == "\n" || _loc14_ == "\r")
{
_loc35_.appendText(_loc14_);
_loc19_[_loc10_] = _loc35_.text;
_loc21_ = _loc11_ = _loc33_ + 1;
_loc10_++;
_loc35_.text = "";
_loc35_.setTextFormat(_loc30_);
}
else
{
if(_loc11_ == _loc21_)
{
break;
}
_loc15_ = _loc35_.text.substring(0,_loc36_);
if(shouldAddSpace(_loc15_))
{
_loc19_[_loc10_] = _loc15_ + " ";
}
else
{
_loc19_[_loc10_] = _loc15_;
}
_loc11_ = _loc21_;
_loc10_++;
_loc35_.text = "";
_loc35_.setTextFormat(_loc30_);
_loc33_ = _loc21_ - 1;
}
}
else if(_loc14_ == " " || _loc14_ == "-")
{
_loc35_.appendText(_loc14_);
_loc21_ = _loc33_ + 1;
_loc36_ = _loc35_.length;
_loc35_.setTextFormat(_loc30_);
}
else if(_loc14_ == "\n" || _loc14_ == "\r")
{
_loc37_ = _loc28_.charAt(_loc33_ - 1);
if(_loc33_ == 0 || _loc37_ == "." || _loc37_ == "!" || _loc37_ == "?" || _loc37_ == "\n" || _loc37_ == "\r")
{
_loc35_.appendText(_loc14_);
_loc35_.setTextFormat(_loc30_);
}
else
{
_loc35_.appendText(" ");
_loc35_.setTextFormat(_loc30_);
}
_loc21_ = _loc33_ + 1;
_loc36_ = _loc35_.length;
}
else
{
_loc35_.appendText(_loc14_);
_loc35_.setTextFormat(_loc30_);
}
_loc33_++;
}
if(param6 && _loc30_.size < _loc18_ * 0.7)
{
_loc20_ = _loc19_.length > 1 ? _loc19_.length - 2 : 0;
_loc22_ = _loc19_[_loc20_];
_loc19_[_loc20_] = _loc22_ != null ? _loc22_.substr(0,_loc22_.length - 4) + "..." : "";
if(_loc20_ != 0)
{
_loc19_.pop();
}
_loc32_ = true;
_loc30_.size = _loc18_;
param1.setTextFormat(_loc30_);
updateToFit(param1,_loc19_.join(""),param3,param4,param5,param6);
return;
}
if(_loc33_ == _loc28_.length)
{
if(param4)
{
param1.text = _loc19_.join("");
param1.htmlText = _loc34_ + "<u>" + _loc19_.join("") + "</u></a>";
}
else
{
param1.text = _loc19_.join("");
}
}
_loc30_.size = Number(_loc30_.size) - 1;
param1.setTextFormat(_loc30_);
if(param3 && _loc8_ != null)
{
_loc31_ = 0;
while(_loc31_ < _loc8_.length)
{
_loc39_ = _loc8_[_loc31_];
_loc24_ = new TextFormat("CCDigitalDelivery",_loc39_.bold ? _loc30_.size + 2 : _loc30_.size,_loc39_.color == "" ? null : _loc39_.color,_loc39_.bold,null,_loc39_.underline);
param1.setTextFormat(_loc24_,_loc39_.startIndex,_loc39_.endIndex);
_loc31_++;
}
}
_loc27_ = hasBrokenWord(param1,param2);
}
}
param1.sharpness = Number(_loc30_.size);
if(_loc23_ != 0)
{
param1.rotation = _loc23_;
}
if(!param1.multiline && param5)
{
if(param1.rotation == 0)
{
param1.y += (_loc7_ - param1.textHeight) * 0.5;
}
else
{
_loc17_ = param1.rotation;
param1.rotation = 0;
param1.y += Math.round((_loc7_ - param1.textHeight) * 0.5);
param1.rotation = _loc17_;
}
}
}
else if(param3 && _loc8_ != null)
{
_loc31_ = 0;
while(_loc31_ < _loc8_.length)
{
_loc39_ = _loc8_[_loc31_];
_loc24_ = new TextFormat("CCDigitalDelivery",_loc39_.bold ? _loc30_.size + 2 : _loc30_.size,_loc39_.color == "" ? _loc30_.color : _loc39_.color,_loc39_.bold,null,_loc39_.underline);
param1.setTextFormat(_loc24_,_loc39_.startIndex,_loc39_.endIndex);
_loc31_++;
}
}
if(_loc12_ && param1.name != _loc12_.name)
{
_loc12_.visible = false;
}
if(_loc9_)
{
param1.multiline = true;
param1.wordWrap = true;
}
if(param1.multiline && param5 && param1.text != "")
{
if(param1.parent.scaleY != 1)
{
_loc38_ = param1.parent.height / param1.parent.scaleY;
}
else
{
_loc38_ = param1.parent.height;
}
if(param1.y < 0)
{
_loc29_ = param1.y + _loc38_ * 0.5;
}
else
{
_loc29_ = param1.y;
}
_loc26_ = (param1.height - param1.textHeight) * 0.5;
if(_loc29_ + param1.textHeight + _loc26_ > _loc38_)
{
param1.y += _loc38_ - (_loc29_ + param1.textHeight);
}
else
{
param1.y += _loc26_;
}
}
if(_loc23_ != 0)
{
param1.rotation = _loc23_;
}
}
private static function findSpecialTagPositions(param1:Object) : void
{
var _loc9_:Boolean = false;
var _loc3_:Boolean = false;
var _loc11_:int = 0;
var _loc13_:int = 0;
var _loc5_:int = 0;
var _loc6_:int = 0;
var _loc7_:Array = [];
var _loc12_:String = param1.text;
var _loc10_:String = "";
var _loc2_:String = "";
var _loc8_:Boolean = false;
var _loc4_:Boolean = false;
_loc6_ = 0;
while(_loc6_ < _loc12_.length)
{
if(_loc12_.charAt(_loc6_) == "<")
{
_loc5_++;
_loc6_++;
if(_loc12_.charAt(_loc6_) == "/")
{
_loc3_ = true;
}
else
{
_loc9_ = true;
}
while(_loc12_.charAt(_loc6_) != ">")
{
if(_loc12_.charAt(_loc6_) == "c" && _loc12_.charAt(_loc6_ + 1) == "=")
{
_loc2_ += _loc12_.substring(_loc6_ + 2,_loc6_ + 10);
_loc6_ += 10;
_loc5_ += 10;
}
else if(_loc12_.charAt(_loc6_) == "u" && _loc12_.charAt(_loc6_ + 1) == "=")
{
_loc4_ = _loc12_.charAt(_loc6_ + 2) == "t";
_loc6_ += 2;
_loc5_ += 2;
}
else if(_loc12_.charAt(_loc6_) == "b" && _loc12_.charAt(_loc6_ + 1) == "=")
{
_loc8_ = _loc12_.charAt(_loc6_ + 2) == "t";
_loc6_ += 2;
_loc5_ += 2;
}
else
{
_loc6_++;
_loc5_++;
}
}
if(_loc12_.charAt(_loc6_) == ">")
{
_loc5_++;
}
if(_loc9_)
{
_loc11_ = _loc6_ + 1 - _loc5_;
_loc9_ = false;
}
else
{
_loc13_ = _loc6_ + 1 - _loc5_;
_loc3_ = false;
_loc7_.push({
"startIndex":_loc11_,
"endIndex":_loc13_,
"color":_loc2_,
"bold":_loc8_,
"underline":_loc4_
});
_loc2_ = "";
_loc8_ = false;
_loc4_ = false;
}
}
else
{
_loc10_ += _loc12_.charAt(_loc6_);
}
_loc6_++;
}
param1.array = _loc7_;
param1.text = _loc10_;
}
private static function isDifference99PercentOrGreater(param1:Number, param2:Number, param3:Boolean) : Boolean
{
return param1 / param2 >= (param3 ? 0.999 : 0.996);
}
private static function hasBrokenWord(param1:TextField, param2:String) : Boolean
{
var _loc4_:* = null;
var _loc5_:int = 0;
var _loc7_:String = null;
var _loc6_:Number = NaN;
var _loc3_:Number = 0;
_loc5_ = 0;
while(_loc5_ < param2.length)
{
_loc7_ = param2.charAt(_loc5_);
_loc6_ = param1.getLineIndexOfChar(_loc5_);
if(_loc6_ != _loc3_)
{
if(_loc4_ != " " && _loc4_ != "\r" && _loc4_ != "\n" && _loc4_ != "\r\n" && _loc4_ != "-")
{
return true;
}
}
_loc3_ = _loc6_;
_loc4_ = _loc7_;
_loc5_++;
}
return false;
}
private static function isLastLetterAReturn(param1:String) : Boolean
{
var _loc2_:String = param1.substr(-1);
if(_loc2_ == "\n" || _loc2_ == "\r")
{
return true;
}
return false;
}
private static function shouldAddSpace(param1:String) : Boolean
{
var _loc2_:String = param1.substr(-1);
if(_loc2_ == " " || _loc2_ == "\n" || _loc2_ == "\r")
{
return false;
}
return true;
}
private static function translateLocalizedIdAndUpdateSize(param1:TextField) : void
{
var _loc2_:Object = translateLocalizedId(param1.text);
if(param1.text != _loc2_.text || param1.sharpness != -1 && param1.sharpness != param1.defaultTextFormat.size)
{
if(_loc2_.isHtmlClick)
{
updateToFit(param1,"<a " + _loc2_.htmlRefText + "><u>" + _loc2_.text + "</u></a>",false,true);
}
else
{
updateToFit(param1,_loc2_.text,_loc2_.isHtmlNormal);
}
}
}
public static function translateLocalizedId(param1:String) : Object
{
var _loc2_:Array = null;
var _loc3_:String = null;
if(_staticLocalizations)
{
_loc2_ = param1.split("#");
if(_loc2_.length > 1)
{
_loc3_ = _staticLocalizations[int(removeCarriageReturn(_loc2_[1]))] as String;
if(_loc3_ != null && _loc3_ != "")
{
if(_loc2_.length == 4)
{
return {
"text":_loc3_,
"isHtmlNormal":false,
"isHtmlClick":true,
"htmlRefText":_loc2_[3]
};
}
if(_loc2_.length == 3)
{
return {
"text":_loc3_,
"isHtmlNormal":true,
"isHtmlClick":false
};
}
return {
"text":_loc3_,
"isHtmlNormal":false,
"isHtmlClick":false
};
}
return {
"text":param1,
"isHtmlNormal":false,
"isHtmlClick":false
};
}
return {
"text":removeCarriageReturn(param1),
"isHtmlNormal":false,
"isHtmlClick":false
};
}
return {
"text":removeCarriageReturn(param1),
"isHtmlNormal":false,
"isHtmlClick":false
};
}
private static function removeCarriageReturn(param1:String) : String
{
var _loc2_:String = param1.charAt(param1.length - 1);
if(_loc2_ == "\r" || _loc2_ == "\n" || _loc2_ == "\r\n")
{
return param1.substr(0,param1.length - 1);
}
return param1;
}
public static function findAllTextfields(param1:Object) : void
{
var _loc2_:int = 0;
var _loc4_:Object = null;
if(param1 is TextField)
{
translateLocalizedIdAndUpdateSize(TextField(param1));
return;
}
if(param1.hasOwnProperty("numChildren"))
{
_loc2_ = 0;
while(_loc2_ < param1.numChildren)
{
_loc4_ = param1.getChildAt(_loc2_);
if(_loc4_)
{
if(_loc4_.name == "bakedLogo")
{
_loc4_.gotoAndStop(currentLanguage + 1);
}
else if(_loc4_.name == "countryCodeTxt")
{
for each(var _loc3_:Object in _loc4_.currentLabels)
{
if(_loc3_.name.toLowerCase() == _countryCode.toLowerCase())
{
_loc4_.gotoAndStop(_loc3_.name);
break;
}
}
}
if(_loc4_ is TextField)
{
translateLocalizedIdAndUpdateSize(TextField(_loc4_));
}
if(_loc4_.hasOwnProperty("numChildren") && _loc4_.numChildren > 0)
{
findAllTextfields(_loc4_);
}
}
_loc2_++;
}
}
}
public static function translateAvatarName(param1:String) : String
{
var _loc3_:Array = null;
var _loc4_:Array = null;
var _loc5_:String = null;
var _loc2_:Array = param1.split("|");
if(_loc2_.length > 1)
{
if(isCurrLanguageReversed())
{
_loc3_ = LocalizationManager.translateIdOnly(_loc2_[2]).split("$");
_loc4_ = LocalizationManager.translateIdOnly(_loc2_[1]).split("$");
if(_loc3_.length == 1 || _loc3_[1] == "m")
{
_loc5_ = _loc4_[0].toLowerCase();
}
else if(_loc4_.length == 1)
{
_loc5_ = _loc4_[0].toLowerCase();
}
else
{
_loc5_ = _loc4_[1].toLowerCase();
}
return translateIdOnly(_loc2_[0]) + " " + _loc3_[0] + _loc5_;
}
return translateIdOnly(_loc2_[0]) + " " + translateIdOnly(_loc2_[1]) + translateIdOnly(_loc2_[2]).toLowerCase();
}
// a name its owner typed (world.js xrn), not the game's word ids:
// through the player's chat filter (AJClient.filterName)
return AJClient.filterName(param1);
}
public static function translatePetName(param1:String) : String
{
var _loc3_:Array = null;
var _loc4_:Array = null;
var _loc5_:String = null;
var _loc2_:Array = param1.split("|");
if(_loc2_.length > 1)
{
if(isCurrLanguageReversed())
{
_loc3_ = LocalizationManager.translateIdOnly(_loc2_[1]).split("$");
_loc4_ = LocalizationManager.translateIdOnly(_loc2_[0]).split("$");
if(_loc3_.length == 1 || _loc3_[1] == "m")
{
_loc5_ = _loc4_[0].toLowerCase();
}
else if(_loc4_.length == 1)
{
_loc5_ = _loc4_[0].toLowerCase();
}
else
{
_loc5_ = _loc4_[1].toLowerCase();
}
return _loc3_[0] + _loc5_;
}
return translateIdOnly(_loc2_[0]) + translateIdOnly(_loc2_[1]).toLowerCase();
}
// a name its owner typed (world.js xrn), not the game's word ids:
// through the player's chat filter (AJClient.filterName)
return AJClient.filterName(param1);
}
public static function isCurrLanguageReversed() : Boolean
{
if(currentLanguage == LANG_FRE || currentLanguage == LANG_POR || currentLanguage == LANG_SPA)
{
return true;
}
return false;
}
}
}
+551
View File
@@ -0,0 +1,551 @@
package game.microSmoothie
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.utils.getTimer;
import game.GameBase;
import game.IMinigame;
import game.MinigameManager;
import game.SoundManager;
import gskinner.motion.GTween;
public class MicroSmoothie extends GameBase implements IMinigame
{
private static const MAX_VELOCITY_X:Number = 900;
private static const MAX_VELOCITY_Y:Number = 250;
private static const ACCELERATION_X:Number = 2500;
private static const ACCELERATION_Y:Number = 450;
private static const BRAKE_X:Number = 4000;
private static const BRAKE_Y:Number = 800;
private static const REQUIRED_FRUITS:int = 10;
public var _fruitTypesColor:Array;
public var _fruitTypes:Array;
public var myId:uint;
public var _pIDs:Array;
public var _dbIDs:Array;
private var _sceneLoaded:Boolean;
private var _bInit:Boolean;
public var _layerBack:Sprite;
public var _layerFront:Sprite;
public var _layerFruits:Sprite;
public var _layerCupFront:Sprite;
private var _lastTime:int;
private var _frameTime:Number;
private var _gameTime:Number;
private var _cupFront:Object;
private var _cupBack:Object;
private var _cupFrontMax:Object;
private var _cupBackMax:Object;
private var _fruitMachine:Object;
private var _ready:Object;
private var _congrats:Object;
private var _fruitStart:Object;
public var _leftArrowDown:Boolean;
public var _rightArrowDown:Boolean;
public var _downArrowDown:Boolean;
public var _upArrowDown:Boolean;
public var _nextFruitTimer:Number;
public var _congratsTimer:Number;
public var _velocityX:Number;
public var _fruitCaught:int;
public var _smoothieType:int;
private var _dismissDialogTimer:Number;
public var _soundMan:SoundManager;
public var _fruitStartSounds:Array;
private var _audio:Array = ["slushy_fruit_passby.mp3","slushy_fruit_passby2.mp3","slushy_correct_fruit.mp3","slushy_wrong_fruit.mp3","MG_popup_youWon.mp3"];
private var _soundNameFruitStart1:String = _audio[0];
private var _soundNameFruitStart2:String = _audio[1];
private var _soundNameCorrect:String = _audio[2];
private var _soundNameWrong:String = _audio[3];
private var _soundNamePlayerWins:String = _audio[4];
public function MicroSmoothie()
{
super();
_fruitTypesColor = new Array("purple","orange","red","yellow");
_fruitTypes = new Array("grapes","orange","strawberry","banana");
init();
}
private function loadSounds() : void
{
_fruitStartSounds = [];
_soundMan.addSoundByName(_audioByName[_soundNameFruitStart1],_soundNameFruitStart1,0.5);
_soundMan.addSoundByName(_audioByName[_soundNameFruitStart2],_soundNameFruitStart2,0.5);
_fruitStartSounds = new Array(_soundNameFruitStart1,_soundNameFruitStart2);
_soundMan.addSoundByName(_audioByName[_soundNameCorrect],_soundNameCorrect,0.8);
_soundMan.addSoundByName(_audioByName[_soundNameWrong],_soundNameWrong,0.8);
_soundMan.addSoundByName(_audioByName[_soundNamePlayerWins],_soundNamePlayerWins,0.35);
}
private function keyHandleUp(param1:KeyboardEvent) : void
{
switch(int(param1.keyCode) - 37)
{
case 0:
_leftArrowDown = false;
break;
case 1:
_upArrowDown = false;
break;
case 2:
_rightArrowDown = false;
break;
case 3:
_downArrowDown = false;
}
}
private function keyHandleDown(param1:KeyboardEvent) : void
{
switch(int(param1.keyCode) - 37)
{
case 0:
_leftArrowDown = true;
break;
case 1:
_upArrowDown = true;
break;
case 2:
_rightArrowDown = true;
break;
case 3:
_downArrowDown = true;
}
}
public function start(param1:uint, param2:Array) : void
{
myId = param1;
_pIDs = param2;
init();
}
public function end(param1:Array) : void
{
releaseBase();
stage.removeEventListener("keyUp",keyHandleUp);
stage.removeEventListener("keyDown",keyHandleDown);
stage.removeEventListener("enterFrame",heartbeat);
stage.removeEventListener("click",mouseClickHandler);
resetGame();
_bInit = false;
removeLayer(_layerBack);
removeLayer(_layerFront);
removeLayer(_layerFruits);
removeLayer(_layerCupFront);
removeLayer(_guiLayer);
_layerBack = null;
_layerFront = null;
_layerFruits = null;
_layerCupFront = null;
_guiLayer = null;
MinigameManager.leave();
}
private function init() : void
{
if(!_bInit)
{
_layerBack = new Sprite();
_layerFront = new Sprite();
_layerFruits = new Sprite();
_layerCupFront = new Sprite();
_layerBack.mouseEnabled = false;
_layerFront.mouseEnabled = false;
_layerFruits.mouseEnabled = false;
_layerCupFront.mouseEnabled = false;
_guiLayer = new Sprite();
addChild(_layerBack);
addChild(_layerFruits);
addChild(_layerFront);
addChild(_layerCupFront);
addChild(_guiLayer);
loadScene("SmoothieAssets/room_main.xroom",_audio);
_bInit = true;
}
else
{
startGame();
}
}
override protected function sceneLoaded(param1:Event) : void
{
var _loc3_:int = 0;
var _loc4_:Object = null;
var _loc2_:* = null;
_soundMan = new SoundManager(this);
loadSounds();
_loc4_ = _scene.getLayer("closeButton");
addBtn("CloseButton",_loc4_.x,_loc4_.y,onCloseButton);
_cupFront = _scene.getLayer("cupFront");
_cupBack = _scene.getLayer("cupBack");
_cupFrontMax = _scene.getLayer("cupFrontMax");
_cupBackMax = _scene.getLayer("cupBackMax");
_fruitMachine = _scene.getLayer("smoothieGame");
_layerBack.addChild(_scene.getLayer("smoothieBackground").loader);
_layerBack.addChild(_cupBack.loader);
_layerFruits.addChild(_fruitMachine.loader);
_layerCupFront.addChild(_cupFront.loader);
_congrats = _scene.getLayer("smoothieSuccess");
_leftArrowDown = false;
_rightArrowDown = false;
_downArrowDown = false;
_upArrowDown = false;
stage.addEventListener("keyUp",keyHandleUp);
stage.addEventListener("keyDown",keyHandleDown);
_sceneLoaded = true;
stage.addEventListener("enterFrame",heartbeat,false,0,true);
stage.addEventListener("click",mouseClickHandler);
startGame();
super.sceneLoaded(param1);
}
public function message(param1:Array) : void
{
var _loc3_:int = 0;
var _loc2_:int = 0;
if(param1[0] != "ml")
{
if(param1[0] == "ms")
{
_dbIDs = [];
_loc2_ = 0;
while(_loc2_ < _pIDs.length)
{
_dbIDs[_loc2_] = param1[_loc2_ + 1];
_loc2_++;
}
}
else if(param1[0] == "mm")
{
}
}
}
public function heartbeat(param1:Event) : void
{
var _loc3_:int = 0;
var _loc7_:* = null;
var _loc6_:Point = null;
var _loc5_:int = 0;
var _loc2_:int = 0;
var _loc4_:int = 0;
if(_sceneLoaded)
{
_frameTime = (getTimer() - _lastTime) / 1000;
if(_frameTime > 0.5)
{
_frameTime = 0.5;
}
_lastTime = getTimer();
if(_sceneLoaded)
{
_gameTime += _frameTime;
if(_fruitCaught < 10)
{
if(_dismissDialogTimer > 0)
{
_dismissDialogTimer -= _frameTime;
if(_dismissDialogTimer <= 0)
{
hideDlg();
_nextFruitTimer = 1.5;
}
}
else if(_nextFruitTimer >= 0)
{
_loc6_ = localToGlobal(new Point(_cupBack.loader.x,_cupBack.loader.y));
_loc5_ = int(_fruitMachine.loader.content.detectCollision(_loc6_.x,_loc6_.y,_cupBack.width,_cupBack.height + 75));
if(_loc5_ >= 0)
{
if(_loc5_ == _smoothieType)
{
_soundMan.playByName(_soundNameCorrect);
_fruitCaught += 2;
updateFruitMeter();
if(_fruitCaught >= 10)
{
new GTween(_fruitMachine.loader,0.5,{"alpha":0});
_guiLayer.addChild(_congrats.loader);
_congrats.loader.content.Ready_Text.gotoAndPlay("on");
if(_closeBtn)
{
_closeBtn.visible = false;
}
// the adventure's own smoothie machine (91) counts
// towards it; any other gives a smoothie, even when
// the game it is was not noted down (-1), where
// before it gave nothing
if(MinigameManager.minigameInfoCache && MinigameManager.minigameInfoCache.currMinigameId == 91)
{
MinigameManager.handleQuestMiniGameComplete(1);
}
else
{
MinigameManager.msg(["_a",2,_fruitTypesColor[_smoothieType]]);
}
_congratsTimer = 3;
_soundMan.playByName(_soundNamePlayerWins);
}
}
else
{
_soundMan.playByName(_soundNameWrong);
_cupFront.loader.content.loseSlush();
_fruitCaught -= 2;
if(_fruitCaught < 0)
{
_fruitCaught = 0;
}
updateFruitMeter();
}
}
_nextFruitTimer -= _frameTime;
if(_nextFruitTimer <= 0)
{
_loc2_ = Math.random() * 6;
if(_loc2_ >= 3)
{
_loc2_ = _smoothieType;
}
else if(_smoothieType == _loc2_)
{
_loc2_ = 3;
}
_nextFruitTimer = 0.5 + Math.random() * 0.5;
_fruitMachine.loader.content.createFruit(_loc2_);
_loc4_ = Math.random() * _fruitStartSounds.length;
_soundMan.playByName(_fruitStartSounds[_loc4_]);
}
_cupBack.loader.x = stage.mouseX - _cupFront.width / 2;
_cupFront.loader.x = stage.mouseX - _cupFront.width / 2;
if(_cupFront.loader.x < _cupFront.x)
{
_cupBack.loader.x = _cupBack.x;
_cupFront.loader.x = _cupFront.x;
}
else if(_cupFront.loader.x > _cupFrontMax.x)
{
_cupBack.loader.x = _cupBackMax.x;
_cupFront.loader.x = _cupFrontMax.x;
}
}
}
else
{
_congratsTimer -= _frameTime;
if(_congratsTimer <= 0)
{
end(null);
}
}
}
}
}
public function updateFruitMeter() : void
{
var _loc1_:int = 2;
if(_fruitCaught > 0)
{
_loc1_ = Math.max(3,_fruitCaught / 10 * 15 + 1);
if(_loc1_ > 16)
{
_loc1_ = 16;
}
}
_cupFront.loader.content.gotoAndStop(_loc1_);
}
public function updateControls() : void
{
if(stage.mouseX < _cupFront.loader.x + _cupFront.width / 5)
{
_velocityX -= 2500 * _frameTime;
if(_velocityX < -900)
{
_velocityX = -900;
}
}
else if(stage.mouseX > _cupFront.loader.x + 4 * _cupFront.width / 5)
{
_velocityX += 2500 * _frameTime;
if(_velocityX > 900)
{
_velocityX = 900;
}
}
else if(_velocityX > 0)
{
_velocityX -= 4000 * _frameTime;
if(_velocityX < 0)
{
_velocityX = 0;
}
}
else if(_velocityX < 0)
{
_velocityX += 4000 * _frameTime;
if(_velocityX > 0)
{
_velocityX = 0;
}
}
}
public function startGame() : void
{
var _loc2_:int = 0;
var _loc4_:* = null;
var _loc3_:Number = NaN;
var _loc1_:MovieClip = null;
_gameTime = 0;
_lastTime = getTimer();
_frameTime = 0;
_nextFruitTimer = -1;
_dismissDialogTimer = 0;
_fruitCaught = 0;
_velocityX = 0;
if(_sceneLoaded)
{
_loc3_ = (_cupFrontMax.x - _cupFront.x) / 2;
_cupFront.loader.x = _cupFront.x + _loc3_;
_cupBack.loader.x = _cupBack.x + _loc3_;
_cupFront.loader.content.gotoAndStop(2);
_loc1_ = showDlg("popup_flavor",[{
"name":"button_strawberry",
"f":onFlavorStrawberry
},{
"name":"button_orange",
"f":onFlavorOrange
},{
"name":"button_banana",
"f":onFlavorBanana
},{
"name":"button_grape",
"f":onFlavorGrape
}]);
_loc1_.x = 455;
_loc1_.y = 225;
}
}
public function resetGame() : void
{
var _loc1_:int = 0;
}
private function mouseClickHandler(param1:MouseEvent) : void
{
if(_sceneLoaded)
{
}
}
public function onCloseButton() : void
{
end(null);
}
public function onStart() : void
{
hideDlg();
if(_ready && _ready.loader.parent)
{
_ready.loader.parent.removeChild(_ready.loader);
}
_nextFruitTimer = 3;
}
public function selectFlavor(param1:int) : void
{
_smoothieType = param1;
_cupFront.loader.content.slush.gotoAndStop(_fruitTypesColor[_smoothieType]);
hideDlg();
var _loc2_:MovieClip = showDlg("popup_fillcup",[]);
_loc2_.x = 455;
_loc2_.y = 300;
_loc2_.gotoAndStop(_fruitTypes[_smoothieType]);
_dismissDialogTimer = 3;
addChild(_scene.getLayer("pickedFruit").loader);
}
public function onFlavorStrawberry() : void
{
_scene.getLayer("pickedFruit").loader.content.gotoAndStop("icon_strawberry");
selectFlavor(2);
}
public function onFlavorBanana() : void
{
_scene.getLayer("pickedFruit").loader.content.gotoAndStop("icon_banana");
selectFlavor(3);
}
public function onFlavorOrange() : void
{
_scene.getLayer("pickedFruit").loader.content.gotoAndStop("icon_orange");
selectFlavor(1);
}
public function onFlavorGrape() : void
{
_scene.getLayer("pickedFruit").loader.content.gotoAndStop("icon_grape");
selectFlavor(0);
}
}
}
File diff suppressed because it is too large. Load diff
+34 -5
View File
@@ -77,6 +77,9 @@ package gui
public function destroy() : void
{
// Never leave the editor's full-screen layer behind to swallow
// clicks after Settings is closed by another path.
ItemWindowToggle.closeChatBubbleEditor();
removeEventListeners();
_popupLayer.removeChild(_mySettings);
_closeCallback = null;
@@ -174,6 +177,15 @@ package gui
"iconFrame":"buddyRequest",
"labelLabel":"Chat Filter",
"btnLabel":"Open"
},{
// Chat appearance is account-wide; this opens the centered
// in-game editor rather than burying it in the emoji picker.
"type":TOGGLE_TYPE_JOIN,
"frame":"chatBubble",
// Reuse Predict Chat's ABC artwork and keep it in its on state.
"iconFrame":"predictTxt",
"labelLabel":"Chat Bubble",
"btnLabel":"Customize"
},{
"type":TOGGLE_TYPE_JOIN,
"frame":"themeMenu",
@@ -201,9 +213,14 @@ package gui
"run":showSavedList
*/
},{
"type":TOGGLE_TYPE_JOIN,
// this server's switches, drawn as the Nametag row is: the two
// choices named either side of the knob (ItemWindowToggle)
"type":TOGGLE_TYPE_TOGGLE_BTN,
"frame":"wasd",
"iconFrame":"world"
"iconFrame":"world",
"labelLabel":"WASD Movement",
"onLabel":"On",
"offLabel":"Off"
},{
"type":TOGGLE_TYPE_JOIN,
"frame":"performance",
@@ -221,13 +238,25 @@ package gui
"frame":"camera",
"iconFrame":"world"
},{
"type":TOGGLE_TYPE_JOIN,
"type":TOGGLE_TYPE_TOGGLE_BTN,
"frame":"hideBlocked",
"iconFrame":"buddyRequest"
"iconFrame":"buddyRequest",
"labelLabel":"Blocked Players",
"onLabel":"Shown",
"offLabel":"Hidden"
},{
// the pictures players give their items (AJClient.customArtOn)
"type":TOGGLE_TYPE_JOIN,
"type":TOGGLE_TYPE_TOGGLE_BTN,
"frame":"customArt",
"iconFrame":"redeemCode",
"labelLabel":"Custom Items",
"onLabel":"Shown",
"offLabel":"Hidden"
},{
// more, smaller items a row in the clothes and item pickers
// (AJClient.expandedInventoryOn)
"type":TOGGLE_TYPE_JOIN,
"frame":"expandedInventory",
"iconFrame":"redeemCode"
},{
"type":TOGGLE_TYPE_JOIN,
+37 -5
View File
@@ -702,11 +702,17 @@ package gui
{
_loc2_.txt.text = "";
}
if(_loc2_.title != null)
// the Alpha HQ's bios have no title (string 0), and an id with no
// string throws: the popup stayed on screen with nothing able to
// close it. none is left as it is.
if(_loc2_.title != null && param1.title > 0)
{
LocalizationManager.translateId(_loc2_.title.txt,param1.title);
}
LocalizationManager.translateId(_loc2_.txt,param1.description);
if(param1.description > 0)
{
LocalizationManager.translateId(_loc2_.txt,param1.description);
}
if(param1.media && param1.media != 0)
{
_loc3_ = new MediaHelper();
@@ -724,7 +730,13 @@ package gui
}
}
_loc2_.addEventListener("mouseDown",factMouseDownHandler,false,0,true);
if(_loc2_.nextBtn)
// one fact on its own (not one of a list) has no next or previous
if(_loc2_.nextBtn && (_genericFactDefIndexList == null || isNaN(param1.index)))
{
_loc2_.nextBtn.visible = false;
_loc2_.prevBtn.visible = false;
}
else if(_loc2_.nextBtn)
{
_loc2_.nextBtn.addEventListener("mouseDown",factNextPrevBtnHandler,false,0,true);
_loc2_.prevBtn.addEventListener("mouseDown",factNextPrevBtnHandler,false,0,true);
@@ -809,6 +821,11 @@ package gui
private static function reloadGenericFactPopup(param1:Object) : void
{
// a fact had by its id is in no list: the arrows have nowhere to go
if(param1 == null)
{
return;
}
factCloseHandler(null);
if(param1.type == 18 || param1.type == 12 || param1.type == 17 || param1.type == 9 || param1.type == 19)
{
@@ -824,6 +841,11 @@ package gui
{
var _loc3_:String = null;
var _loc5_:Array = null;
// a fact had by its id is in no list: the arrows have nowhere to go
if(param1 == null)
{
return;
}
_factPopup.index = param1.index;
_factPopup.bitIdx = param1.bitIdx;
while(_factPopup.imgBlock.numChildren > 0)
@@ -1022,10 +1044,12 @@ package gui
}
DarkenManager.showLoadingSpiral(false);
_loc2_ = _genericFactDefList[_genericFactId];
// the fact lists came from the official server; one this server has
// no entry for opens nothing (#1009)
// the fact lists came from the official server, and this one
// answers them empty: the fact is had by its id instead, from the
// CDN's factDefs (requestFactInfo), as the game's other facts are
if(_loc2_ == null)
{
requestFactInfo([_genericFactId]);
return;
}
if(_loc2_.type == 18 || _loc2_.type == 12 || _loc2_.type == 17 || _loc2_.type == 9 || _loc2_.type == 19)
@@ -1063,6 +1087,14 @@ package gui
_museumFactDefIndexList[_loc3_] = _loc2_.id;
_loc3_++;
}
// as above: an exhibit this server's list does not have is had by
// its id. opening nothing left the game behind its spinner.
if(_museumFactDefList[_museumRequest] == null)
{
DarkenManager.showLoadingSpiral(false);
requestFactInfo([_museumRequest]);
return;
}
displayMuseumEngangermentPopup(_museumFactDefList[_museumRequest]);
}
+487
View File
@@ -0,0 +1,487 @@
package pet
{
import flash.display.MovieClip;
import flash.display.Sprite;
import loader.MediaHelper;
import localization.LocalizationManager;
public class PetBase extends Sprite
{
public static const DEF_ID_CAT:int = 1;
public static const DEF_ID_FROG:int = 2;
public static const DEF_ID_DUCK:int = 3;
public static const DEF_ID_DOG:int = 4;
public static const DEF_ID_BFLY:int = 5;
public static const DEF_ID_HAMS:int = 6;
public static const DEF_ID_BAT:int = 7;
public static const DEF_ID_SEAHORSE:int = 8;
public static const DEF_ID_ANGLER:int = 9;
public static const DEF_ID_REINDEER:int = 10;
public static const DEF_ID_SNAKE:int = 11;
public static const DEF_ID_JELLYFISH:int = 12;
public static const DEF_ID_BUNNY:int = 13;
public static const DEF_ID_HUMMINGBIRD:int = 14;
public static const DEF_ID_TURTLE:int = 15;
public static const DEF_ID_MONKEY:int = 16;
public static const DEF_ID_TARANTUAL:int = 17;
public static const DEF_ID_FOX:int = 18;
public static const DEF_ID_OWL:int = 19;
public static const DEF_ID_TIGER:int = 20;
public static const DEF_ID_ARCTIC_WOLF:int = 21;
public static const DEF_ID_RACCOON:int = 22;
public static const DEF_ID_JOEY:int = 23;
public static const DEF_ID_EAGLET:int = 24;
public static const DEF_ID_CHEETAH:int = 25;
public static const DEF_ID_RHINO:int = 26;
public static const DEF_ID_GIRAFFE:int = 27;
public static const DEF_ID_SUGAR_GLIDER:int = 28;
public static const DEF_ID_LION_CUB:int = 29;
public static const DEF_ID_PANDA:int = 30;
public static const DEF_ID_POLAR_BEAR_CUB:int = 31;
public static const DEF_ID_GECKO:int = 32;
public static const DEF_ID_PONY:int = 34;
public static const DEF_ID_PIGLET:int = 35;
public static const DEF_ID_FERRET:int = 36;
public static const DEF_ID_ELEPHANT:int = 37;
public static const DEF_ID_ARMADILLO:int = 38;
public static const DEF_ID_PEACOCK:int = 39;
public static const DEF_ID_BEE:int = 40;
public static const DEF_ID_ROOSTER:int = 41;
public static const DEF_ID_SKUNK:int = 42;
public static const DEF_ID_TURKEY:int = 43;
public static const DEF_ID_PENGUIN:int = 44;
public static const DEF_ID_SNOW_LEOPARD:int = 45;
public static const DEF_ID_MANITS:int = 46;
public static const DEF_ID_LADYBUG:int = 47;
public static const DEF_ID_CRICKET:int = 48;
public static const DEF_ID_SQUIRREL:int = 49;
public static const DEF_ID_MOUSE:int = 50;
public static const DEF_ID_FIREFLY:int = 51;
public static const DEF_ID_LEMUR:int = 52;
public static const DEF_ID_HIPPO:int = 53;
public static const DEF_ID_GOAT:int = 54;
public static const DEF_ID_MEERKAT:int = 55;
public static const DEF_ID_GOLDEN_BUNNY:int = 56;
public static const DEF_ID_PHANTOM:int = 57;
public static const DEF_ID_SEAL:int = 58;
public static const DEF_ID_OTTER:int = 59;
public static const DEF_ID_PHANTOM_RARE:int = 60;
public static const DEF_ID_GROUND_HOG:int = 61;
public static const DEF_ID_LLAMA:int = 62;
public static const DEF_ID_ARCTIC_FOX:int = 63;
public static const DEF_ID_HYENA:int = 64;
public static const DEF_ID_SLOTH:int = 65;
public static const DEF_ID_DOVE:int = 66;
public static const DEF_ID_CHICK:int = 67;
public static const DEF_ID_GOLDEN_ARMADILLO:int = 68;
public static const DEF_ID_FALCON:int = 69;
public static const DEF_ID_CROCODILE:int = 70;
public static const DEF_ID_PLATYPUS:int = 71;
public static const DEF_ID_PHANTOM_JW:int = 72;
public static const DEF_ID_GOLDEN_PONY:int = 73;
public static const DEF_ID_SHARK:int = 74;
public static const DEF_ID_DOLPHIN:int = 75;
public static const DEF_ID_ECHIDNA:int = 76;
public static const DEF_ID_KOALA:int = 77;
public static const DEF_ID_LYNX:int = 80;
public static const DEF_ID_OCTOPUS:int = 81;
public static const DEF_ID_FENNEC_FOX_JW:int = 82;
public static const DEF_ID_HEDGEHOG:int = 83;
public static const DEF_ID_SCORPION:int = 84;
public static const DEF_ID_CROW:int = 85;
public static const DEF_ID_MOOSE:int = 86;
public static const DEF_ID_POODLE:int = 87;
public static const DEF_ID_LOVEBUNNY:int = 88;
public static const DEF_ID_SABERTOOTH:int = 89;
public static const DEF_ID_DIREWOLF:int = 90;
public static const DEF_ID_DODO:int = 91;
public static const DEF_ID_FANTASY_PEACOCK:int = 92;
public static const DEF_ID_MILLIPEDE:int = 93;
public static const DEF_ID_MOTH:int = 94;
public static const DEF_ID_VULTURE:int = 95;
public static const DEF_ID_COYOTE:int = 96;
public static const DEF_ID_MEAGYNS:int = 97;
public static const DEF_ID_FALCON2:int = 98;
public static const DEF_ID_LOVE_BUG:int = 99;
public static const DEF_ID_FLYING_PIG:int = 100;
public static const DEF_ID_SPARROW:int = 101;
public static const DEF_ID_FENNEC_FOX:int = 102;
public static const DEF_ID_CARDINAL:int = 103;
public static const DEF_ID_FRILLED_LIZARD:int = 104;
public static const DEF_ID_DRAGONFLY:int = 105;
public static const DEF_ID_MAGENTA_SEAL:int = 106;
public static const DEF_ID_PANGOLIN:int = 107;
public static const DEF_ID_CAMEL:int = 108;
public static const DEF_ID_SNAIL:int = 109;
public static const DEF_ID_GALACTIC_FIREFLY:int = 110;
public static const DEF_ID_CATERPILLAR:int = 111;
public static const DEF_ID_LAMB:int = 112;
public static const DEF_ID_GOLDEN_REINDEER:int = 113;
public static const DEF_ID_HIGHLANDCOW:int = 114;
public static const DEF_ID_NIGHTHAWK:int = 115;
public static const DEF_ID_FRANKENKITTEN:int = 116;
public static const TYPE_LAND_GROUND:int = 0;
public static const TYPE_LAND_AIR:int = 1;
public static const TYPE_OCEAN_GROUND:int = 2;
public static const TYPE_OCEAN_AIR:int = 3;
public static const TYPE_AMPHIB_GROUND:int = 4;
public static const TYPE_AMPHIB_AIR:int = 5;
protected var _petDef:PetDef;
protected var _lBits:uint;
protected var _uBits:uint;
protected var _eBits:uint;
protected var _traitDefId:uint;
protected var _toyDefId:uint;
protected var _foodDefId:uint;
protected var _content:MovieClip;
protected var _createdTs:Number;
private var _mediaHelper:MediaHelper;
private var _onPetLoadedCallback:Function;
public function PetBase(param1:Number, param2:uint, param3:uint, param4:uint, param5:uint, param6:uint, param7:uint, param8:Function)
{
super();
_createdTs = param1;
_lBits = param2;
_uBits = param3;
_eBits = param4;
_traitDefId = param5;
_toyDefId = param6;
_foodDefId = param7;
_onPetLoadedCallback = param8;
_petDef = PetManager.getPetDef(param2 & 0xFF);
// bits naming no pet the game has: the first pet, rather than
// a pet that never loads and stops what was drawing it
if(_petDef == null)
{
_petDef = PetManager.getPetDef(1);
}
_mediaHelper = new MediaHelper();
_mediaHelper.init(mediaIdForDefId(_petDef.defId),onMediaLoaded,true);
}
public function destroy() : void
{
}
public function getPetTitleName() : String
{
return LocalizationManager.translateIdOnly(_petDef.titleStrId);
}
public function isGround() : Boolean
{
if(_petDef.isEgg && !PetManager.hasHatched(_createdTs))
{
return true;
}
return PetManager.isGround(_petDef.type);
}
public function isEggAndHasNotHatched() : Boolean
{
if(_petDef.isEgg)
{
return PetManager.hasHatched(_createdTs) == false;
}
return false;
}
public function isEgg() : Boolean
{
return _petDef.isEgg;
}
public function getType() : int
{
return _petDef.type;
}
public function getDefID() : int
{
return _petDef.defId;
}
public function canGoInOcean() : Boolean
{
if(_petDef.type == 2 || _petDef.type == 3 || _petDef.type == 4 || _petDef.type == 5)
{
return true;
}
return false;
}
public function canGoOnLand() : Boolean
{
if(_petDef.type == 0 || _petDef.type == 1 || _petDef.type == 4 || _petDef.type == 5)
{
return true;
}
return false;
}
public function getLBits() : uint
{
return _lBits;
}
public function getUBits() : uint
{
return _uBits;
}
public function getEBits() : uint
{
return _eBits;
}
public function getContent() : MovieClip
{
return _content;
}
public function getCreatedTs() : Number
{
return _createdTs;
}
public function colorMyItem(param1:int, param2:MovieClip, param3:int, param4:int, param5:int, param6:int, param7:int, param8:int) : void
{
if(_content)
{
_content.colorMe(param1,param2,param3,param4,param5,param6,param7,param8);
}
}
public function updateAllBits(param1:uint, param2:uint, param3:uint) : void
{
if(_content)
{
_lBits = param1;
_uBits = param2;
_eBits = param3;
PetManager.setPetState(_content,_lBits,_uBits,_eBits);
}
}
public function updateUBits(param1:uint) : void
{
_uBits = param1;
PetManager.setPetState(_content,_lBits,_uBits,_eBits);
}
public function animatePet(param1:Boolean) : void
{
if(_content && "willItAnimate" in _content.pet)
{
_content.pet.willItAnimate(param1);
}
}
protected function setSparkle(param1:int) : void
{
if(_content)
{
_content.pet.setSparkle(param1);
}
}
private function onMediaLoaded(param1:MovieClip) : void
{
var _loc2_:int = 0;
if(param1)
{
_content = param1;
this.addChild(_content);
_mediaHelper.destroy();
delete _content.mediaHelper;
delete _content.passback;
PetManager.setPetState(_content,_lBits,_uBits,_eBits);
if(_onPetLoadedCallback != null)
{
_onPetLoadedCallback(_content);
}
_content.pet.setAnim(0);
if(_petDef.isEgg)
{
if(_content.pet.hasOwnProperty("setEggDayInt"))
{
_loc2_ = _createdTs > 0 ? Math.floor((Utility.getInitialEpochTime() - _createdTs) / 86400) : 0;
_content.pet.setEggDayInt(_loc2_);
}
}
}
}
private function mediaIdForDefId(param1:int) : int
{
var _loc2_:PetDef = PetManager.getPetDef(param1);
if(_loc2_)
{
return _loc2_.mediaRefId;
}
return -1;
}
public function get personalityDefId() : uint
{
return _traitDefId;
}
public function set personalityDefId(param1:uint) : void
{
_traitDefId = param1;
}
public function get favoriteToyDefId() : uint
{
return _toyDefId;
}
public function set favoriteToyDefId(param1:uint) : void
{
_toyDefId = param1;
}
public function get favoriteFoodDefId() : uint
{
return _foodDefId;
}
public function set favoriteFoodDefId(param1:uint) : void
{
_foodDefId = param1;
}
}
}
+74
View File
@@ -3,6 +3,7 @@ package gui
import Party.PartyManager;
import adoptAPet.AdoptAPetManager;
import avatar.AvatarManager;
import avatar.UserCommXtCommManager;
import com.sbi.analytics.SBTracker;
import com.sbi.popup.SBOkPopup;
import com.sbi.popup.SBYesNoPopup;
@@ -43,6 +44,12 @@ package gui
private var _inventoryMC:MovieClip;
private var _loadingMediaHelper:MediaHelper;
// "play as your pet": the settings menu's on/off switch, in any room
// but a Play-As-Your-Pet party's (AJClient.petFormOn)
private var _petFormSwitch:MovieClip;
private var _petFormOn:Boolean;
private var _loadingSpiralBig:LoadingSpiral;
@@ -222,6 +229,7 @@ package gui
_guiLayer.addChild(_inventoryMC);
DarkenManager.darken(_inventoryMC);
createItemWindows();
addPetFormSwitch();
addEventListeners();
if(_openCheckListImmediately)
{
@@ -246,6 +254,58 @@ package gui
}
// A double click on the big pet's name lets the player type another.
// the switch sits at the top left of the pet's picture, across from
// the certificate. on, whichever pet is out stands in for the avatar,
// for everyone (the server keeps it with the user vars and tells the
// room: UserCommXtCommManager type 13).
private function addPetFormSwitch() : void
{
var _loc1_:MovieClip = null;
if(GuiManager.isBeYourPetRoom())
{
return;
}
_loc1_ = GETDEFINITIONBYNAME("mySettingsToggle",false);
_petFormSwitch = _loc1_.toggleBtn;
_loc1_.removeChild(_petFormSwitch);
_petFormSwitch.x = 78;
_petFormSwitch.y = -143;
_petFormSwitch.buttonMode = true;
_petFormSwitch.useHandCursor = true;
_petFormSwitch.toggleBtn.toggleKnob.gotoAndStop("up");
_petFormSwitch.toggleBtn.toggleBG.gotoAndStop("up");
_petFormOn = AJClient.petFormOn();
_petFormSwitch.toggleBtn.gotoAndStop(_petFormOn ? "startingOn" : "startingOff");
LocalizationManager.translateId(_petFormSwitch.toggleBtn.valueTxt.onTxt,6324);
LocalizationManager.translateId(_petFormSwitch.toggleBtn.valueTxt.offTxt,6322);
_inventoryMC.addChild(_petFormSwitch);
}
private function onPetFormSwitch(param1:MouseEvent) : void
{
param1.stopPropagation();
_petFormOn = !_petFormOn;
_petFormSwitch.toggleBtn.gotoAndPlay(_petFormOn ? "on" : "off");
UserCommXtCommManager.sendPetPlayerMode(_petFormOn);
}
private function onPetFormSwitchOver(param1:MouseEvent) : void
{
param1.stopPropagation();
_petFormSwitch.toggleBtn.toggleBG.gotoAndStop("over");
_petFormSwitch.toggleBtn.toggleKnob.gotoAndStop("over");
GuiManager.toolTip.init(_petFormSwitch,"Play as your pet",58,-10);
GuiManager.toolTip.startTimer(param1);
}
private function onPetFormSwitchOut(param1:MouseEvent) : void
{
param1.stopPropagation();
_petFormSwitch.toggleBtn.toggleBG.gotoAndStop("up");
_petFormSwitch.toggleBtn.toggleKnob.gotoAndStop("up");
GuiManager.toolTip.resetTimerAndSetVisibility();
}
private function onPetRenamed(param1:String) : void
{
var _loc2_:int = 0;
@@ -852,6 +912,12 @@ package gui
_inventoryMC.salonBtn.addEventListener("mouseDown",onSalonBtn,false,0,true);
_inventoryMC.checklistBtn.addEventListener("mouseDown",onChecklistBtn,false,0,true);
_inventoryMC.certBtn.addEventListener("mouseDown",onCertBtn,false,0,true);
if(_petFormSwitch)
{
_petFormSwitch.addEventListener("mouseDown",onPetFormSwitch,false,0,true);
_petFormSwitch.addEventListener("rollOver",onPetFormSwitchOver,false,0,true);
_petFormSwitch.addEventListener("rollOut",onPetFormSwitchOut,false,0,true);
}
}
private function removeEventListeners() : void
@@ -866,6 +932,14 @@ package gui
_inventoryMC.salonBtn.removeEventListener("mouseDown",onSalonBtn);
_inventoryMC.checklistBtn.removeEventListener("mouseDown",onChecklistBtn);
_inventoryMC.certBtn.removeEventListener("mouseDown",onCertBtn);
if(_petFormSwitch)
{
_petFormSwitch.removeEventListener("mouseDown",onPetFormSwitch);
_petFormSwitch.removeEventListener("rollOver",onPetFormSwitchOver);
_petFormSwitch.removeEventListener("rollOut",onPetFormSwitchOut);
GuiManager.toolTip.resetTimerAndSetVisibility();
_petFormSwitch = null;
}
}
}
}
File diff suppressed because it is too large. Load diff
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff. Show more