├── .github └── workflows │ └── node.js.yml ├── .gitignore ├── LICENSE ├── README.md ├── beebjit-clapper-recording-fix.patch ├── beebjit.js ├── cache.js ├── client.js ├── docs └── user guide.md ├── hashtag.js ├── images ├── BASE2048.png ├── CHARACTERS.png ├── FRAME_CAPTURE.mp4 └── palette.png ├── install.sh ├── jsbeeb.js ├── mastodon.js ├── mastodon.json ├── output └── README.md ├── package-lock.json ├── package.json ├── parser.js ├── server.js ├── test.js ├── tools └── bbcbasictokenise └── tweetdisk.js /.github/workflows/node.js.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Node.js CI 5 | 6 | on: 7 | push: 8 | branches: [ master, mastodon ] 9 | pull_request: 10 | branches: [ master, mastodon ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | matrix: 19 | node-version: [12.x] 20 | 21 | steps: 22 | - uses: actions/checkout@v2 23 | - name: Use Node.js ${{ matrix.node-version }} 24 | uses: actions/setup-node@v1 25 | with: 26 | node-version: ${{ matrix.node-version }} 27 | - run: sudo apt-get update 28 | - run: sudo apt-get install -y ffmpeg 29 | - run: ln -s /usr/bin/ffmpeg . 30 | # Workaround for https://github.com/npm/cli/issues/2610 31 | - run: git config --global url."https://github.com/".insteadOf ssh://git@github.com 32 | - run: npm ci 33 | - run: npm run build --if-present 34 | - run: npm test --unhandled-rejections=strict 35 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | code 4 | certs 5 | tmp 6 | beebjit 7 | roms 8 | *.log 9 | npm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | ffmpeg* 14 | 15 | # Diagnostic reports (https://nodejs.org/api/report.html) 16 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 17 | 18 | # Runtime data 19 | pids 20 | *.pid 21 | *.seed 22 | *.pid.lock 23 | 24 | # Directory for instrumented libs generated by jscoverage/JSCover 25 | lib-cov 26 | 27 | # Coverage directory used by tools like istanbul 28 | coverage 29 | *.lcov 30 | 31 | # nyc test coverage 32 | .nyc_output 33 | 34 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 35 | .grunt 36 | 37 | # Bower dependency directory (https://bower.io/) 38 | bower_components 39 | 40 | # node-waf configuration 41 | .lock-wscript 42 | 43 | # Compiled binary addons (https://nodejs.org/api/addons.html) 44 | build/Release 45 | 46 | # Dependency directories 47 | node_modules/ 48 | jspm_packages/ 49 | 50 | # TypeScript v1 declaration files 51 | typings/ 52 | 53 | # TypeScript cache 54 | *.tsbuildinfo 55 | 56 | # Optional npm cache directory 57 | .npm 58 | 59 | # Optional eslint cache 60 | .eslintcache 61 | 62 | # Microbundle cache 63 | .rpt2_cache/ 64 | .rts2_cache_cjs/ 65 | .rts2_cache_es/ 66 | .rts2_cache_umd/ 67 | 68 | # Optional REPL history 69 | .node_repl_history 70 | 71 | # Output of 'npm pack' 72 | *.tgz 73 | 74 | # Yarn Integrity file 75 | .yarn-integrity 76 | 77 | # dotenv environment variables file 78 | .env 79 | .env.test 80 | 81 | # parcel-bundler cache (https://parceljs.org/) 82 | .cache 83 | 84 | # Next.js build output 85 | .next 86 | 87 | # Nuxt.js build / generate output 88 | .nuxt 89 | dist 90 | 91 | # Gatsby files 92 | .cache/ 93 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 94 | # https://nextjs.org/blog/next-9-1#public-directory-support 95 | # public 96 | 97 | # vuepress build output 98 | .vuepress/dist 99 | 100 | # Serverless directories 101 | .serverless/ 102 | 103 | # FuseBox cache 104 | .fusebox/ 105 | 106 | # DynamoDB Local files 107 | .dynamodb/ 108 | 109 | # TernJS port file 110 | .tern-port 111 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BBCMicroBot 2 | 3 | ![Node.js CI](https://github.com/8bitkick/BBCMicroBot/workflows/Node.js%20CI/badge.svg?branch=mastodon) 4 | 5 | A bot that runs toots that mention the #bbcmicrobot tag on a [BBC Micro emulator](https://github.com/scarybeasts/beebjit/) and responds with a toot of 3 second, 50fps video after 30 seconds of emulated execution time. 6 | 7 | ## Using the bot 8 | 9 | You can try the bot now live at [https://mastodon.me.uk/@bbcmicrobot](https://mastodon.me.uk/@bbcmicrobot) 10 | 11 | For help running code on the bot please see [the User Guide](https://github.com/8bitkick/BBCMicroBot/blob/master/docs/user%20guide.md). 12 | 13 | ## Background 14 | 15 | The [@bbcmicrobot](https://mastodon.me.uk/@bbcmicrobot) gained fans like comedian Dara Ó Briain, science writer Ben Goldacre, and Raspberry Pi founder Eben Upton. The concept is simple - make a retrocomputer accessible over social media. The bot runs any toot written in BBC BASIC (1982) a programming language developed by Sophie Wilson who later went on to create the ARM architecture. 16 | 17 | The Twitter community rose to the challenge with some seriously creative and clever code within 280 character limit. Read [more background on BBC Micro Bot here](https://www.dompajak.com/bbcmicrobot.html). 18 | 19 | It started a Twitter code bot revolution! There's a guide to building emulators in the cloud in the [Commodore 64 notes](https://github.com/8bitkick/c64bot) as well as full bot projects inspired by it including [Auto Tweetcart for the pico8](https://gitlab.com/rendello/auto_tweetcart) and Kay Savetz's AppleIIbot, PC BASIC Bot and [Atari8BitBot](https://github.com/savetz/Atari8BitBot). 20 | 21 | In November 2022 BBC Micro Bot was founded on Mastodon. 22 | 23 | https://mastodon.me.uk/@bbcmicrobot 24 | 25 | ## Contributing 26 | 27 | ### Running your own bot instance 28 | 29 | For development and testing you can run your own instance of the bot on a Linux machine. I've been running it on: 30 | 31 | * Arm-based AWS instances (Ubuntu) 32 | * Raspberry Pi 4 (Raspbian and Raspberry Pi OS) 33 | * Apple Mac OS X 34 | 35 | ### Installation 36 | 37 | * Install [Node.js v12.x](https://nodejs.org/en/download/) 38 | * Install [ffmpeg](https://www.ffmpeg.org/download.html) (e.g. `sudo apt install ffmpeg`) 39 | * Download or clone this BBCMicroBot repository and `cd` into the directory 40 | * `npm install` 41 | 42 | ### Local testing 43 | 44 | To run a set of test toots defined in [test.js](https://github.com/8bitkick/BBCMicroBot/blob/mastodon/test.js) and output the video or image capture to the `./tmp/` folder. For each test a checksum of the last frame of emulator video is compared against a known good value. To run the tests type: 45 | 46 | `npm test` 47 | 48 | You should see output like the following: 49 | 50 | ~~~ 51 | [14/06/2020 09:06:49 ] [LOG] Cli0: Running BASE2048 from @ 52 | [14/06/2020 09:06:49 ] [LOG] Cli0: Base 2048 decode 53 | [14/06/2020 09:06:49 ] [LOG] Cli0: Loading OS from roms/os.rom 54 | [14/06/2020 09:06:49 ] [LOG] Cli0: Loading ROM from roms/BASIC.ROM 55 | [14/06/2020 09:06:49 ] [LOG] Cli0: Loading ROM from roms/b/DFS-0.9.rom 56 | [14/06/2020 09:06:49 ] [LOG] Cli0: Loading ROM from roms/gxr.rom 57 | [14/06/2020 09:06:59 ] [LOG] Cli0: JSbeeb DONE in 9.807s 58 | [14/06/2020 09:07:01 ] [LOG] Cli0: JSbeeb captured 150 frames (1 unique) 59 | [14/06/2020 09:07:01 ] [LOG] Cli0: Ffmpeg DONE in 0.172s 60 | [14/06/2020 09:07:01 ] [LOG] Cli0: checksum: 80f830477fc1632c3f8a65702825f33b3d6c069e 61 | [14/06/2020 09:07:01 ] [LOG] Cli0: BASE2048 TEST - OK 62 | ~~~~ 63 | 64 | 65 | In the `tmp` folder you should also see the test output files. 66 | 67 | ### Interactive testing 68 | 69 | The `try` subcommand allows you to run a BASIC program from a file. If the bot would have posted a replied it instead runs `xdg-open` with the video or image output filename as an argument, which should open it in a suitable viewer: 70 | 71 | `node client try someprogram.bas` 72 | 73 | If you omit the filename, it defaults to reading from `stdin` which is handy for one-liners: 74 | 75 | `echo '0MO.4:REP.V.RND(2)*45+2:U.0'|node client try` 76 | 77 | ### Connecting to a Mastodon account 78 | 79 | You need to put the `ACCESS_TOKEN` for the Mastodon account for the bot and the `HASHTAG` that the bot should watch for in a `.env` file to be accessed by [mastodon.js](https://github.com/8bitkick/BBCMicroBot/blob/mastodon/mastodon.js#L8). 80 | 81 | You can then run the bot with 82 | 83 | `npm start` 84 | 85 | ### Thanks 86 | 87 | Thanks to Matt Godbolt for the JSBeeb emulator that made this project possible and to all the @bbcmicrobot users for their support - I hope this source code is interesting or useful. 88 | -------------------------------------------------------------------------------- /beebjit-clapper-recording-fix.patch: -------------------------------------------------------------------------------- 1 | diff --git a/video.c b/video.c 2 | index cb39b722..3f1c819b 100644 3 | --- a/video.c 4 | +++ b/video.c 5 | @@ -1259,12 +1259,12 @@ video_paint_timer_fired(void* p) { 6 | timing_get_total_timer_ticks(p_video->p_timing)); 7 | } 8 | 9 | + p_video->has_paint_timer_triggered = 1; 10 | if (!p_video->externally_clocked) { 11 | /* For accurate mode, this triggers the start of painting, and paint will 12 | * occur at the usual 50Hz virtual time. 13 | */ 14 | if (timing_timer_is_running(p_timing, timer_id)) { 15 | - p_video->has_paint_timer_triggered = 1; 16 | video_wall_time_vsync_hit(p_video); 17 | /* A bunch of unconsumed framing changes will have built up. Clear the 18 | * the flag so the screen isn't immediately cleared after the first paint. 19 | -------------------------------------------------------------------------------- /beebjit.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | 3 | const MemStart = 0x0000; 4 | const MemLength = 0x8000; // 32K RAM 5 | 6 | function exec(cmd) { 7 | const exec = require('child_process').exec; 8 | return new Promise((resolve, reject) => { 9 | exec(cmd, (error, stdout, stderr) => { 10 | if (error) { 11 | console.warn(error); 12 | } 13 | resolve(stdout? stdout.trim() : stderr); 14 | }); 15 | }); 16 | } 17 | 18 | async function beebjit(c, jsbeeb){ 19 | 20 | // Run tweet on emulator 21 | var tokenised; 22 | try { 23 | let basic = c.input; 24 | let tmp = basic.replace(/\#\w+/g, "").trim(); // get rid of tags and white space 25 | if (tmp.match(/^\d/) != null) { 26 | // If there are line numbers remove a trailing explicit "RUN". 27 | basic = basic.replace(/\n\s*RUN[\s\n]*$/, ""); 28 | } 29 | 30 | console.log(basic) 31 | tokenised = await jsbeeb.tokenise(basic); 32 | await fs.writeFileSync("./tmp/tweet.bas",tokenised,{encoding:"binary"}); 33 | await fs.writeFileSync("./tmp/keys.bin","RUN\r",{encoding:"binary"}); 34 | 35 | let keyboardBuffer = "03e0"; // BBC Micro OS 1.20 36 | let IBP = 0x02E1; // input pointer 37 | let OBP = 0x02D8; // output pointer 38 | 39 | let page = ( c.flags.includes("gxr.rom") ) ? "1c00" : "1900"; 40 | let end = parseInt(page,16) + tokenised.length; 41 | let endLow = (end & 0xff).toString(16); 42 | let endHigh = ((end >>> 8) & 0xff).toString(16); 43 | 44 | // beebjit debug commands 45 | let commands = "'"+ 46 | ["breakat 725000", 47 | "c", 48 | "loadmem ../tmp/tweet.bas "+page, // paste tokenised program into PAGE 49 | "loadmem ../tmp/keys.bin "+keyboardBuffer, // 0x03E0 OS 1.2 50 | "writem 02e1 e4", // Advance pointer 4 bytes 51 | "writem 0000 "+endLow, // LOWMEM 52 | "writem 0001 "+endHigh, 53 | "writem 0002 "+endLow, // VARTOP 54 | "writem 0003 "+endHigh, 55 | "writem 0012 "+endLow, // TOP 56 | "writem 0013 "+endHigh, 57 | "breakat "+c.cycles, // after emulated cycles 58 | "c", 59 | "r", 60 | "crtc", 61 | "bbc", 62 | `savemem ../tmp/savemem.bin ${MemStart.toString(16)} ${MemLength.toString(16)}`, // BBC Micro memory dump 63 | "c" 64 | ].join(";")+"'"; 65 | 66 | 67 | let beebjit_cmd = "cd beebjit && ./beebjit -fast -headless -frames-dir ../tmp/ -cycles "+(c.cycles*2)+" "+c.flags+" -opt video:hack-legacy-shift-mode7 -commands "+commands; 68 | let stdout = await exec(beebjit_cmd ); 69 | console.log(beebjit_cmd,stdout); 70 | let state = await parseBeebjitState(stdout); 71 | return state; 72 | 73 | 74 | } catch (e) { 75 | console.log("Tokenisation FAILED"); 76 | console.log(e); 77 | return null; 78 | } 79 | } 80 | 81 | 82 | // Parse Beebjit state dump 83 | async function parseBeebjitState(stdout){ 84 | let regdump = stdout.match(/A=(.+) X=(.+) Y=(.+) S=(.+) F=(.+) PC=(.+) cycles/i); 85 | let crtcregs = stdout.match(/R\d\d \$([0-9A-Fa-f]{2})/mg).map(r => parseInt(r.substring(5,7),16)); 86 | let registers = { 87 | A:parseInt(regdump[1],16), 88 | X:parseInt(regdump[2],16), 89 | Y:parseInt(regdump[3],16), 90 | S:parseInt(regdump[4],16), 91 | F:regdump[5], 92 | PC:parseInt(regdump[6],16) 93 | } 94 | 95 | let ulaControl = parseInt(stdout.match(/ULA control \$(.+)/i)[1],16); 96 | let ulaPalette = stdout.match(/ULA palette \$(\S+) \$(\S+) \$(\S+) \$(\S+) \$(\S+) \$(\S+) \$(\S+) \$(\S+) \$(\S+) \$(\S+) \$(\S+) \$(\S+) \$(\S+) \$(\S+) \$(\S+) \$(\S+)/i).slice(1,17).map(a => parseInt(a,16)); 97 | let mem = await fs.readFileSync("./tmp/savemem.bin"); 98 | 99 | let state = { 100 | "RAM": mem.toString('base64'), 101 | "address": MemStart.toString(16), 102 | "CPU6502": registers, 103 | "CRTC": crtcregs, 104 | "ULAcontrol": ulaControl, 105 | "ULApalette": ulaPalette 106 | }; 107 | 108 | return state; // full BBC Micro state snapshot 109 | } 110 | 111 | module.exports = beebjit; 112 | -------------------------------------------------------------------------------- /cache.js: -------------------------------------------------------------------------------- 1 | 2 | const BotGenesis = 1569394800; // First ever bot tweet 25 Sep 2019 3 | const AWS = require('aws-sdk'); 4 | require('dotenv').config(); 5 | const s3 = new AWS.S3(); 6 | const cloudfront = new AWS.CloudFront(); 7 | 8 | async function cache(toot, beebState){ 9 | 10 | // Were assuming single thread sequential URL generation here... 11 | let num = Math.floor(Date.now()/1000) - 1569394800; 12 | let digits = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 13 | let len = Math.min(digits.length, 62); 14 | let tag = ''; 15 | while (num > 0) { 16 | tag = digits[num % len] + tag; 17 | num = parseInt(num / len, 10); 18 | } 19 | 20 | 21 | let body = { 22 | 'v': 3, 23 | 'toot': toot.prog, 24 | 'mode': toot.mode, 25 | 'src': toot.src, 26 | 'state': beebState, 27 | 'title': toot.title, 28 | } 29 | 30 | const params = { 31 | Bucket: "bbcmic.ro", 32 | Key: 'state/'+tag, 33 | Body: JSON.stringify(body), 34 | ACL:'public-read', 35 | ContentType: 'application/json' 36 | }; 37 | // Uploading files to the bucket 38 | await s3.upload(params).promise(); 39 | console.log("Cache: bbcmic.ro/state/"+tag); 40 | 41 | // load index.txt from S3, append tag, upload back to S3 42 | let index = await s3.getObject({Bucket: "bbcmic.ro", Key: 'state/index.txt'}).promise(); 43 | index = index.Body.toString('utf-8'); 44 | index += tag+"\n"; 45 | params.Key = 'state/index.txt'; 46 | params.Body = index; 47 | await s3.upload(params).promise(); 48 | 49 | await invalidateCloudFront(params.Key); 50 | 51 | return tag; 52 | } 53 | 54 | async function invalidateCloudFront(fileKey) { 55 | const distributionId = process.env.CLOUDFRONT; 56 | 57 | const params = { 58 | DistributionId: distributionId, 59 | InvalidationBatch: { 60 | CallerReference: Date.now().toString(), 61 | Paths: { 62 | Quantity: 1, 63 | Items: [`/${fileKey}`] 64 | } 65 | } 66 | }; 67 | 68 | await cloudfront.createInvalidation(params).promise(); 69 | console.log(`CloudFront invalidation created for ${fileKey}`); 70 | } 71 | 72 | module.exports = cache; 73 | -------------------------------------------------------------------------------- /client.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | require('dotenv').config(); 3 | const PORT = process.env.PORT || 6502; 4 | const HOST = process.env.SERVER || 'localhost' 5 | var POLL_DELAY = process.env.POLL_DELAY || 5000 6 | 7 | const TEST = (process.argv.indexOf("test") > -1) 8 | const TRY = (process.argv.indexOf("try") > -1) 9 | POLL_DELAY = TEST ? 0 : POLL_DELAY ; 10 | 11 | const emulationDuration = 33; // seconds 12 | const startFrame = 1587; // frames (50fps when vsync active) 13 | 14 | const fs = require('fs'); 15 | const requirejs = require('requirejs'); // for jsbeeb compatibility 16 | const https = require('https'); 17 | const cert_path = "./certs/"; 18 | const parser = require('./parser'); 19 | const gifsicle = require('gifsicle'); 20 | const beebjit = require('./beebjit'); 21 | const cache = require('./cache'); 22 | 23 | let beebState = null; 24 | 25 | var mastodon = TRY ? null : require(TEST ? './test' : './mastodon'); 26 | 27 | var tweetServer = { 28 | hostname: HOST, 29 | port: PORT, 30 | method: 'GET', 31 | key: fs.readFileSync(cert_path+'client_key.pem'), 32 | cert: fs.readFileSync(cert_path+'client_cert.pem'), 33 | ca: fs.readFileSync(cert_path+'server_cert.pem') 34 | }; 35 | 36 | function exec(cmd) { 37 | const exec = require('child_process').exec; 38 | return new Promise((resolve, reject) => { 39 | exec(cmd, (error, stdout, stderr) => { 40 | if (error) { 41 | console.warn(error); 42 | } 43 | resolve(stdout? stdout.trim() : stderr); 44 | }); 45 | }); 46 | } 47 | 48 | 49 | function log(l){console.log(l);} 50 | 51 | var clientID = "Cli0"; 52 | 53 | require( 'console-stamp' )( console, { pattern: 'dd/mm/yyyy HH:MM:ss '},clientID+":" ); 54 | 55 | requirejs.config({ 56 | baseUrl: "./node_modules/jsbeeb/", 57 | paths: { 58 | 'jsunzip': 'lib/jsunzip', 59 | 'promise': 'lib/promise-6.0.0', 60 | 'underscore': 'lib/underscore-min', 61 | 'emulator':'../../jsbeeb' 62 | } 63 | }); 64 | 65 | requirejs(['emulator'], 66 | function (jsbeeb) { 67 | "use strict"; 68 | 69 | async function run(tweet){ 70 | // Tweet ID will be used in tmp filenames passed into shell exec, so check it's safe. For a real tweet it should be numeric while for a testcase it can contain alphanumerics. 71 | if (/\W/.test(tweet.id)) { 72 | console.error("id contained unexpected character"); 73 | process.exit(1); 74 | } 75 | 76 | console.log(""); 77 | console.log("Running "+tweet.id+" from "+tweet.account.url); 78 | 79 | var c = parser.parseTweet(tweet); 80 | 81 | console.log("Parser output",c); 82 | 83 | // If rude, block the user and do not run the program 84 | if (c.rude) { 85 | console.warn("BLOCKED @"+tweet.user.screen_name) 86 | await mastodon.block(tweet); 87 | setTimeout(requestTweet, POLL_DELAY); 88 | return; 89 | } 90 | 91 | let start = new Date() 92 | let media_path = "./tmp/"+tweet.id; 93 | 94 | // Emulate on Beebjit 95 | if (c.emulator == "beebjit") { 96 | 97 | var frame_path = "./tmp/beebjit_frame_"; 98 | var audio_file = null; 99 | var pixel_format = "bgra"; 100 | var emu_name = "beebjit"; 101 | 102 | beebState = await beebjit(c, jsbeeb); 103 | if (beebState === null) setTimeout(requestTweet, POLL_DELAY); 104 | 105 | } else // JSbeeb 106 | { 107 | var frame_path = media_path + "frame"; 108 | audio_file = media_path + "audiotrack.raw"; 109 | var pixel_format = "rgba"; 110 | var emu_name = "jsbeeb"; 111 | var frames = await jsbeeb.emulate(c.input,frame_path,audio_file,emulationDuration,startFrame); 112 | if (!fs.existsSync(audio_file)) audio_file = null; 113 | } 114 | 115 | var end = new Date() - start 116 | console.log(emu_name+" DONE in %ds ",end/1000); 117 | 118 | // Count unique video frames 119 | var shasum_check = (await exec("sha1sum client.js | awk '{print $1}' | wc -l")); // should equal 1 120 | var shasum = (shasum_check > 0) ? "sha1sum" : "shasum"; 121 | var frames = (await exec(shasum+" "+frame_path+"*."+pixel_format+" | awk '{print $1}' | wc -l")); 122 | var uniqueFrames = (await exec(shasum+" "+frame_path+"*."+pixel_format+" | awk '{print $1}' | sort | uniq | wc -l")); 123 | 124 | console.log("Captured "+frames+" frames ("+uniqueFrames+" unique) "+frame_path); 125 | 126 | start = new Date(); 127 | 128 | if (frames == 0) { 129 | // NO VIDEO -> NOTHING 130 | var ffmpegCmd = ""; 131 | } else if (uniqueFrames==1 && audio_file === null) { 132 | // STATIC IMAGE WITHOUT SOUND -> PNG SCREENSHOT 133 | var mediaFilename = media_path+'.png'; 134 | var mediaType = 'image/png'; 135 | var ffmpegCmd = './ffmpeg -hide_banner -y -f rawvideo -pixel_format '+pixel_format+' -video_size 640x512 -i '+frame_path+(frames-1)+'.'+pixel_format+' -vf "scale=1280:1024" '+mediaFilename 136 | 137 | } else { 138 | // ANIMATION OR STATIC IMAGE WITH SOUND -> GIF 139 | var mediaFilename = media_path+'.gif'; 140 | var mediaType = 'image/gif'; 141 | var ffmpegCmd = './ffmpeg -hide_banner -loglevel panic '; 142 | if (audio_file !== null) { 143 | ffmpegCmd = ffmpegCmd + '-f f32le -ar 44100 -ac 1 -i '+audio_file; 144 | } 145 | ffmpegCmd = ffmpegCmd + '-y -f image2 -r 50 -s 640x512 -pix_fmt '+pixel_format+' -vcodec rawvideo -i '+frame_path+'%d.'+pixel_format+' -i images/palette.png -filter_complex "[0:v][1:v] paletteuse" -af "highpass=f=50, lowpass=f=15000,volume=0.5" -b:v 8M -b:a 128k -strict -2 -shortest '+mediaFilename 146 | } 147 | 148 | if (frames > 0) { 149 | await exec(ffmpegCmd); 150 | var checksum = await exec(shasum+" "+frame_path+(frames-1)+'.'+pixel_format+" | awk '{print $1}'"); 151 | } else { 152 | var checksum = ''; 153 | } 154 | 155 | exec('rm -f '+frame_path+'*.'+pixel_format); 156 | 157 | if (audio_file !== null) { 158 | fs.unlinkSync(audio_file); 159 | } 160 | if (frames > 1) { 161 | var output = await exec ("gifsicle "+mediaFilename+" --optimize=3 --colors=16 --output "+mediaFilename); 162 | console.log("Gifsicle:"+output); 163 | } 164 | 165 | var end = new Date() - start 166 | console.log("Ffmpeg DONE in %ds ",end/1000); 167 | 168 | if (frames == 0) { 169 | mastodon.noOutput(tweet); 170 | } else { 171 | var hasAudio = (audio_file !== null); 172 | 173 | let title = tweet.spoiler_text || "Untitled"; 174 | // Summarize toot data 175 | let tootData = { 176 | "prog":c.input, 177 | "mode":c.mode, 178 | "src": tweet.url, 179 | "title": title 180 | }; 181 | 182 | // Save state to cache 183 | let tag = (TEST || TRY) ? "test" : await cache(tootData, beebState); 184 | 185 | // Post a video toot 186 | mastodon.videoReply(mediaFilename,mediaType,tweet.id,"@"+tweet.account.acct,tweet,checksum,hasAudio,tag); 187 | } 188 | 189 | setTimeout(requestTweet, POLL_DELAY); 190 | }; 191 | 192 | function requestTweet() { 193 | tweetServer.path="/pop"; 194 | https.get(tweetServer, (resp) => { 195 | let data = ''; 196 | resp.setEncoding('utf8'); 197 | resp.on('data', (chunk) => { 198 | data += chunk; 199 | }); 200 | // The whole response has been received. Print out the result. 201 | resp.on('end', () => { 202 | var tweet = JSON.parse(data); 203 | if (typeof tweet.text === 'undefined') { 204 | setTimeout(requestTweet, 5000); 205 | return; 206 | 207 | } else { 208 | if (TEST && tweet.text == null) {process.exit()}; 209 | run(tweet).catch((err) => { 210 | console.error(err); 211 | if (TEST) { 212 | tweetServer.path="/quit"; 213 | https.get(tweetServer); 214 | process.exit(1); 215 | } 216 | }); 217 | } 218 | }); 219 | }).on("error", (err) => { 220 | log("Error: " + err.message); 221 | log('Retry in 5 seconds'); 222 | setTimeout(requestTweet, 5000); 223 | }); 224 | } 225 | 226 | var try_arg = process.argv.indexOf("try") + 1; 227 | if (try_arg > 0) { 228 | var try_file = (try_arg == process.argv.length) ? "/dev/stdin" : process.argv[try_arg]; 229 | var toot = { 230 | text: fs.readFileSync(try_file, 'utf8'), 231 | id: 'try', 232 | user: { screen_name: 'try' }, 233 | account: { username: 'try', url: 'https://localhost/@try' } 234 | }; 235 | // Set up mastodon object to mock the methods that we use. 236 | mastodon = {}; 237 | mastodon.videoReply = function(filename,mediaType,replyTo,text,toot,checksum,hasAudio) { 238 | console.log("Generated " + mediaType); 239 | exec("xdg-open "+filename); 240 | process.exit(); 241 | }; 242 | mastodon.block = function(toot) { 243 | console.log("Failed: Toot blocked because of badwords"); 244 | process.exit(1); 245 | }; 246 | mastodon.noOutput = function(toot) { 247 | console.log("Failed: No output captured"); 248 | process.exit(1); 249 | }; 250 | run(toot); 251 | } else { 252 | requestTweet(); 253 | } 254 | } 255 | ); 256 | -------------------------------------------------------------------------------- /docs/user guide.md: -------------------------------------------------------------------------------- 1 | # BBC Micro Bot User Guide 2 | 3 | This guide will outline how BBC Micro Bot works on Mastodon and provide some tricks to reduce the size of your code (so that it can fit in a toot) with the [Owlet Editor](https://bbcmic.ro). 4 | 5 | ## Prerequisites 6 | 7 | Before reading below check this awesome [interactive BBC BASIC tutorial](https://www.bbcmicrobot.com/learn/index.html) first if you aren’t familiar or want a refresher. The guide below is more about using the bot and how to minify code rather than covering the BBC BASIC language. 8 | 9 | ## How to run your code 10 | 11 | When you include [#bbcmicrobot](https://mastodon.me.uk/@bbcmicrobot) in a toot the bot will run your toot as code on a BBC Micro emulator. Your code must fit within a single toot, limited to 500 characters by its home instance. 12 | 13 | ### Default 14 | 15 | Normally the bot runs your code for 30 seconds, and then takes 3 second video clip that it posts to Mastodon. If that final 3 seconds is a static image, the bot will reply with a PNG image instead. 16 | 17 | ### Emoji commands 18 | 19 | You can add an emoji to the end of your toot to send a command to the bot. These are not included in the program sent to the BBC Micro emulator, and should not be in your code in Owlet. Because the [emulator is very fast](https://github.com/scarybeasts/beebjit) a 3 hour emulation only takes a few seconds. Although the emulation is fast, the video capture at the end is real-time - the 🎬 is the same as leaving a real BBC Micro running for 3 hours and then afterwards taking a look at the screen for 3 seconds. 20 | 21 | 22 | Bot execution modes 23 | 24 | | Emoji | Pre render | GXR | Output. | 25 | | ----------- | ----------- | ----| ----------- | 26 | | None | 30 sec | Yes | 3 sec video | 27 | | 🎬 | 3 hours* | No | 3 sec video | 28 | | 🚀 | 3 hours* | No | screen shot | 29 | 30 | 31 | \* The bot runs 3 hours equivalent 6502 execution in just a few seconds thanks to Beebjit! 32 | 33 | ### Unexpected behavior with 🎬 mode animations 34 | 35 | We use the beebjit `-fast` parameter to achieve very fast emulation in the accelerated modes, the only downside being some unexpected 'relativistic' effects if your code relies on external timers. In this mode CPU time is accelerated several thousandfold and decoupled from timing of BBC Micro peripherals and timers which remain emulated in real-time. This means flashing colours in the palette, and `*FX 19` or `INKEY` based timing will not work well! 36 | 37 | If your code waits for an external timer based event like VSYNC the video will appear to freeze. It's recommended to use `FOR ... NEXT` loop based delays in code you intend to run with 🎬 mode for that reason. The emulator takes a screenshot every 40,000 emulated 6502 cycles (which is the same period as VSYNC) and so resulting animation will still look [pretty much the same on a real machine](https://twitter.com/bbcmicrobot/status/1356755101587697669?s=20). 38 | 39 | 40 | ## Etiquette 41 | 42 | If you copy or modify someone's code you should either reply to the original toot so people can see the thread, or acknowledge the author in your toot. When you toot at the bot your code is public. You might find that other users are inspired to help reduce the size of your code, improve the design or remix it - you should take this as a compliment! 43 | 44 | BBC Micro Bot is a place to write fun code and help each other out doing it. Toots containing any bad words will be ignored and the user account blocked. This is automatic and on quite a strict filter. 45 | 46 | # Writing code in a toot 47 | 48 | The [Owlet Editor](https://bbcmic.ro) is designed specifically for creative coding with BBC Micro Bot. 49 | 50 | ## Reducing code size 51 | 52 | One of the fun and challenging aspects of the bot is you need to squeeze your code down in size - code golf! Techniques to do this have evolved over time, many pioneered by [Rheolism](https://oldbytes.space/@rheolism). Here we outline some fundamental approaches, this is by no means comprehensive. 53 | 54 | ``` 55 | 10 PRINT "HELLO WORLD" 56 | 20 GOTO 10 57 | ``` 58 | 59 | 60 | ### Removing line numbers and spaces 61 | 62 | You do not need line numbers in your code. The numbers are automatically added in increments of 10 by the bot. As a guide, Owlet will show you the line numbers in the gutter of the editor if you omit them from your code. Spaces are usually removable, but are required in some cases where a variable name is directly next to a BASIC keyword. 63 | 64 | ``` 65 | PRINT"HELLO WORLD" 66 | GOTO10 67 | ``` 68 | 69 | ### Abbreviations 70 | 71 | BBC BASIC keywords can also be abbreviated. Abbreviations have the advantage that they are still somewhat readable. However they are not as small as byte tokens. For example `PRINT` can become `P.` and `GOTO` can become `G.`. You can find a list of minimum abbreviations [here](https://central.kaserver5.org/Kasoft/Typeset/BBC/Ch47.html). Using the [Owlet Editor](https://bbcmic.ro) you can expand any abbreviation to the full keyword using the `expand` button. 72 | 73 | ``` 74 | P."HELLO WORLD" 75 | G.10 76 | ``` 77 | 78 | ### BBC BASIC byte tokens 79 | 80 | As with the original implementation each BBC BASIC keyword is represented in memory as a single byte. We can use these byte tokens directly in toots to save characters. You can quickly do the conversion in the [Owlet Editor](https://bbcmic.ro) using the `Shrink` button (so you don't need to worry about learning the [values of byte tokens](http://www.benryves.com/bin/bbcbasic/manual/Appendix_Tokeniser.htm)). The `PRINT` keyword shrinks to byte token 0xF1. This is represented in a toot as Unicode U+00F1 which is `ñ`. 81 | 82 | ``` 83 | ñ"HELLO WORLD" 84 | å10 85 | ``` 86 | 87 | Note that some byte values must be ORed with 0x100 in order to map to a valid Unicode character that can be used in the editor or in a tweet. For byte tokens this is done automatically in Owlet, and the BBC Micro emulator ANDs all character codepoints with 0xFF to return them to single byte values. 88 | 89 | 90 | ### base2048 encoding [deprecated for Mastodon due to larger post length] 91 | 92 | [Base2048](https://github.com/qntm/base2048) is a Unicode encoding optimized for transmitting binary data through Twitter. Using base2048 allowed an extra 100 characters of BBC BASIC code in a tweet, bringing the total to ~384 characters. However our Hello World tweet would no longer be human readable: 93 | 94 | ``` 95 | ༣Ȝǁঐ౭चؼ๗ԪʢࠁನȤ3 96 | ``` 97 | 98 | For this reason and because the Mastodon bot supports 512 characters we no longer support base2048. 99 | 100 | ## Advanced minification techniques 101 | 102 | ### VDU and graphics commands 103 | 104 | VDU commands are powerful in BBC BASIC. One of their many uses is to change the colors assigned in the current palette: 105 | 106 | ``` 107 | VDU 19,1,4,0,0,0 108 | VDU 19,2,6,0,0,0 109 | ``` 110 | Instead of declaring the values in a `VDU` statement you can instead `PRINT` the byte values and they will be executed by the VDU driver with an identical result. There's a handy [online tool to convert VDU calls to strings](https://8bitkick.github.io/vdu/). The VDU calls above would become: 111 | ``` 112 | PRINT"ēāĄĀĀĀēĂĆĀĀĀ" 113 | ``` 114 | Note that graphics commands (e.g. `GCOL` and `PLOT`) can also be expressed as VDU commands as shown in the [table on the conversion page](https://8bitkick.github.io/vdu/). This mean complex graphics sequences can be run using a single `PRINT` command! This can save a lot of characters. 115 | 116 | ### Inline binary data 117 | 118 | Using the BASIC `DATA` and `READ` keywords to store data can quickly become large. It's possible to store byte data directly into a `REM` statement to be read out by the BBC BASIC peek command `?`. The address of the data is calculated as a 5 byte offset from the start of the BASIC program memory defined in `PAGE` 119 | 120 | ``` 121 | REMthis statement is my data 122 | D=PAGE+5 123 | FOR A=0 TO 24 124 | PRINT D?A 125 | NEXT 126 | ``` 127 | 128 | In this example the first value returned would be 116, the ASCII value for the letter `t`. You can create a Mastodon-friendly byte string to use in a `REM` from comma separated data with the [VDU to string tool](https://8bitkick.github.io/vdu/) 129 | -------------------------------------------------------------------------------- /hashtag.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | 4 | const log = require('npmlog'); 5 | log.level = process.env.LOG_LEVEL || 'verbose'; 6 | const fs = require('fs'); 7 | 8 | const Mastodon = require('mastodon'); 9 | require('dotenv').config(); 10 | const config = { 11 | access_token: process.env.ACCESS_TOKEN, 12 | api_url: `https://${process.env.API_HOST}/api/v1/`, 13 | hashtag: process.env.HASHTAG, 14 | }; 15 | const client = new Mastodon(config); 16 | 17 | log.info("BBC Micro Bot mastodon edition"); 18 | log.info(`Running on: ${process.env.API_HOST} #${config.hashtag}`); 19 | 20 | 21 | // Monitor timeline {timeline 22 | class Timeline { 23 | constructor() { 24 | this.queue = []; // list of mention statuses 25 | } 26 | 27 | 28 | async update() { 29 | log.info("Queue length :"+this.queue.length) 30 | if (this.queue.length>0) return 31 | //console.log(`${config.api_url}timelines/public/?access_token=${config.access_token}&tag=${config.hashtag}`) 32 | const response = (await client.get('/timelines/tag/:hashtag',{'hashtag':`${config.hashtag}`})).data; 33 | 34 | // List all tagged posts 35 | for (var i = 0; i < response.length; i++) { 36 | // Remove those we've already liked 37 | if (response[i].favourited !== true) { 38 | response[i].text = response[i].content;//.replace(/<[^>]*>?/gm, '');
39 | console.log(response[i].id,"@"+response[i].account.username+" tagged #bbcmicrobot"); 40 | this.queue.push(response[i]); 41 | } 42 | } 43 | } 44 | 45 | } 46 | 47 | 48 | 49 | module.exports = Timeline; 50 | -------------------------------------------------------------------------------- /images/BASE2048.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/8bitkick/BBCMicroBot/a74a25010f55aac98a87504d7fc1fb2bc0b3f818/images/BASE2048.png -------------------------------------------------------------------------------- /images/CHARACTERS.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/8bitkick/BBCMicroBot/a74a25010f55aac98a87504d7fc1fb2bc0b3f818/images/CHARACTERS.png -------------------------------------------------------------------------------- /images/FRAME_CAPTURE.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/8bitkick/BBCMicroBot/a74a25010f55aac98a87504d7fc1fb2bc0b3f818/images/FRAME_CAPTURE.mp4 -------------------------------------------------------------------------------- /images/palette.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/8bitkick/BBCMicroBot/a74a25010f55aac98a87504d7fc1fb2bc0b3f818/images/palette.png -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -euo pipefail 4 | 5 | echo 6 | echo Installing BBC Micro Bot 7 | echo ------------------------ 8 | 9 | echo Building beebjit 10 | ##################### 11 | # TODO once the error in issue 45 is fixed this could just be a git submodule... 12 | if [ ! -d beebjit ]; then 13 | git clone https://github.com/scarybeasts/beebjit.git 14 | fi 15 | pushd beebjit 16 | git fetch 17 | git reset --hard 18 | git checkout 327ab3d8caa2c1db8b7073535a28bb1174cf6644 19 | # Fix for https://github.com/scarybeasts/beebjit/issues/49 20 | patch -p1 < ../beebjit-clapper-recording-fix.patch 21 | # if scarybeasts used Makefiles we could save a compile & link every time... 22 | ./build_headless_opt.sh 23 | popd 24 | 25 | echo Getting GXR ROM 26 | ln -sf ./node_modules/jsbeeb/roms/ roms 27 | test -f roms/gxr.rom || curl -sL https://mdfs.net/System/ROMs/Graphics/GXR120 -o roms/gxr.rom 28 | cp roms/gxr.rom beebjit/roms/ 29 | 30 | echo Creating directories 31 | ######################## 32 | mkdir -p tmp 33 | mkdir -p certs 34 | 35 | echo Generating certificates 36 | ############################ 37 | 38 | pushd certs 39 | test -f server_cert.pem || openssl req -x509 -newkey rsa:4096 -keyout server_key.pem -out server_cert.pem -nodes -days 365 -subj "/CN=localhost/O=BBC\ Micro\ Bot" 40 | test -f client_csr.pem || openssl req -newkey rsa:4096 -keyout client_key.pem -out client_csr.pem -nodes -subj "/CN=Emulator Client" 41 | test -f client_cert.pem || openssl x509 -req -in client_csr.pem -CA server_cert.pem -CAkey server_key.pem -out client_cert.pem -set_serial 01 -days 365 42 | chmod og-rwx * 43 | popd 44 | -------------------------------------------------------------------------------- /jsbeeb.js: -------------------------------------------------------------------------------- 1 | 2 | // This code calls JSBeeb emulator functions directly 3 | 4 | define(['6502', 'video', 'soundchip', 'models', 'ddnoise', 'cmos', 'utils','fdc','basic-tokenise'], 5 | function (Cpu6502, Video, SoundChip, models, DdNoise, Cmos, utils,fdc,tokeniser) { 6 | 7 | const fs = require('fs'); 8 | 9 | var video, processor, cycles; 10 | var thisEmulator = null; 11 | var MaxCyclesPerIter = 100 * 1000; 12 | var hexword = utils.hexword; 13 | 14 | var model = models.findModel('B'); 15 | model.os.push('gxr.rom'); // Add GXR ROM 16 | 17 | var keyboardBuffer = 0x0300; // BBC Micro OS 1.20 18 | var IBP = 0x02E1; // input pointer 19 | var OBP = 0x02D8; // output pointer 20 | 21 | var screenMode = 0x0355; // Current screen mode. 22 | 23 | async function tokenise(input) { 24 | return await tokeniser.create().then(function (t) { 25 | return t.tokenise(input); 26 | }); 27 | } 28 | 29 | async function emulate(input,frame_path,audio_file,duration,capture_start) { 30 | 31 | var frameBuffer32 = new Uint32Array(1024 * 625); 32 | var soundBuffer = new Float32Array(44100 * duration).fill(0); 33 | var soundPoint = 0; 34 | var frame = 0; 35 | var soundChip = new SoundChip.SoundChip(44100); 36 | var dbgr = { 37 | setCpu: function () { 38 | } 39 | }; 40 | 41 | // Set up video and sound capture 42 | video = new Video.Video(false, frameBuffer32, function paint(minx, miny, maxx, maxy) { 43 | if (frame > capture_start){ 44 | soundChip.render(soundBuffer, soundPoint, 882); // 44100Hz / 50fps = 882 45 | soundPoint = soundPoint + 882; 46 | 47 | var mode = processor.readmem(screenMode); 48 | var fd = fs.openSync(frame_path+(frame-capture_start)+'.rgba', 'w'); 49 | // frameBuffer32 includes the frame border. The area where the image is 50 | // varies a little by screen mode - it's always 640 pixels wide (i.e. 2560 51 | // bytes since each pixel is 4 bytes) but in mode 7 it is offset to the 52 | // right by 16 pixels (64 bytes), which we compensate for below. 53 | // 54 | // In modes 3,6,7 the screen is a little shorter, but we just crop to the 55 | // tallest height it can be since this works better when there's a mode 56 | // switch mid-video. 57 | 58 | // Top-left of screen. 59 | var off = 262944; 60 | // Bottom-right of screen. 61 | var end = 2358556; 62 | switch (mode) { 63 | case 3: case 6: 64 | // This includes the "stripe" below the bottom line of the screen. 65 | end = 2309468; break; 66 | case 7: 67 | off = 263008; end = 2309468; break; 68 | } 69 | while (off <= 2358556) { 70 | if ((mode == 3 || mode == 6) && off < end) { 71 | // The "stripes" have alpha = 0, but we want to make them 72 | // non-transparent so that an image output looks better on 73 | // a non-black background. 74 | var start = off / 4; 75 | 76 | for (var i = 0; i != 1024; ++i) { 77 | if (frameBuffer32[start + i] != 0) 78 | break; 79 | frameBuffer32[start + i] = 0xff000000; 80 | } 81 | } 82 | fs.writeSync(fd, frameBuffer32, off, 2560); 83 | off += 4096; 84 | } 85 | fs.closeSync(fd); 86 | } 87 | frame++;}); 88 | 89 | // Set up our BBC Micro emulator 90 | processor = new Cpu6502(model, dbgr, video, soundChip, new DdNoise.FakeDdNoise(), new Cmos()); 91 | await processor.initialise(); 92 | await runUntilInput(); 93 | 94 | // Use the tokeniser if the program contains non-ASCII characters or if 95 | // it doesn't have any line numbers. 96 | if (/[^\0-\x7e]/.test(input) || !/^ *[0-9]/m.test(input)) { 97 | /* Tokeniser input method */ 98 | var tokenised; 99 | try { 100 | tokenised = await tokenise(input); 101 | } 102 | catch (e) { 103 | console.log("Tokenisation FAILED"); 104 | console.log(e); 105 | return 0; 106 | } 107 | 108 | var page = processor.readmem(0x18) << 8; 109 | for (var i = 0; i < tokenised.length; ++i) { 110 | processor.writemem(page + i, tokenised.charCodeAt(i)); 111 | } 112 | var end = page + tokenised.length; 113 | var endLow = end & 0xff; 114 | var endHigh = (end >>> 8) & 0xff; 115 | // Set LOMEM. 116 | processor.writemem(0x00, endLow); 117 | processor.writemem(0x01, endHigh); 118 | // Set VARTOP. 119 | processor.writemem(0x02, endLow); 120 | processor.writemem(0x03, endHigh); 121 | // Set TOP. 122 | processor.writemem(0x12, endLow); 123 | processor.writemem(0x13, endHigh); 124 | 125 | input="RUN\r"; 126 | } else { 127 | input=input.replace(/[\n]/g,'\r'); 128 | if (!input.endsWith('\r')) { 129 | input=input+'\r'; 130 | } 131 | if (!/\r\s*RUN\s*\r/.test(input)) { 132 | input=input+"RUN\r"; 133 | } 134 | } 135 | 136 | await pasteToBuffer(input); 137 | await runFor((2000000*duration)-15000*(input.length)); 138 | 139 | // Check if the soundBuffer has any non-zero values. 140 | if (soundBuffer.some(function(elt, idx, a) { return elt != 0; })) { 141 | await fs.writeFileSync(audio_file, soundBuffer.slice(0, soundPoint),(err) => { 142 | if (err) throw err; 143 | }); 144 | } 145 | 146 | return frame < capture_start ? 0 : frame-capture_start; 147 | } 148 | 149 | 150 | function writeToKeyboardBuffer(text) { 151 | var inputBufferPointer = processor.readmem(IBP); 152 | for (var a = 0; a0xff) {inputBufferPointer=0xE0;} 156 | } 157 | processor.writemem(IBP,inputBufferPointer); 158 | return processor.execute(text.length*15000); // Wait until Buffer empty 159 | } 160 | 161 | function pasteToBuffer(textIn) { 162 | var regex = new RegExp(/(.|[\r\n]){1,31}/g); 163 | var fragments = textIn.match(regex); 164 | if (fragments==null) return; 165 | for (const fragment of fragments) { 166 | writeToKeyboardBuffer(fragment); 167 | } 168 | return; 169 | } 170 | 171 | // The following is from https://github.com/mattgodbolt/jsbeeb/blob/master/tests/test.js 172 | function runFor(cycles) { 173 | var left = cycles; 174 | var stopped = false; 175 | return new Promise(function (resolve) { 176 | var runAnIter = function () { 177 | var todo = Math.max(0, Math.min(left, MaxCyclesPerIter)); 178 | if (todo) { 179 | stopped = !processor.execute(todo); 180 | left -= todo; 181 | } 182 | if (left && !stopped) { 183 | setTimeout(runAnIter, 0); 184 | } else { 185 | resolve(); 186 | } 187 | }; 188 | runAnIter(); 189 | }); 190 | } 191 | 192 | 193 | function runUntilInput() { 194 | var idleAddr = processor.model.isMaster ? 0xe7e6 : 0xe581; 195 | var hit = false; 196 | var hook = processor.debugInstruction.add(function (addr) { 197 | if (addr === idleAddr) { 198 | hit = true; 199 | return hit; 200 | } 201 | }); 202 | return runFor(20 * 2000000).then(function () { 203 | hook.remove(); 204 | runFor(1); 205 | return hit; 206 | }); 207 | } 208 | 209 | 210 | return { 211 | emulate:emulate, 212 | tokenise:tokenise 213 | }; 214 | } 215 | ); 216 | -------------------------------------------------------------------------------- /mastodon.js: -------------------------------------------------------------------------------- 1 | 2 | const ENABLE_TEXT_REPLY = false; 3 | const log = require('npmlog'); 4 | log.level = process.env.LOG_LEVEL || 'verbose'; 5 | const Mastodon = require('mastodon'); 6 | require('dotenv').config(); 7 | const config = { 8 | access_token: process.env.ACCESS_TOKEN, 9 | api_url: `https://${process.env.API_HOST}/api/v1/`, 10 | hashtag: process.env.HASHTAG, 11 | }; 12 | 13 | const mastodon = new Mastodon(config); 14 | const fs = require('fs'); 15 | 16 | function exec(cmd) { 17 | const exec = require('child_process').exec; 18 | return new Promise((resolve, reject) => { 19 | exec(cmd, (error, stdout, stderr) => { 20 | if (error) { 21 | console.warn(error); 22 | } 23 | resolve(stdout? stdout.trim() : stderr); 24 | }); 25 | }); 26 | } 27 | 28 | function post(path, params) { 29 | log.info("Post", path, params) 30 | } 31 | 32 | function get(path, params) { 33 | log.info("get", path, params) 34 | } 35 | 36 | 37 | async function videoReply(filename, mediaType, replyTo, text, toot, checksum, hasAudio, tag) { 38 | 39 | if (toot.spoiler_text == "") { 40 | console.log("No CW on bot source post") 41 | } 42 | 43 | try { 44 | let resp = await mastodon.post('media', { file: fs.createReadStream(filename), description: "BBC Micro Bot graphics output - " + toot.spoiler_text }); 45 | log.info(JSON.stringify(resp.data.id)); 46 | let id = resp.data.id; // Source: https://bbcmic.ro/#"+progData 47 | let params = { status: "I ran " + text + "'s program and got this.\nSource: https://bbcmic.ro/?t=" + tag + " #bbcbasic", media_ids: [id], in_reply_to_id: replyTo }; 48 | params.visibility = "public"; 49 | 50 | let response = await mastodon.post('statuses', params); 51 | 52 | log.info("Media post DONE ", JSON.stringify(response.data.id)); 53 | 54 | await mastodon.post('statuses/' + response.data.in_reply_to_id + '/favourite'); 55 | log.info("Favourited " + toot.id); 56 | 57 | let user = response.data.in_reply_to_account_id; 58 | log.info("User " + user); 59 | let relationship = await mastodon.get('accounts/relationships', { id: user }); 60 | log.info("Relationship " + (relationship.data[0].following ? "following" : "not following")); 61 | 62 | // If we're not following the user, reblog the toot 63 | if (relationship.data[0].following) { 64 | log.info("Reposting toot " + response.data.id); 65 | await mastodon.post('statuses/' + response.data.id + '/reblog'); 66 | } 67 | 68 | exec('rm '+filename); 69 | 70 | //return {full:"https://bbcmic.ro/"+experimental+"#"+progData,key:short_url} 71 | } 72 | 73 | catch (e) { 74 | 75 | log.info("Media post FAILED"); 76 | log.info(e); 77 | return null; 78 | } 79 | } 80 | 81 | 82 | function noOutput(toot) { 83 | console.warn("NO VIDEO CAPTURED"); 84 | if (!ENABLE_TEXT_REPLY) return; 85 | try { 86 | post('statuses/update', { status: "@" + toot.user.screen_name + " Sorry, no output captured from that program", in_reply_to_status_id: toot.id }); 87 | } 88 | catch (e) { 89 | log.info("Non-media post FAILED"); 90 | log.info(e); 91 | } 92 | } 93 | 94 | function block(toot) { 95 | post('blocks/create', { screen_name: toot.user.screen_name }); 96 | } 97 | 98 | module.exports = { 99 | videoReply: videoReply, 100 | noOutput: noOutput, 101 | block: block, 102 | post: post, 103 | get: get 104 | }; 105 | -------------------------------------------------------------------------------- /mastodon.json: -------------------------------------------------------------------------------- 1 | [06/11/2022 20:39:39 ] [LOG] Serv: { 2 | id: '109292779039545453', 3 | created_at: '2022-11-05T19:11:01.429Z', 4 | in_reply_to_id: '109292630262682237', 5 | in_reply_to_account_id: '109246658710563854', 6 | sensitive: false, 7 | spoiler_text: '', 8 | visibility: 'public', 9 | language: 'en', 10 | uri: 'https://mastodon.me.uk/users/bbcmicrobot/statuses/109292779039545453', 11 | url: 'https://mastodon.me.uk/@bbcmicrobot/109292779039545453', 12 | replies_count: 1, 13 | reblogs_count: 0, 14 | favourites_count: 2, 15 | edited_at: null, 16 | favourited: false, 17 | reblogged: false, 18 | muted: false, 19 | bookmarked: false, 20 | pinned: false, 21 | content: '

Thanks @Jaffa yeah that might be the way. I can have it respond to toots with (I think this is specific enough not to be spammy. I will check with @Floppy once things calm down a bit)

', 22 | reblog: null, 23 | application: { 24 | name: 'Mastodon for iOS', 25 | website: 'https://app.joinmastodon.org/ios' 26 | }, 27 | account: { 28 | id: '109289826032916877', 29 | username: 'bbcmicrobot', 30 | acct: 'bbcmicrobot', 31 | display_name: 'BBC Micro Bot :mastodon:', 32 | locked: false, 33 | bot: true, 34 | discoverable: true, 35 | group: false, 36 | created_at: '2022-11-05T00:00:00.000Z', 37 | note: '

Programs in a single toot of code 👾 1980s BBC Micro Model B 32K 6502. Acorn Computers and ARM stuff. BBC BASIC.

Also building a 3D simulator at virtual.bbcmic.ro

⚠️ Bot not online yet... I'm busy porting it!

bbcmicrobot.com

', 38 | url: 'https://mastodon.me.uk/@bbcmicrobot', 39 | avatar: 'https://cdn.masto.host/mastodonmeuk/accounts/avatars/109/289/826/032/916/877/original/7d1450f49b48a83e.png', 40 | avatar_static: 'https://cdn.masto.host/mastodonmeuk/accounts/avatars/109/289/826/032/916/877/original/7d1450f49b48a83e.png', 41 | header: 'https://cdn.masto.host/mastodonmeuk/accounts/headers/109/289/826/032/916/877/original/b7165f77e4b670b0.png', 42 | header_static: 'https://cdn.masto.host/mastodonmeuk/accounts/headers/109/289/826/032/916/877/original/b7165f77e4b670b0.png', 43 | followers_count: 508, 44 | following_count: 46, 45 | statuses_count: 36, 46 | last_status_at: '2022-11-07', 47 | emojis: [ [Object] ], 48 | fields: [ [Object] ] 49 | }, 50 | media_attachments: [], 51 | mentions: [ 52 | { 53 | id: '109246658710563854', 54 | username: 'Jaffa', 55 | url: 'https://social.linux.pizza/@Jaffa', 56 | acct: 'Jaffa@social.linux.pizza' 57 | }, 58 | { 59 | id: '1', 60 | username: 'Floppy', 61 | url: 'https://mastodon.me.uk/@Floppy', 62 | acct: 'Floppy' 63 | } 64 | ], 65 | tags: [ 66 | { 67 | name: 'bbcmicrobot', 68 | url: 'https://mastodon.me.uk/tags/bbcmicrobot' 69 | } 70 | ], 71 | emojis: [], 72 | card: null, 73 | poll: null 74 | } 75 | -------------------------------------------------------------------------------- /output/README.md: -------------------------------------------------------------------------------- 1 | Program records go here 2 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bbcmicrobot", 3 | "version": "0.3.0", 4 | "description": "Runs your tweet on an 8-bit computer emulator", 5 | "main": "server.js", 6 | "scripts": { 7 | "start": "node server & node client", 8 | "test": "node server test & node client test", 9 | "install": "bash ./install.sh" 10 | }, 11 | "author": "", 12 | "license": "ISC", 13 | "dependencies": { 14 | "aws-sdk": "^2.1265.0", 15 | "bad-words": "^3.0.3", 16 | "console-stamp": "^0.2.9", 17 | "dotenv": "^8.2.0", 18 | "express": "^4.17.1", 19 | "gifsicle": "^5.1.0", 20 | "grapheme-splitter": "^1.0.4", 21 | "htmlparser2": "^8.0.1", 22 | "jsbeeb": "git+https://github.com/mattgodbolt/jsbeeb.git#8935c9a3a095e846f63c0e4a08070f76ad01473e", 23 | "mastodon": "^1.2.2", 24 | "npmlog": "^7.0.1", 25 | "request": "^2.88.2", 26 | "requirejs": "^2.3.6" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /parser.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const TRY = (process.argv.indexOf("try") > -1) 4 | 5 | require('dotenv').config(); 6 | const Filter = require('bad-words'); 7 | const customFilter = new Filter({ placeHolder: '*'}); 8 | //customFilter.addWords('words','here'); 9 | const Grapheme = require('grapheme-splitter'); 10 | var splitter = new Grapheme(); 11 | const htmlparser2 = require('htmlparser2'); 12 | 13 | function processInput(toot) { 14 | if (TRY) return toot.text.trim(); 15 | 16 | var out = ''; 17 | var ignore = 0; 18 | const htmlparser = new htmlparser2.Parser({ 19 | onopentag(name, attributes) { 20 | if (ignore) { 21 | ++ignore; 22 | return; 23 | } 24 | 25 | var c = attributes['class']; 26 | if (c !== undefined && c.match(/\b(?:mention|hashtag)\b/)) { 27 | ignore = 1; 28 | return; 29 | } 30 | if (name === 'p' || name === 'br') out += '\n'; 31 | }, 32 | ontext(text) { 33 | if (!ignore) out += text; 34 | }, 35 | onclosetag(name) { 36 | if (ignore) --ignore; 37 | }, 38 | }); 39 | 40 | console.log(toot.text) 41 | htmlparser.parseComplete(toot.text); 42 | out = out.trim(); 43 | out = out.replace(/[“”]/g,'"'); 44 | console.log(out) 45 | 46 | return out; 47 | } 48 | 49 | function parseTweet(toot){ 50 | var graphemes = splitter.splitGraphemes(toot.text.trim()); 51 | var one_hour = 2000000*60*60; 52 | 53 | var c = { 54 | emulator: "beebjit", 55 | flags: "-accurate -rom 7 roms/gxr.rom -opt video:paint-start-cycles=60680000,video:border-chars=0 -frame-cycles 1 -max-frames 150", 56 | cycles: 69000000, 57 | compressed: false, 58 | input: "", 59 | mode: 1, 60 | } 61 | 62 | for (let i = 0; i -1) 6 | 7 | const express = require('express'); 8 | const https = require("https"); 9 | const fs = require("fs"); 10 | const cert_path = "./certs/"; 11 | const Feed = TEST ? require("./test").Feed : require('./hashtag'); 12 | 13 | // add timestamps in front of log messages 14 | require( 'console-stamp' )( console, { pattern: 'dd/mm/yyyy HH:MM:ss '},"Serv:" ); 15 | 16 | function log(l){console.log(l)} 17 | 18 | var tootFeed = new Feed(); 19 | var app = express(); 20 | var emulators = 0; 21 | var served = 0; 22 | 23 | app.get('/pop', (req, res) => { 24 | if (req.client.authorized) { 25 | let toot = (tootFeed.queue.length>0) ? tootFeed.queue.pop() : "{}"; 26 | 27 | res.send(toot); 28 | 29 | } 30 | }) 31 | 32 | app.get('/quit', (req, res) => { 33 | if (req.client.authorized) { 34 | process.exit(); 35 | } 36 | }) 37 | 38 | var options = { 39 | key: fs.readFileSync(cert_path+'server_key.pem'), 40 | cert: fs.readFileSync(cert_path+'server_cert.pem'), 41 | ca: [ fs.readFileSync(cert_path+'server_cert.pem') ], 42 | requestCert: true, 43 | rejectUnauthorized: true 44 | }; 45 | 46 | var listener = https.createServer(options, app).listen(PORT, function () { 47 | console.log('BBC Micro Bot toot server listening on port ' + listener.address().port); 48 | }); 49 | 50 | // Poll the twitter mentions 51 | 52 | tootFeed.update(); 53 | setInterval(function(){ tootFeed.update(); }, 45000); 54 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | 4 | // Monitor timeline timeline 5 | function Tests(since_id){ 6 | 7 | console.log("TEST TWEETS QUEUED"); 8 | 9 | var tests = [ 10 | { 11 | name: "ROCKET_MODE", // Test that a slow program completes 12 | text: "🚀0 MODE 2:VDU5\n10 FOR X = 0 TO 1279 STEP8:FOR Y = 0 TO 1023 STEP 4:GCOL 0, RND(7):PLOT 69, X, Y:NEXT:NEXT\nREPEAT UNTIL FALSE", 13 | mediaType: "image/png", 14 | checksum: "a02c1e9f18e3a86718067695c0e6e97ffdd5c6bd" 15 | }, 16 | { 17 | name: "LIKE_THE_CLAPPERS", // Test clapperboard emoji 18 | text: "🎬10MO.2:REP.F.A=0TO14:P.;A:F.D=1TO360:N.,:U.0", 19 | mediaType: "image/gif", 20 | checksum: "768e2a06a7a02b115f5e8efe5fa652810e051b43" 21 | }, 22 | { 23 | name: "FRAME_CAPTURE", // MODE 0-6 24 | text: "0 MODE 2\n10 FOR C = 0 TO 7\n20 COLOUR C\n30 PRINT \"COLOUR \",C\n40 NEXT C\n"+ 25 | "60 MOVE 0,0\n70 DRAW 1279,0\n80 DRAW 1279,1023\n90 DRAW 0,1023\n100 DRAW 0,0\n"+ 26 | "110 DRAW 1279,1023\n120 VDU 23,1,0;0;0;0;\n130 P.TAB(0,16);INT(TIME/10)/10;\" s \"\n140 GOTO 130", 27 | mediaType: "image/gif", 28 | checksum: "b0a979b0be31f48fc85b29635f55489857327f26" 29 | }, 30 | { 31 | name: "CHARACTERS", 32 | text: "10 PRINT“>&<&lt;”'SPC39\"|\"\n20 VDU 23,1,0;0;0;0;\n", // Tests twitter HTML escapes for <,&,> and OS X auto "" 33 | mediaType: "image/png", 34 | checksum: "c3f630a42cc39990a6e38c574a93f6c79b3c5a8a" 35 | }, 36 | /* beebjit doesn't currently support capturing audio output 37 | { 38 | name: "STATICAUDIO", // Test static image with audio gives a video 39 | text: '0V.279;0;0;0;0;12:P."BEEP":REP.V.7:U.NOTINKEY50', 40 | mediaType: "image/gif", 41 | hasAudio: true, 42 | checksum: "810209c18581c36ad7a3eb40502519e1aec39cae" 43 | }, 44 | { 45 | name: "AUDIOVISUAL", // Video with sound 46 | text: '1MO.2:V.5:ENV.1,1,-26,-36,-45,255,255,255,127,0,0,0,126,0:SO.1,1,1,1\n2GC.0,RND(7):PL.85,RND(1280),1023A.RND:G.2\n', 47 | mediaType: "image/gif", 48 | hasAudio: true, 49 | checksum: "4a954818f333f1d9a3b7334246bcdb5056295e3d" 50 | }, 51 | */ 52 | { 53 | name: "MODE6", // Test stripes aren't transparent in PNG 54 | text: '1MO.6:?&D0=2:F.L=0TO999:V.32+L MOD95:N.:V.19;4;0;279;0;0;0;0;', 55 | mediaType: "image/png", 56 | checksum: "06577a813c4df4f59f0e2325e9fe5874b7106293" 57 | }, 58 | { 59 | name: "RUNCHECK", // Regression test for program that didn't used to get run 60 | text: '0REM THIS SHOULD GET RUN\n1MO.6:P."MODE6":V.19;4;0;19,1,6;0;279;0;0;0;0', 61 | mediaType: "image/png", 62 | checksum: "b595b191a31cff941162438d1ce0135d71018a01" 63 | }, 64 | { 65 | name: "YOUONLYRUNONCE", // Check that an explicit RUN suppresses an implicit one. 66 | text: '1PRINT"HELLO":!-512=&B000B\nRUN', 67 | mediaType: "image/png", 68 | checksum: "28222f638d2c0b97e7e03d0e54561ab7364bd445" 69 | }, 70 | { 71 | name: "NOLINENOS", // Test no line numbers -> tokeniser. 72 | text: "P.\"HELLO\";\nV.279;0;0;0;0;32\nP.\"WORLD\"", 73 | mediaType: "image/png", 74 | checksum: "5c3db47017774d43ad27c9916af332d471e273e6" 75 | }, 76 | { 77 | name: "TOKENS", // Test tokens -> tokeniser. 78 | text: "\xf1~\u0190\n\xef279;0;0;0;0;\n", 79 | mediaType: "image/png", 80 | checksum: "27760d3701f31e398df07429364ef0ebcc8b2434" 81 | }, 82 | { 83 | name: "MENTIONS", // Test mention and hashtag removal 84 | text: "@BBCMicroBot @RhEolisM #bbcmicrobot 1V.279;0;0;0;0;12:PRINTCHR$141\"Hello\"'CHR$141\"Hello\"CHR$21\n", 85 | mediaType: "image/png", 86 | checksum: "10e6285dc55ec5ddab8470e8f038725db2d0ffbc" 87 | }, 88 | { 89 | name: "OVERLONG", // Test overlong line doesn't crash the bot 90 | text: "0REM " + ("BBC".repeat(88)), 91 | mediaType: "text/plain", 92 | checksum: "" 93 | }, 94 | { 95 | name: "TOKENISE_LONG", // Test tokenisation handles a long input 96 | text: "0PRINT" + (":PRINT".repeat(125)), 97 | mediaType: "image/gif", 98 | checksum: "930d0ab94529922c030d9797f2ec9a9c735a319c" 99 | }, 100 | {name: null, text: null} 101 | ] 102 | 103 | this.queue = []; 104 | while (tests.length) { 105 | var test = tests.pop(); 106 | var toot = { 107 | 'account' : {'url':'@test@localhost'}, 108 | 'user' : {'screen_name':""}, // 109 | 'text' : test.text, 110 | 'id' : test.name, 111 | 'bbcmicrobot_has_audio' : (test.hasAudio == true), 112 | 'bbcmicrobot_checksum' : test.checksum, 113 | 'bbcmicrobot_media_type' : test.mediaType, 114 | 'url' : "https://www.bbcmicrobot.com/test.html" 115 | }; 116 | this.queue.push(toot); 117 | } 118 | } 119 | 120 | // Get the next section of timeline timeline 121 | Tests.prototype.update = async function () {} 122 | 123 | function exec(cmd) { 124 | const exec = require('child_process').exec; 125 | return new Promise((resolve, reject) => { 126 | exec(cmd, (error, stdout, stderr) => { 127 | if (error) { 128 | throw error; 129 | } 130 | resolve(stdout? stdout.trim() : stderr); 131 | }); 132 | }); 133 | } 134 | 135 | function videoReply(filename,mediaType,id,replyTo,tweet,checksum,hasAudio){ 136 | console.log("checksum: "+checksum) 137 | if (tweet.bbcmicrobot_checksum != checksum) { 138 | throw new Error(id+' TEST - \u001b[31mFAILED\u001b[0m') 139 | } 140 | console.log("mediaType: "+mediaType) 141 | if (tweet.bbcmicrobot_media_type != mediaType) { 142 | throw new Error(id+' TEST - \u001b[31mFAILED\u001b[0m') 143 | } 144 | console.log("hasAudio: "+hasAudio) 145 | if (tweet.bbcmicrobot_has_audio != hasAudio) { 146 | throw new Error(id+' TEST - \u001b[31mFAILED\u001b[0m') 147 | } 148 | if (mediaType == 'image/gif') { 149 | exec('ffprobe -v 0 -select_streams a -show_streams '+filename).then( 150 | function(audioInfo) { 151 | var videoHasAudio = (audioInfo.length > 0); 152 | console.log("videoHasAudio: "+videoHasAudio); 153 | if (hasAudio != videoHasAudio) { 154 | throw new Error(id+' TEST - \u001b[31mFAILED\u001b[0m') 155 | } 156 | }); 157 | } 158 | console.log(replyTo+' TEST - \u001b[32mOK\u001b[0m') 159 | } 160 | 161 | function noOutput(tweet) { 162 | // If the checksum is empty then we expect no output. 163 | if (tweet.bbcmicrobot_checksum == '') { 164 | console.log(tweet.id+' TEST - \u001b[32mOK\u001b[0m') 165 | } else { 166 | throw new Error(tweet.id+' TEST - \u001b[31mFAILED\u001b[0m') 167 | } 168 | } 169 | 170 | function block(tweet) { 171 | throw new Error(tweet.id+' TEST - \u001b[31mFAILED\u001b[0m') 172 | } 173 | 174 | module.exports = { 175 | Feed: Tests, 176 | videoReply: videoReply, 177 | noOutput: noOutput, 178 | block: block 179 | }; 180 | -------------------------------------------------------------------------------- /tools/bbcbasictokenise: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl -CSAD 2 | use strict; 3 | use warnings; 4 | 5 | # Path to base2048 repo. 6 | # FIXME: Need to sort out not to need custom code in there for this to work 7 | # outside my machine! 8 | my ($base2048dir) = ($0 =~ m,(.*/),); 9 | $base2048dir //= ''; 10 | $base2048dir .= '../base2048'; 11 | 12 | # To twitter these inclusive ranges count as 1 character (everything else as 2): 13 | # U+0000-U+10FF 14 | # U+2000-U+200D # various spaces 15 | # U+2010-U+201F # various punctuation 16 | # U+2032-U+2037 # various prime marks 17 | my %token = ( 18 | 'AND' => "\x{580}", 19 | 'DIV' => "\x{281}", 20 | 'EOR' => "\x{E82}", 21 | 'MOD' => "\x{583}", 22 | 'OR' => "\x{184}", 23 | 'ERROR' => "\x{F85}", 24 | 'LINE' => "\x{186}", 25 | 'OFF' => "\x{287}", 26 | 'STEP' => "\x{388}", 27 | 'SPC' => "\x{F89}", 28 | 'TAB(' => "\x{38A}", 29 | 'ELSE' => "\x{18B}", 30 | 'THEN' => "\x{18C}", 31 | # 8D encodes a line number in GOTO/GOSUB 32 | 'OPENIN' => "\x{18E}", 33 | #'PTR' => "\x8F" # (right form) 34 | 35 | 'PAGE' => "\x{490}", 36 | '?PAGE=' => "?\x{490}=", 37 | '!PAGE=' => "!\x{490}=", 38 | '$PAGE=' => "\$\x{490}=", 39 | 'TIME' => "\x{191}", 40 | '?TIME=' => "?\x{191}=", 41 | '!TIME=' => "!\x{191}=", 42 | '$TIME=' => "\$\x{191}=", 43 | 'LOMEM' => "\x{1092}", 44 | '?LOMEM=' => "?\x{1092}=", 45 | '!LOMEM=' => "!\x{1092}=", 46 | '$LOMEM=' => "\$\x{1092}=", 47 | 'HIMEM' => "\x{493}", 48 | '?HIMEM=' => "?\x{493}=", # E.g. ?HIMEM=32 or P%?HIMEM=32 49 | '!HIMEM=' => "!\x{493}=", # E.g. !HIMEM=32 or P%!HIMEM=32 50 | '$HIMEM=' => "\$\x{493}=", # E.g. $HIMEM="HELLO" 51 | 'ABS' => "\x{294}", 52 | 'ACS' => "\x{195}", 53 | 'ADVAL' => "\x{196}", 54 | 'ASC' => "\x{297}", 55 | 'ASN' => "\x{298}", 56 | 'ATN' => "\x{199}", 57 | 'BGET' => "\x{19A}", 58 | 'COS' => "\x{19B}", 59 | 'COUNT' => "\x{19C}", 60 | 'DEG' => "\x{19D}", 61 | 'ERL' => "\x{19E}", 62 | 'ERR' => "\x{19F}", 63 | 64 | 'EVAL' => "\x{3A0}", 65 | 'EXP' => "\xA1", 66 | 'EXT' => "\xA2", 67 | 'FALSE' => "\x{1A3}", 68 | 'FN' => "\xA4", 69 | 'GET' => "\xA5", 70 | 'INKEY' => "\xA6", 71 | 'INSTR(' => "\xA7", 72 | 'INT' => "\xA8", 73 | 'LEN' => "\xA9", 74 | 'LN' => "\xAA", 75 | 'LOG' => "\xAB", 76 | 'NOT' => "\xAC", 77 | 'OPENUP' => "\xAD", 78 | 'OPENOUT' => "\xAE", 79 | 'PI' => "\xAF", 80 | 81 | 'POINT(' => "\xB0", 82 | 'POS' => "\xB1", 83 | 'RAD' => "\xB2", 84 | 'RND' => "\xB3", 85 | 'SGN' => "\xB4", 86 | 'SIN' => "\xB5", 87 | 'SQR' => "\xB6", 88 | 'TAN' => "\xB7", 89 | 'TO' => "\xB8", 90 | 'TRUE' => "\xB9", 91 | 'USR' => "\xBA", 92 | 'VAL' => "\xBB", 93 | 'VPOS' => "\xBC", 94 | 'CHR$' => "\xBD", 95 | 'GET$' => "\xBE", 96 | 'INKEY$' => "\xBF", 97 | 98 | 'LEFT$(' => "\xC0", 99 | 'MID$(' => "\xC1", 100 | 'RIGHT$(' => "\xC2", 101 | 'STR$' => "\xC3", 102 | 'STRING$(' => "\xC4", 103 | 'EOF' => "\xC5", 104 | 'AUTO' => "\xC6", 105 | 'DELETE' => "\xC7", 106 | 'LOAD' => "\xC8", 107 | 'LIST' => "\xC9", 108 | 'NEW' => "\xCA", 109 | 'OLD' => "\xCB", 110 | 'RENUMBER' => "\xCC", 111 | 'SAVE' => "\xCD", 112 | # CE unused by BASIC II (EDIT in later versions) 113 | #'PTR' => "\xCF" # (left form) 114 | 115 | 'PAGE=' => "\xD0=", 116 | 'PA.=' => "\xD0=", 117 | 'TIME=' => "\xD1=", 118 | 'TI.=' => "\xD1=", 119 | 'LOMEM=' => "\xD2=", 120 | 'HIMEM=' => "\xD3=", 121 | 'H.=' => "\xD3=", 122 | 'SOUND' => "\xD4", 123 | 'BPUT' => "\xD5", 124 | 'CALL' => "\xD6", 125 | 'CHAIN' => "\xD7", 126 | 'CLEAR' => "\xD8", 127 | 'CLOSE' => "\xD9", 128 | 'CLG' => "\x{3DA}", 129 | 'CLS' => "\xDB", 130 | 'DATA' => "\xDC", 131 | 'DEF' => "\xDD", 132 | 'DIM' => "\xDE", 133 | 'DRAW' => "\xDF", 134 | 135 | 'END' => "\xE0", 136 | 'ENDPROC' => "\xE1", 137 | 'ENVELOPE' => "\xE2", 138 | 'FOR' => "\x{1E3}", 139 | 'GOSUB' => "\x{1E4}", 140 | 'GOTO' => "\x{1E5}", 141 | 'GCOL' => "\x{1E6}", 142 | 'IF' => "\x{2E7}", 143 | 'INPUT' => "\xE8", 144 | 'LET' => "\xE9", 145 | 'LOCAL' => "\xEA", 146 | 'MODE' => "\xEB", 147 | 'MOVE' => "\xEC", 148 | 'NEXT' => "\xED", 149 | 'NEXT:NEXT' => "\xED,", 150 | 'NEXT:NEXT:NEXT' => "\xED,,", 151 | 'NEXT:NEXT:NEXT:NEXT' => "\xED,,,", 152 | 'N.:N.' => "\xED,", 153 | 'N.:N.:N.' => "\xED,,", 154 | 'N.:N.:N.:N.' => "\xED,,,", 155 | 'ON' => "\xEE", 156 | 'VDU' => "\xEF", 157 | 158 | 'PLOT' => "\xF0", 159 | 'PRINT' => "\x{10F1}", 160 | 'PROC' => "\x{4F2}", 161 | 'READ' => "\x{6F3}", 162 | 'REM' => "\xF4", 163 | 'REPEAT' => "\x{4F5}", 164 | 'REPORT' => "\xF6", 165 | 'RESTORE' => "\x{7F7}", 166 | 'RETURN' => "\xF8", 167 | 'RUN' => "\xF9", 168 | 'STOP' => "\xFA", 169 | 170 | 'COLOUR' => "\xFB", 171 | 'TRACE' => "\xFC", 172 | 'UNTIL' => "\xFD", 173 | 'WIDTH' => "\xFE", 174 | 'OSCLI' => "\xFF" 175 | ); 176 | 177 | # Minimum abbreviations: 178 | my @abbrevs = ( 179 | 'ABS' => 'AB.', 180 | 'ACS' => 'AC.', 181 | 'ADVAL' => 'AD.', 182 | 'AND' => 'A.', 183 | 'ASC' => 'AS.', 184 | 'ASN' => 'ASN', 185 | 'ATN' => 'AT.', 186 | 'AUTO' => 'AU.', 187 | 'BGET' => 'B.', 188 | 'BPUT' => 'BP.', 189 | 'CALL' => 'CA.', 190 | 'CHAIN' => 'CH.', 191 | 'CHR$' => 'CHR.', 192 | 'CLEAR' => 'CL.', 193 | 'CLG' => 'CLG', 194 | 'CLOSE' => 'CLO.', 195 | 'CLS' => 'CLS', 196 | 'COLOUR' => 'C.', 197 | 'COS' => 'COS', 198 | 'COUNT' => 'COU.', 199 | 'DATA' => 'D.', 200 | 'DEF' => 'DEF', 201 | 'DEG' => 'DE.', 202 | 'DELETE' => 'DEL.', 203 | 'DIM' => 'DIM', 204 | 'DIV' => 'DI.', 205 | 'DRAW' => 'DR.', 206 | 'ELSE' => 'EL.', 207 | 'END' => 'END', 208 | 'ENDPROC' => 'E.', 209 | 'ENVELOPE' => 'ENV.', 210 | 'EOF' => 'EO.', 211 | 'EOR' => 'EOR', 212 | 'ERL' => 'ER.', 213 | 'ERR' => 'ERR', 214 | 'ERROR' => 'ERR.', 215 | 'EVAL' => 'EV.', 216 | 'EXP' => 'EX.', 217 | 'EXT' => 'EXT', 218 | 'FALSE' => 'FA.', 219 | 'FN' => 'FN', 220 | 'FOR' => 'F.', 221 | 'GCOL' => 'GC.', 222 | 'GET$' => 'GE.', 223 | 'GET' => 'GET', 224 | 'GOSUB' => 'GOS.', 225 | 'GOTO' => 'G.', 226 | 'HIMEM' => 'H.', 227 | 'IF' => 'IF', 228 | 'INKEY' => 'INKEY', 229 | 'INKEY$' => 'INK.', 230 | 'INPUT' => 'I.', 231 | 'INSTR(' => 'INS.', 232 | 'INT' => 'INT', 233 | 'LEFT$(' => 'LE.', 234 | 'LEN' => 'LEN', 235 | 'LET' => 'LET', 236 | 'LINE' => 'LIN.', 237 | 'LIST' => 'L.', 238 | 'LN' => 'LN', 239 | 'LOAD' => 'LO.', 240 | 'LOCAL' => 'LOC.', 241 | 'LOG' => 'LOG', 242 | 'LOMEM' => 'LOM.', 243 | 'MID$(' => 'M.', 244 | 'MOD' => 'MOD', 245 | 'MODE' => 'MO.', 246 | 'MOVE' => 'MOV.', 247 | 'NEW' => 'NEW', 248 | 'NEXT' => 'N.', 249 | 'NOT' => 'NO.', 250 | 'OFF' => 'OF.', 251 | 'OLD' => 'O.', 252 | 'ON' => 'ON', 253 | 'OPENIN' => 'OP.', 254 | 'OPENOUT' => 'OPENO.', 255 | 'OPENUP' => 'OPENU.', 256 | 'OPT' => 'OPT', 257 | 'OR' => 'OR', 258 | 'OSCLI' => 'OS.', 259 | 'PAGE' => 'PA.', 260 | 'PI' => 'PI', 261 | 'PLOT' => 'PL.', 262 | 'POINT(' => 'PO.', 263 | 'POS' => 'POS', 264 | 'PRINT' => 'P.', 265 | 'PROC' => 'PRO.', 266 | 'PTR' => 'PT.', 267 | 'RAD' => 'RAD', 268 | 'READ' => 'REA.', 269 | 'REM' => 'REM', 270 | 'RENUMBER' => 'REN.', 271 | 'REPEAT' => 'REP.', 272 | 'REPORT' => 'REPO.', 273 | 'RESTORE' => 'RES.', 274 | 'RETURN' => 'R.', 275 | 'RIGHT$(' => 'RI.', 276 | 'RND' => 'RN.', 277 | 'RUN' => 'RU.', 278 | 'SAVE' => 'SA.', 279 | 'SGN' => 'SG.', 280 | 'SIN' => 'SI.', 281 | 'SOUND' => 'SO.', 282 | 'SPC' => 'SP.', 283 | 'SQR' => 'SQ.', 284 | 'STEP' => 'S.', 285 | 'STOP' => 'STO.', 286 | 'STR$' => 'STR.', 287 | 'STRING$(' => 'STRI.', 288 | 'TAB(' => 'TAB.', 289 | 'TAN' => 'T.', 290 | 'THEN' => 'TH.', 291 | 'TIME' => 'TI.', 292 | 'TO' => 'TO', 293 | 'TRACE' => 'TR.', 294 | 'TRUE' => 'TRU.', 295 | 'UNTIL' => 'U.', 296 | 'USR' => 'US.', 297 | 'VAL' => 'VA.', 298 | 'VDU' => 'V.', 299 | 'VPOS' => 'VP.', 300 | 'WIDTH' => 'W.', 301 | ); 302 | 303 | sub expand_token { 304 | my $token = shift; 305 | for (my $i = 1; $i < @abbrevs; $i += 2) { 306 | if ($abbrevs[$i] eq $token) { 307 | return $abbrevs[$i - 1]; 308 | } 309 | } 310 | return $token; 311 | } 312 | 313 | # Hash to allow undoing abbreviations so we can work with full tokens, which we 314 | # then tokenise, optimise, or re-abbreviate (but having ensured the shortest 315 | # possible abbreviation is used). 316 | my %abbrevs; 317 | for (my $i = 0; $i < @abbrevs; $i += 2) { 318 | my $token = $abbrevs[$i]; 319 | my $abbrev = $abbrevs[$i + 1]; 320 | if (!exists($token{$token})) { 321 | $token{$token} = $abbrev; 322 | } 323 | while (1) { 324 | if (exists($abbrevs{$abbrev})) { 325 | warn "Collision for '$abbrev': '$abbrevs{$abbrev}' vs '$token'\n"; 326 | } 327 | $abbrevs{$abbrev} = $token; 328 | last if (length($abbrev) == length($token)); 329 | # Remove the '.' then add another character and replace the '.'. 330 | $abbrev = substr($abbrev, 0, -1); 331 | $abbrev .= substr($token, length($abbrev), 1) . '.'; 332 | } 333 | } 334 | 335 | my $decode; 336 | if (@ARGV > 0 && $ARGV[0] eq '--decode') { 337 | shift @ARGV; 338 | my @detoken = (); 339 | for my $k (sort keys %token) { 340 | my $t = $token{$k}; 341 | if (length($t) == 2 && substr($t, -1) eq '=' && substr($k, -1) eq '=') { 342 | # print STDERR "trimming '$k' "; 343 | $t = substr($t, 0, -1); 344 | $k = substr($k, 0, -1); 345 | # print STDERR "to '$k'\n"; 346 | } 347 | if (length($t) == 1) { 348 | $detoken[ord($t)] = $k; 349 | # printf STDERR "token &%02x = '%s'\n", ord($t), $k; 350 | if (ord($t)>=0x100) { 351 | $detoken[ord($t)&0xff] //= $k; 352 | } 353 | } 354 | } 355 | for (32 .. 126) { 356 | $detoken[$_] //= chr($_); 357 | } 358 | for (0 .. 0xff) { 359 | $detoken[$_] //= sprintf '[UNKNOWN TOKEN &%02x]', $_; 360 | } 361 | $_ = <>; 362 | if (s/^\x{1F5DC}//) { 363 | local $/ = undef; 364 | my $base2048 = $_ . <>; 365 | print "len = " , length($base2048) , "\n"; 366 | $_ = `node \Q$base2048dir\E/src/decode.js \Q$base2048\E`; 367 | } 368 | while (defined $_) { 369 | my ($q, $c); 370 | for (my $i = 0; $i < length($_); ++$i) { 371 | my $p = $c; 372 | $c = substr($_, $i, 1); 373 | if ($c eq '"') { 374 | $q = !$q; 375 | next; 376 | } 377 | my $codepoint = ord($c); 378 | my $replacement; 379 | if ($q) { 380 | # FIXME: Decode VDU sequences encoded as Unicode in strings to 381 | # somehow? 382 | if ($codepoint < 32 || ($codepoint >= 127 && $codepoint < 160)) { 383 | # Replace non-printables with equivalent printables. 384 | $replacement = chr(0x100 + $codepoint); 385 | } 386 | } elsif ($codepoint >= 0x80 && $codepoint <= 0x10ff) { 387 | # Expand token 388 | $replacement = ' ' . $detoken[$codepoint & 0xff]; 389 | } elsif ($codepoint >= ord('A') && $codepoint <= ord('Z')) { 390 | if (substr($_, $i + 1) =~ /([A-Z]*\.)/) { 391 | # Expand abbreviation. 392 | $c .= $1; 393 | $replacement = expand_token($c); 394 | } 395 | } 396 | if (defined($replacement)) { 397 | $_ = substr($_, 0, $i) . $replacement . substr($_, $i + length($c)); 398 | $i += length($replacement) - length($c); 399 | next; 400 | } 401 | } 402 | print; 403 | $_ = <>; 404 | } 405 | exit 0; 406 | } 407 | 408 | my $seen_rem; 409 | 410 | sub token { 411 | my ($pre, $w, $k) = @_; 412 | my $q = 0; 413 | ++$q while $pre =~ /"/g; 414 | if ($q % 2 == 1) { 415 | return $w . $k; 416 | } 417 | if (substr($k, -1) eq '.' and exists $abbrevs{$k}) { 418 | $k = $abbrevs{$k}; 419 | } 420 | if (!exists $token{$k}) { 421 | print STDERR "KEYWORD '$k'\n"; 422 | return $w . $k; 423 | } 424 | if ($k eq 'REM') { 425 | $seen_rem = 1; 426 | } 427 | my $t = $token{$k}; 428 | if ($t =~ /^[A-Z]/) { 429 | return $w . $t; 430 | } 431 | return $t; 432 | } 433 | my $T = join("|",map quotemeta, sort {length($b)<=>length($a) or $a cmp $b} (keys %token, keys %abbrevs)); 434 | 435 | my $o = ''; 436 | 437 | my $len = 0; 438 | while (<>) { 439 | if ($len > 0) { 440 | print "\n"; 441 | $o .= "\n"; 442 | ++$len; 443 | } 444 | chomp; 445 | # Leave already tokenised lines alone. 446 | # if (/[^\0-\x7f]/) { 447 | # goto leave_alone; 448 | #} 449 | #next if !$full && /^REM/; 450 | $seen_rem = 0; 451 | s/( *?)($T)/$seen_rem ? $1.$2 : token($`,$1,$2)/ge; 452 | my ($q, $c); 453 | for (my $i = 0; $i < length($_); ++$i) { 454 | my $p = $c; 455 | $c = substr($_, $i, 1); 456 | if ($c eq '"') { 457 | $q = !$q; 458 | next; 459 | } 460 | # Don't strip spaces from REMs - if they're in the code then their 461 | # contents is probably being peeked for data. 462 | last if ($c eq $token{'REM'}); 463 | # Don't strip spaces from DATA. 464 | last if ($c eq $token{'DATA'}); 465 | if (!$q) { 466 | if ($c eq ' ' and (!defined $p or $p =~ /^[^A-Za-z]$/)) { 467 | $_ = substr($_, 0, $i) . substr($_, $i + 1); 468 | --$i; 469 | } 470 | } 471 | } 472 | leave_alone: 473 | print; 474 | $o .= $_; 475 | print STDERR "Line length: ", length($_), " bytes\n"; 476 | $len += length($_); 477 | } 478 | print STDERR "\nTotal length: $len bytes\n"; 479 | if ($len > 281 || exists $ENV{FORCE_BASE2048}) { 480 | system 'node', "$base2048dir/src/index.js", $o; 481 | if ($len > 382) { 482 | print "Too long by ", $len - 382, " bytes (pre-BASE2048)\n"; 483 | } 484 | } 485 | 486 | # BUG: O!2=A ORRND EL.F.R=0TO2 -> syntax error 487 | # and decoding doesn't insert spaces after tokens which need it 488 | -------------------------------------------------------------------------------- /tweetdisk.js: -------------------------------------------------------------------------------- 1 | const request = require('request'); 2 | const fs = require("fs"); 3 | PNG = require("pngjs").PNG; 4 | 5 | function stegDecode(dataIn){ 6 | const magicWord = 0x12345678; 7 | const version = 0x00000001; 8 | 9 | var image8 = new Uint8Array(dataIn); 10 | var data8 = new Uint8Array(900*900); 11 | var data32 = new Uint32Array(data8.buffer); 12 | 13 | let i = 0; 14 | 15 | for (let d = 0; d