submissions.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. /**
  2. * Enjoy this over-engineered pile of garbage that is actually pretty cool
  3. *
  4. * @author Sv443
  5. * @since 2.3.2
  6. * @ref #340 - https://github.com/Sv443-Network/JokeAPI/issues/340
  7. */
  8. const { readdir, readFile, writeFile, copyFile, rm, rmdir } = require("fs-extra");
  9. const { resolve, join } = require("path");
  10. const { colors, Errors, reserialize, filesystem, isEmpty } = require("svcorelib");
  11. const prompt = require("prompts");
  12. const promiseAllSeq = require("promise-all-sequential");
  13. const languages = require("../src/languages");
  14. const translate = require("../src/translate");
  15. const parseJokes = require("../src/parseJokes");
  16. const { reformatJoke } = require("../src/jokeSubmission");
  17. const settings = require("../settings");
  18. const col = colors.fg;
  19. const { exit } = process;
  20. //#MARKER types & init
  21. /** @typedef {import("./types").AllSubmissions} AllSubmissions */
  22. /** @typedef {import("./types").Submission} Submission */
  23. /** @typedef {import("./types").ParsedFileName} ParsedFileName */
  24. /** @typedef {import("./types").ReadSubmissionsResult} ReadSubmissionsResult */
  25. /** @typedef {import("./types").LastEditedSubmission} LastEditedSubmission */
  26. /** @typedef {import("./types").Keypress} Keypress */
  27. /** @typedef {import("../src/types/jokes").JokeSubmission} JokeSubmission */
  28. /** @typedef {import("../src/types/jokes").JokeFlags} JokeFlags */
  29. /** @typedef {import("../src/types/jokes").JokesFile} JokesFile */
  30. /** @typedef {import("../src/types/languages").LangCode} LangCodes */
  31. /** @type {LastEditedSubmission} */
  32. let lastSubmissionType;
  33. /** @type {number} */
  34. let currentSub;
  35. /** @type {boolean} */
  36. let lastKeyInvalid = false;
  37. const stats = {
  38. /** How many submissions were acted upon */
  39. submissionsActAmt: 0,
  40. /** How many submissions were saved */
  41. savedSubmissions: 0,
  42. /** How many submissions were deleted / discarded */
  43. deletedSubmissions: 0,
  44. /** How many submissions were edited */
  45. editedSubmissions: 0,
  46. };
  47. /**
  48. * Entrypoint of this tool
  49. */
  50. async function run()
  51. {
  52. try
  53. {
  54. await languages.init();
  55. await translate.init();
  56. await parseJokes.init();
  57. }
  58. catch(err)
  59. {
  60. throw new Error(`Error while initializing dependency modules: ${err}`);
  61. }
  62. lastSubmissionType = undefined;
  63. currentSub = 1;
  64. /** @type {LangCodes} */
  65. const langCodes = await getLangCodes();
  66. const { submissions, amount } = await readSubmissions(langCodes);
  67. if(amount < 1)
  68. {
  69. console.log("\nFound no submissions to go through. Exiting.\n");
  70. exit(0);
  71. }
  72. const langCount = Object.keys(submissions).length;
  73. const { proceed } = await prompt({
  74. message: `There are ${amount} submissions of ${langCount} language${langCount > 1 ? "s" : ""}. Go through them now?`,
  75. type: "confirm",
  76. name: "proceed"
  77. });
  78. if(proceed)
  79. return promptSubmissions(submissions);
  80. else
  81. {
  82. console.log("Exiting.");
  83. exit(0);
  84. }
  85. }
  86. //#MARKER prompts
  87. /**
  88. * Goes through all submissions, prompting about what to do with them
  89. * @param {AllSubmissions} allSubmissions
  90. */
  91. async function promptSubmissions(allSubmissions)
  92. {
  93. const langs = Object.keys(allSubmissions);
  94. for await(const lang of langs)
  95. {
  96. /** @type {Submission[]} */
  97. const submissions = allSubmissions[lang];
  98. /** @type {(() => Promise)[]} */
  99. const proms = submissions.map((sub) => (() => actSubmission(sub)));
  100. await promiseAllSeq(proms);
  101. const langSubfolderPath = resolve(settings.jokes.jokeSubmissionPath, lang);
  102. await cleanupDir(langSubfolderPath);
  103. }
  104. return finishPrompts();
  105. }
  106. //#SECTION act on submission
  107. /**
  108. * Prompts the user to act on a submission
  109. * @param {Submission} sub
  110. * @returns {Promise<void, Error>}
  111. */
  112. function actSubmission(sub)
  113. {
  114. return new Promise(async (res, rej) => {
  115. try
  116. {
  117. console.clear();
  118. let lastSubmText = "";
  119. switch(lastSubmissionType)
  120. {
  121. case "accepted_safe":
  122. lastSubmText = `(Last submission was accepted ${col.green}safe${col.rst})`;
  123. break;
  124. case "accepted_unsafe":
  125. lastSubmText = `(Last submission was accepted ${col.yellow}unsafe${col.rst})`;
  126. break;
  127. case "edited":
  128. lastSubmText = `(Last submission was ${col.magenta}edited${col.rst})`;
  129. break;
  130. case "deleted":
  131. lastSubmText = `(Last submission was ${col.red}deleted${col.rst})`;
  132. break;
  133. }
  134. const last = !lastKeyInvalid ? (lastSubmissionType ? lastSubmText : "") : `${col.red}Invalid key - try again${col.rst}`;
  135. console.log(`${last}\n\n------------\nLanguage: ${sub.lang}\n------------\n`);
  136. printSubmission(sub);
  137. /** @type {null|Submission} The submission to be added to the local jokes */
  138. let finalSub = null;
  139. const key = await getKey(`\n${col.blue}Choose action:${col.rst} Accept ${col.green}[S]${col.rst}afe • Accept ${col.magenta}[U]${col.rst}nsafe • ${col.yellow}[E]${col.rst}dit • ${col.red}[D]${col.rst}elete`);
  140. let safe = false;
  141. switch(key.name)
  142. {
  143. case "s": // add safe
  144. safe = true;
  145. lastSubmissionType = "accepted_safe";
  146. finalSub = reserialize(sub);
  147. currentSub++;
  148. break;
  149. case "u": // add unsafe
  150. lastSubmissionType = "accepted_unsafe";
  151. finalSub = reserialize(sub);
  152. currentSub++;
  153. break;
  154. case "e": // edit
  155. lastSubmissionType = "edited";
  156. finalSub = await editSubmission(sub);
  157. currentSub++;
  158. break;
  159. case "d": // delete
  160. lastSubmissionType = "deleted";
  161. await deleteSubmission(sub);
  162. currentSub++;
  163. return res();
  164. default: // invalid key
  165. lastKeyInvalid = true;
  166. return await actSubmission(sub);
  167. }
  168. if(finalSub && lastSubmissionType != "edited")
  169. finalSub.joke.safe = safe;
  170. // if not deleted in editSubmission()
  171. if(finalSub !== null)
  172. await saveSubmission(finalSub);
  173. return res();
  174. }
  175. catch(err)
  176. {
  177. return rej(new Error(`Error while choosing action for submission #${currentSub}: ${err}`));
  178. }
  179. });
  180. }
  181. //#SECTION edit submission
  182. /**
  183. * Gets called to edit a submission
  184. * @param {Submission} sub
  185. * @returns {Promise<Submission>} Returns the edited submission
  186. */
  187. function editSubmission(sub)
  188. {
  189. return new Promise(async (res, rej) => {
  190. /** @type {Submission} */
  191. const editedSub = reserialize(sub);
  192. /** @param {Submission} finalSub */
  193. const trySubmit = async (finalSub) => {
  194. if(typeof finalSub.joke.lang !== "string")
  195. finalSub.joke.lang = finalSub.lang;
  196. const validateRes = parseJokes.validateSingle(finalSub.joke, finalSub.lang);
  197. const allErrors = Array.isArray(validateRes) ? validateRes : [];
  198. if(typeof finalSub.joke.safe !== "boolean")
  199. allErrors.push("Property 'safe' is not of type boolean");
  200. if(allErrors.length > 0)
  201. {
  202. console.log(`${col.red}Joke is invalid:${col.rst}`);
  203. console.log(`- ${allErrors.join("\n- ")}\n`);
  204. await getKey("Press any key to try again.");
  205. return res(editSubmission(finalSub)); // async recursion, who doesn't love it
  206. }
  207. else
  208. {
  209. stats.editedSubmissions++;
  210. return res(Object.freeze(finalSub));
  211. }
  212. };
  213. try
  214. {
  215. const jokeChoices = sub.joke.type === "single" ? [
  216. {
  217. title: `Joke (${editedSub.joke.joke})`,
  218. value: "joke",
  219. },
  220. ] : [
  221. {
  222. title: `Setup (${editedSub.joke.setup})`,
  223. value: "setup",
  224. },
  225. {
  226. title: `Delivery (${editedSub.joke.delivery})`,
  227. value: "delivery",
  228. },
  229. ];
  230. const choices = [
  231. {
  232. title: `Category (${editedSub.joke.category})`,
  233. value: "category",
  234. },
  235. {
  236. title: `Type (${editedSub.joke.type})`,
  237. value: "type",
  238. },
  239. ...jokeChoices,
  240. {
  241. title: `Flags (${extractFlags(editedSub.joke)})`,
  242. value: "flags",
  243. },
  244. {
  245. title: `Safe (${editedSub.joke.safe})`,
  246. value: "safe",
  247. },
  248. {
  249. title: `${col.green}[Submit]${col.rst}`,
  250. value: "submit",
  251. },
  252. {
  253. title: `${col.red}[Delete]${col.rst}`,
  254. value: "delete",
  255. },
  256. ];
  257. process.stdout.write("\n");
  258. const { editProperty } = await prompt({
  259. message: "Edit property",
  260. type: "select",
  261. name: "editProperty",
  262. hint: "- Use arrow-keys. Return to select. Esc or Ctrl+C to submit.",
  263. choices,
  264. });
  265. switch(editProperty)
  266. {
  267. case "category":
  268. {
  269. const catChoices = settings.jokes.possible.categories.map(cat => ({ title: cat, value: cat }));
  270. const { category } = await prompt({
  271. type: "select",
  272. message: `Select new category`,
  273. name: "category",
  274. choices: catChoices,
  275. initial: settings.jokes.possible.categories.indexOf("Misc"),
  276. });
  277. editedSub.joke.category = category;
  278. break;
  279. }
  280. case "joke":
  281. case "setup":
  282. case "delivery":
  283. editedSub.joke[editProperty] = (await prompt({
  284. type: "text",
  285. message: `Enter new value for '${editProperty}' property`,
  286. name: "val",
  287. initial: editedSub.joke[editProperty] || "",
  288. validate: (val) => (!isEmpty(val) && val.length >= settings.jokes.submissions.minLength),
  289. })).val;
  290. break;
  291. case "type":
  292. editedSub.joke.type = (await prompt({
  293. type: "select",
  294. message: "Select a new joke type",
  295. choices: [
  296. { title: "Single", value: "single" },
  297. { title: "Two Part", value: "twopart" },
  298. ],
  299. name: "type",
  300. })).type;
  301. break;
  302. case "flags":
  303. {
  304. const flagKeys = Object.keys(editedSub.joke.flags);
  305. const flagChoices = [];
  306. flagKeys.forEach(key => {
  307. flagChoices.push({
  308. title: key,
  309. selected: editedSub.joke.flags[key] === true,
  310. });
  311. });
  312. const { newFlags } = await prompt({
  313. type: "multiselect",
  314. message: "Edit joke flags",
  315. choices: flagChoices,
  316. name: "newFlags",
  317. instructions: false,
  318. hint: "- arrow-keys to move, space to toggle, return to submit",
  319. });
  320. Object.keys(editedSub.joke.flags).forEach(key => {
  321. editedSub.joke.flags[key] = false;
  322. });
  323. newFlags.forEach(setFlagIdx => {
  324. const key = flagKeys[setFlagIdx];
  325. editedSub.joke.flags[key] = true;
  326. });
  327. break;
  328. }
  329. case "safe":
  330. editedSub.joke.safe = (await prompt({
  331. type: "confirm",
  332. message: "Is this joke safe?",
  333. initial: false,
  334. name: "safe",
  335. })).safe;
  336. break;
  337. case "submit":
  338. return trySubmit(editedSub);
  339. case "delete":
  340. {
  341. const { del } = await prompt({
  342. type: "confirm",
  343. message: "Delete this submission?",
  344. name: "del",
  345. });
  346. if(del)
  347. {
  348. lastSubmissionType = "deleted";
  349. await deleteSubmission(sub);
  350. return res(null);
  351. }
  352. break;
  353. }
  354. default:
  355. return trySubmit(editedSub);
  356. }
  357. return res(await editSubmission(editedSub));
  358. }
  359. catch(err)
  360. {
  361. return rej(new Error(`Error while editing submission: ${err}`));
  362. }
  363. });
  364. }
  365. /**
  366. * Deletes/discards a submission
  367. * @param {Submission} sub
  368. * @returns {Promise<void, Error>}
  369. */
  370. function deleteSubmission(sub)
  371. {
  372. return new Promise(async (res, rej) => {
  373. try
  374. {
  375. await rm(sub.path);
  376. stats.submissionsActAmt++;
  377. stats.deletedSubmissions++;
  378. return res();
  379. }
  380. catch(err)
  381. {
  382. return rej(new Error(`Error while deleting submission at path '${sub.path}': ${err}`));
  383. }
  384. });
  385. }
  386. /**
  387. * Cleans up the submission directories if they're empty
  388. * @param {string} path Path to the submission language subfolder
  389. * @returns {Promise<void, Error>}
  390. */
  391. function cleanupDir(path)
  392. {
  393. return new Promise(async (res, rej) => {
  394. try
  395. {
  396. const subDirFiles = await readdir(path);
  397. if(subDirFiles.length === 0)
  398. await rmdir(path);
  399. return res();
  400. }
  401. catch(err)
  402. {
  403. return rej(new Error(`Error while cleaning up directories: ${err}`));
  404. }
  405. });
  406. }
  407. //#SECTION print submission
  408. /**
  409. * Prints a submission to the console
  410. * @param {Submission} sub
  411. */
  412. function printSubmission(sub)
  413. {
  414. const lines = [
  415. `Submission #${currentSub} by ${sub.client}:`,
  416. ` Category: ${sub.joke.category}`,
  417. ` Type: ${sub.joke.type}`,
  418. ` Flags: ${extractFlags(sub.joke)}`,
  419. ``,
  420. ];
  421. if(sub.joke.type === "single")
  422. lines.push(sub.joke.joke);
  423. if(sub.joke.type === "twopart")
  424. {
  425. lines.push(sub.joke.setup);
  426. lines.push(sub.joke.delivery);
  427. }
  428. process.stdout.write(`${lines.join("\n")}\n\n`);
  429. }
  430. /**
  431. * Extracts flags of a joke submission, returning a string representation
  432. * @param {JokeSubmission} joke
  433. * @returns {string} Returns flags delimited with `, ` or "none" if no flags are set
  434. */
  435. function extractFlags(joke)
  436. {
  437. /** @type {JokeFlags[]} */
  438. const flags = [];
  439. Object.keys(joke.flags).forEach(key => {
  440. if(joke.flags[key] === true)
  441. flags.push(key);
  442. });
  443. return flags.length > 0 ? flags.join(", ") : "none";
  444. }
  445. /**
  446. * Called when all submissions have been gone through
  447. */
  448. function finishPrompts()
  449. {
  450. console.log("\nFinished going through submissions.\n");
  451. const statLines = [
  452. `Stats:`,
  453. ` Submissions acted upon: ${stats.submissionsActAmt}`,
  454. ` Submissions edited: ${stats.editedSubmissions}`,
  455. ` Submissions deleted: ${stats.deletedSubmissions}`,
  456. ];
  457. console.log(statLines.join("\n"));
  458. console.log(`\nExiting.\n`);
  459. exit(0);
  460. }
  461. /**
  462. * Waits for the user to press a key, then resolves with it
  463. * @param {string} [prompt]
  464. * @returns {Promise<Keypress, Error>}
  465. */
  466. function getKey(prompt)
  467. {
  468. return new Promise(async (res, rej) => {
  469. if(typeof prompt === "string")
  470. prompt = isEmpty(prompt) ? null : `${prompt.trimRight()} `;
  471. try
  472. {
  473. const onKey = (ch, key) => {
  474. if(key && key.ctrl && ["c", "d"].includes(key.name))
  475. process.exit(0);
  476. process.stdin.pause();
  477. process.stdin.removeListener("keypress", onKey);
  478. process.stdin.setRawMode(false);
  479. prompt && process.stdout.write("\n");
  480. return res({
  481. name: key.name || ch || "",
  482. ctrl: key.ctrl || false,
  483. meta: key.meta || false,
  484. shift: key.shift || false,
  485. sequence: key.sequence || undefined,
  486. code: key.code || undefined,
  487. });
  488. };
  489. process.stdin.setRawMode(true);
  490. process.stdin.on("keypress", onKey);
  491. prompt && process.stdout.write(prompt);
  492. process.stdin.resume();
  493. }
  494. catch(err)
  495. {
  496. return rej(new Error(`Error while getting key: ${err}`));
  497. }
  498. });
  499. }
  500. //#MARKER internal stuff
  501. /**
  502. * Reads all possible language codes and resolves with them
  503. * @returns {Promise<LangCodes[], Error>}
  504. */
  505. function getLangCodes()
  506. {
  507. return new Promise(async (res, rej) => {
  508. try
  509. {
  510. const file = await readFile(resolve(settings.languages.langFilePath));
  511. const parsed = JSON.parse(file.toString());
  512. return res(Object.keys(parsed));
  513. }
  514. catch(err)
  515. {
  516. return rej(new Error(`Error while reading language codes: ${err}`));
  517. }
  518. });
  519. }
  520. /**
  521. * Reads all submissions and resolves with them
  522. * @param {LangCodes} langCodes
  523. * @returns {Promise<ReadSubmissionsResult, Error>}
  524. */
  525. function readSubmissions(langCodes)
  526. {
  527. /** @type {AllSubmissions} */
  528. const allSubmissions = {};
  529. return new Promise(async (res, rej) => {
  530. try
  531. {
  532. const folders = await readdir(resolve(settings.jokes.jokeSubmissionPath));
  533. let amount = 0;
  534. if(folders.length < 1)
  535. {
  536. return res({
  537. submissions: [],
  538. amount,
  539. });
  540. }
  541. /** @type {Promise<void>[]} */
  542. const readPromises = [];
  543. folders.forEach(langCode => {
  544. langCode = langCode.toString();
  545. if(!langCodes.includes(langCode)) // ignore folders that aren't valid
  546. return;
  547. readPromises.push(new Promise(async readRes => {
  548. const subm = await getSubmissions(langCode);
  549. if(subm.length > 0)
  550. allSubmissions[langCode] = subm;
  551. amount += subm.length;
  552. return readRes();
  553. }));
  554. });
  555. await Promise.all(readPromises);
  556. return res({
  557. submissions: allSubmissions,
  558. amount,
  559. });
  560. }
  561. catch(err)
  562. {
  563. return rej(new Error(`Error while reading submissions: ${err}`));
  564. }
  565. });
  566. }
  567. /**
  568. * Reads all submissions of the specified language
  569. * @param {LangCodes} lang
  570. * @returns {Promise<Submission[], Error>}
  571. */
  572. function getSubmissions(lang)
  573. {
  574. return new Promise(async (res, rej) => {
  575. /** @type {Submission[]} */
  576. const submissions = [];
  577. try
  578. {
  579. const submissionsFolder = join(settings.jokes.jokeSubmissionPath, lang);
  580. const files = await readdir(submissionsFolder);
  581. for await(const fileName of files)
  582. {
  583. const path = resolve(submissionsFolder, fileName);
  584. const file = await readFile(path);
  585. /** @type {JokeSubmission} */
  586. const joke = JSON.parse(file);
  587. const valRes = parseJokes.validateSingle(joke, lang);
  588. let errors = null;
  589. if(Array.isArray(valRes))
  590. errors = valRes;
  591. const { client, timestamp } = parseFileName(fileName);
  592. submissions.push({ client, joke, timestamp, errors, lang, path });
  593. }
  594. return res(submissions);
  595. }
  596. catch(err)
  597. {
  598. return rej(new Error(`Error while reading submissions of language '${lang}': ${err}`));
  599. }
  600. });
  601. }
  602. /**
  603. * Parses the file name of a submission, returning its information
  604. * @param {string} fileName
  605. * @returns {Readonly<ParsedFileName>}
  606. */
  607. function parseFileName(fileName)
  608. {
  609. if(fileName.startsWith("submission_"))
  610. fileName = fileName.substring(11);
  611. if(fileName.endsWith(".json"))
  612. fileName = fileName.substring(0, fileName.length - 5);
  613. // eff8e7ca_0_1634205492859
  614. const [ client, index, timestamp ] = fileName.split("_");
  615. return Object.freeze({
  616. client,
  617. index: parseInt(index),
  618. timestamp: parseInt(timestamp),
  619. });
  620. }
  621. /**
  622. * Saves a submission to the local jokes
  623. * @param {Submission} sub
  624. */
  625. function saveSubmission(sub)
  626. {
  627. return new Promise(async (res, rej) => {
  628. try
  629. {
  630. stats.savedSubmissions++;
  631. stats.submissionsActAmt++;
  632. const { lang } = sub;
  633. const joke = reformatJoke(sub.joke);
  634. const jokeFilePath = join(settings.jokes.jokesFolderPath, `jokes-${lang}.json`);
  635. const templatePath = join(settings.jokes.jokesFolderPath, settings.jokes.jokesTemplateFile);
  636. if(!(await filesystem.exists(jokeFilePath)))
  637. await copyFile(templatePath, jokeFilePath);
  638. /** @type {JokesFile} */
  639. const currentJokesFile = JSON.parse((await readFile(jokeFilePath)).toString());
  640. /** @type {any} */
  641. const currentJokes = reserialize(currentJokesFile.jokes);
  642. const lastId = currentJokes[currentJokes.length - 1].id;
  643. // ensure props match and strip extraneous props
  644. joke.id = lastId + 1;
  645. joke.lang && delete joke.lang;
  646. joke.formatVersion && delete joke.formatVersion;
  647. currentJokes.push(joke);
  648. currentJokesFile.jokes = currentJokes;
  649. await writeFile(jokeFilePath, JSON.stringify(currentJokesFile, undefined, 4));
  650. await rm(sub.path);
  651. return res();
  652. }
  653. catch(err)
  654. {
  655. return rej(new Error(`Error while adding submission: ${err}`));
  656. }
  657. });
  658. }
  659. //#SECTION on execute
  660. try
  661. {
  662. if(!process.stdin.isTTY)
  663. throw new Errors.NoStdinError("The process doesn't have an stdin channel to read input from");
  664. else
  665. run();
  666. }
  667. catch(err)
  668. {
  669. console.error(`${col.red}${err.message}${col.rst}\n${err.stack}\n`);
  670. exit(1);
  671. }