backend.js 275 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796
  1. #!/usr/bin/env node
  2. "use strict";
  3. const path = require("path");
  4. const fs = require("fs");
  5. const promisesFs = fs.promises;
  6. const os = require('os');
  7. const envPaths = require("../server/node_modules/env-paths");
  8. const {cli} = require("../client/oasis_client");
  9. const SSBconfig = require('../server/SSB_server.js');
  10. const moment = require('../server/node_modules/moment');
  11. const FileType = require('../server/node_modules/file-type');
  12. const ssbRef = require("../server/node_modules/ssb-ref");
  13. const defaultConfig = {};
  14. const defaultConfigFile = path.join(envPaths("oasis", { suffix: "" }).config, "/default.json");
  15. let haveConfig = false;
  16. try {
  17. Object.assign(defaultConfig, JSON.parse(fs.readFileSync(defaultConfigFile, "utf8")));
  18. haveConfig = true;
  19. } catch (e) { if (e.code !== "ENOENT") { console.log(`Problem loading ${defaultConfigFile}`); throw e; } }
  20. const config = cli(defaultConfig, defaultConfigFile);
  21. if (config.debug) {
  22. process.env.DEBUG = "oasis,oasis:*";
  23. }
  24. const axiosMod = require('../server/node_modules/axios');
  25. const axios = axiosMod.default || axiosMod;
  26. const { spawn } = require('child_process');
  27. let fieldsForSnippet, buildContext, clip, publishExchange, getBestTrainedAnswer;
  28. try {
  29. ({ fieldsForSnippet, buildContext, clip, publishExchange, getBestTrainedAnswer } = require('../AI/buildAIContext.js'));
  30. } catch (e) {
  31. const noop = () => {};
  32. fieldsForSnippet = noop;
  33. buildContext = noop;
  34. clip = (t) => t;
  35. publishExchange = noop;
  36. getBestTrainedAnswer = () => null;
  37. }
  38. let aiStarted = false;
  39. function startAI() {
  40. if (aiStarted) return;
  41. aiStarted = true;
  42. try {
  43. const aiProcess = spawn('node', [path.resolve(__dirname, '../AI/ai_service.mjs')], { detached: true, stdio: 'ignore' });
  44. aiProcess.unref();
  45. } catch (e) {}
  46. }
  47. const ADDR_PATH = path.join(__dirname, '..', 'configs', 'wallet-addresses.json');
  48. const readAddrMap = () => { try { return JSON.parse(fs.readFileSync(ADDR_PATH, 'utf8')); } catch { return {}; } };
  49. const writeAddrMap = (map) => { fs.mkdirSync(path.dirname(ADDR_PATH), { recursive: true }); fs.writeFileSync(ADDR_PATH, JSON.stringify(map, null, 2)); };
  50. //parliament model
  51. let electionInFlight = null;
  52. const ensureTerm = async () => {
  53. const cur = await parliamentModel.getCurrentTerm().catch(() => null);
  54. if (cur) return cur;
  55. if (electionInFlight) return electionInFlight;
  56. electionInFlight = parliamentModel.resolveElection().catch(() => null).finally(() => { electionInFlight = null; });
  57. return electionInFlight;
  58. };
  59. let sweepInFlight = null;
  60. const runSweepOnce = async () => {
  61. if (sweepInFlight) return sweepInFlight;
  62. sweepInFlight = parliamentModel.sweepProposals().catch(e => console.error('sweepProposals failed:', e)).finally(() => { sweepInFlight = null; });
  63. return sweepInFlight;
  64. };
  65. async function buildState(filter) {
  66. const f = (filter || 'government').toLowerCase();
  67. await ensureTerm();
  68. await runSweepOnce();
  69. const [govCard, candidatures, proposals, canPropose, laws, historical] = await Promise.all([
  70. parliamentModel.getGovernmentCard(),
  71. parliamentModel.listCandidatures('OPEN'),
  72. parliamentModel.listProposalsCurrent(),
  73. parliamentModel.canPropose(),
  74. parliamentModel.listLaws(),
  75. parliamentModel.listHistorical()
  76. ]);
  77. return { filter: f, governmentCard: govCard, candidatures, proposals, canPropose, laws, historical };
  78. }
  79. function pickLeader(cands = []) {
  80. if (!cands.length) return null;
  81. return [...cands].sort((a, b) => {
  82. const d = (x, y) => y - x;
  83. return d(Number(a.votes||0), Number(b.votes||0)) || d(Number(a.karma||0), Number(b.karma||0)) ||
  84. (Number(a.profileSince||0) - Number(b.profileSince||0)) ||
  85. (new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()) ||
  86. String(a.targetId).localeCompare(String(b.targetId));
  87. })[0];
  88. }
  89. async function buildLeaderMeta(leader) {
  90. if (!leader) return null;
  91. if (leader.targetType === 'inhabitant') {
  92. let name = null, image = null, description = null;
  93. try { name = about?.name && await about.name(leader.targetId); } catch {}
  94. try { image = about?.image && await about.image(leader.targetId); } catch {}
  95. try { description = about?.description && await about.description(leader.targetId); } catch {}
  96. const imgId = typeof image === 'string' ? image : image?.link || image?.url || null;
  97. return { isTribe: false, name: name || leader.targetId, avatarUrl: imgId ? `/image/256/${encodeURIComponent(imgId)}` : '/assets/images/default-avatar.png', bio: typeof description === 'string' ? description : '' };
  98. }
  99. let tribe = null;
  100. try { tribe = await tribesModel.getTribeById(leader.targetId); } catch {}
  101. const imgId = tribe?.image || null;
  102. return { isTribe: true, name: leader.targetTitle || tribe?.title || tribe?.name || leader.targetId, avatarUrl: imgId ? `/image/256/${encodeURIComponent(imgId)}` : '/assets/images/default-tribe.png', bio: tribe?.description || '' };
  103. }
  104. const safeArr = v => Array.isArray(v) ? v : [];
  105. const safeText = v => String(v || '').trim();
  106. const safeReturnTo = (ctx, fb, ap) => { const rt = ctx.request?.body?.returnTo || ctx.query?.returnTo; return typeof rt === 'string' && ap?.some(p => rt.startsWith(p)) ? rt : fb; };
  107. // anti-injections
  108. const { stripDangerousTags, sanitizeHtml } = require('./sanitizeHtml');
  109. const sharedState = require('../configs/shared-state');
  110. module.exports = stripDangerousTags;
  111. const sanitizeMsgText = (msg) => {
  112. if (!msg?.value?.content) return msg;
  113. const c = msg.value.content;
  114. if (typeof c.text === 'string') c.text = stripDangerousTags(c.text);
  115. if (typeof c.description === 'string') c.description = stripDangerousTags(c.description);
  116. if (typeof c.title === 'string') c.title = stripDangerousTags(c.title);
  117. if (typeof c.contentWarning === 'string') c.contentWarning = stripDangerousTags(c.contentWarning);
  118. return msg;
  119. };
  120. const sanitizeMessages = (msgs) => Array.isArray(msgs) ? msgs.map(sanitizeMsgText) : msgs;
  121. const parseBool01 = v => String(Array.isArray(v) ? v[v.length - 1] : v || '') === '1';
  122. const checkMod = (ctx, mod) => {
  123. const cfg = getConfig();
  124. const serverValue = cfg.modules?.[mod];
  125. if (serverValue === 'off') return false;
  126. const cookieValue = ctx.cookies.get(mod);
  127. if (cookieValue) return cookieValue === 'on';
  128. return serverValue === 'on' || serverValue === undefined;
  129. };
  130. const getViewerId = () => SSBconfig?.config?.keys?.id || SSBconfig?.keys?.id;
  131. const getUserTribeIds = async (uid) => {
  132. const allTribes = await tribesModel.listAll().catch(() => []);
  133. const memberTribes = allTribes.filter(t => t.members.includes(uid));
  134. const idSets = await Promise.all(memberTribes.map(t => tribesModel.getChainIds(t.id).catch(() => [t.id])));
  135. return new Set(idSets.flat());
  136. };
  137. const refreshInboxCount = async (messagesOpt) => {
  138. const messages = messagesOpt || await pmModel.listAllPrivate();
  139. const userId = getViewerId();
  140. const isToUser = m => Array.isArray(m?.value?.content?.to) && m.value.content.to.includes(userId);
  141. const filtered = messages.filter(m => m && m.key && m.value && m.value.content && m.value.content.type === 'post' && m.value.content.private === true);
  142. sharedState.setInboxCount(filtered.filter(isToUser).length);
  143. };
  144. const mediaFavorites = require("./media-favorites.js");
  145. const customStyleFile = path.join(envPaths("oasis", { suffix: "" }).config, "/custom-style.css");
  146. let haveCustomStyle = false;
  147. try { fs.readFileSync(customStyleFile, "utf8"); haveCustomStyle = true; } catch (e) { if (e.code !== "ENOENT") { console.log(`Problem loading ${customStyleFile}`); throw e; } }
  148. const { get } = require("node:http");
  149. const debug = require("../server/node_modules/debug")("oasis");
  150. const log = (formatter, ...args) => {
  151. const isDebugEnabled = debug.enabled;
  152. debug.enabled = true;
  153. debug(formatter, ...args);
  154. debug.enabled = isDebugEnabled;
  155. };
  156. delete config._;
  157. delete config.$0;
  158. const { host } = config;
  159. const { port } = config;
  160. const url = `http://${host}:${port}`;
  161. debug("Current configuration: %O", config);
  162. debug(`You can save the above to ${defaultConfigFile} to make \
  163. these settings the default. See the readme for details.`);
  164. const { saveConfig, getConfig } = require('../configs/config-manager');
  165. const configPath = path.join(__dirname, '../configs/oasis-config.json');
  166. const oasisCheckPath = "/.well-known/oasis";
  167. process.on("uncaughtException", function (err) {
  168. if (err["code"] === "EADDRINUSE") {
  169. get(url + oasisCheckPath, (res) => {
  170. let rawData = "";
  171. res.on("data", (chunk) => {
  172. rawData += chunk;
  173. });
  174. res.on("end", () => {
  175. log(rawData);
  176. if (rawData === "oasis") {
  177. log(`Oasis is already running on host ${host} and port ${port}`);
  178. if (config.open === true) {
  179. log("Opening link to existing instance of Oasis");
  180. open(url);
  181. } else {
  182. log(
  183. "Not opening your browser because opening is disabled by your config"
  184. );
  185. }
  186. process.exit(0);
  187. } else {
  188. throw new Error(`Another server is already running at ${url}.
  189. It might be another copy of Oasis or another program on your computer.
  190. You can run Oasis on a different port number with this option:
  191. oasis --port ${config.port + 1}
  192. Alternatively, you can set the default port in ${defaultConfigFile} with:
  193. {
  194. "port": ${config.port + 1}
  195. }
  196. `);
  197. }
  198. });
  199. });
  200. } else {
  201. console.log("");
  202. console.log("Oasis traceback (share below content with devs to report!):");
  203. console.log("===========================================================");
  204. console.log(err);
  205. console.log("");
  206. }
  207. });
  208. process.argv = [];
  209. const http = require("../client/middleware");
  210. const {koaBody} = require("../server/node_modules/koa-body");
  211. const { nav, ul, li, a, form, button, div, section, h2, p } = require("../server/node_modules/hyperaxe");
  212. const open = require("../server/node_modules/open");
  213. const pull = require("../server/node_modules/pull-stream");
  214. const koaRouter = require("../server/node_modules/@koa/router");
  215. const ssbMentions = require("../server/node_modules/ssb-mentions");
  216. const isSvg = require('../server/node_modules/is-svg');
  217. const { isFeed, isMsg, isBlob } = require("../server/node_modules/ssb-ref");
  218. const ssb = require("../client/gui");
  219. const router = new koaRouter();
  220. const extractMentions = async (text) => {
  221. const mentions = ssbMentions(text) || [];
  222. const resolvedMentions = await Promise.all(mentions.map(async (mention) => {
  223. const name = mention.name || await about.name(mention.link);
  224. return {
  225. link: mention.link,
  226. name: name || 'Anonymous',
  227. };
  228. }));
  229. return resolvedMentions;
  230. };
  231. const cooler = ssb({ offline: config.offline, port: config.port, host: config.host, isPublic: config.public });
  232. const models = require("../models/main_models");
  233. const { about, blob, friend, meta, post, vote } = models({
  234. cooler,
  235. isPublic: config.public,
  236. });
  237. const { handleBlobUpload, serveBlob, FileTooLargeError } = require('../backend/blobHandler.js');
  238. const extractBlobId = (md) => md ? (md.match(/\((&[^)]+)\)/)?.[1] ?? null) : null;
  239. const exportmodeModel = require('../models/exportmode_model');
  240. const panicmodeModel = require('../models/panicmode_model');
  241. const cipherModel = require('../models/cipher_model');
  242. const legacyModel = require('../models/legacy_model');
  243. const walletModel = require('../models/wallet_model')
  244. const pmModel = require('../models/pm_model')({ cooler, isPublic: config.public });
  245. const bookmarksModel = require("../models/bookmarking_model")({ cooler, isPublic: config.public });
  246. const opinionsModel = require('../models/opinions_model')({ cooler, isPublic: config.public });
  247. const eventsModel = require('../models/events_model')({ cooler, isPublic: config.public });
  248. const tasksModel = require('../models/tasks_model')({ cooler, isPublic: config.public });
  249. const votesModel = require('../models/votes_model')({ cooler, isPublic: config.public });
  250. const ssbConfig = require('../server/ssb_config');
  251. const tribeCrypto = require('../models/tribe_crypto')(ssbConfig.path);
  252. const tribesModel = require('../models/tribes_model')({ cooler, isPublic: config.public, tribeCrypto });
  253. const reportsModel = require('../models/reports_model')({ cooler, isPublic: config.public });
  254. const transfersModel = require('../models/transfers_model')({ cooler, isPublic: config.public });
  255. const calendarsModel = require('../models/calendars_model')({ cooler, pmModel, tribeCrypto, tribesModel });
  256. const cvModel = require('../models/cv_model')({ cooler, isPublic: config.public });
  257. const inhabitantsModel = require('../models/inhabitants_model')({ cooler, isPublic: config.public });
  258. const feedModel = require('../models/feed_model')({ cooler, isPublic: config.public });
  259. const imagesModel = require("../models/images_model")({ cooler, isPublic: config.public });
  260. const audiosModel = require("../models/audios_model")({ cooler, isPublic: config.public });
  261. const torrentsModel = require("../models/torrents_model")({ cooler, isPublic: config.public, tribeCrypto, tribesModel });
  262. const videosModel = require("../models/videos_model")({ cooler, isPublic: config.public });
  263. const documentsModel = require("../models/documents_model")({ cooler, isPublic: config.public });
  264. const agendaModel = require("../models/agenda_model")({ cooler, isPublic: config.public });
  265. const trendingModel = require('../models/trending_model')({ cooler, isPublic: config.public });
  266. const statsModel = require('../models/stats_model')({ cooler, isPublic: config.public });
  267. const padsModel = require('../models/pads_model')({ cooler, cipherModel, tribeCrypto, tribesModel });
  268. const tagsModel = require('../models/tags_model')({ cooler, isPublic: config.public, padsModel, tribesModel });
  269. const tribesContentModel = require('../models/tribes_content_model')({ cooler, isPublic: config.public, tribeCrypto, tribesModel });
  270. const searchModel = require('../models/search_model')({ cooler, isPublic: config.public, padsModel });
  271. const activityModel = require('../models/activity_model')({ cooler, isPublic: config.public });
  272. const pixeliaModel = require('../models/pixelia_model')({ cooler, isPublic: config.public });
  273. const marketModel = require('../models/market_model')({ cooler, isPublic: config.public, tribeCrypto });
  274. const forumModel = require('../models/forum_model')({ cooler, isPublic: config.public });
  275. const blockchainModel = require('../models/blockchain_model')({ cooler, isPublic: config.public });
  276. const jobsModel = require('../models/jobs_model')({ cooler, isPublic: config.public, tribeCrypto });
  277. const shopsModel = require('../models/shops_model')({ cooler, isPublic: config.public, tribeCrypto });
  278. const chatsModel = require('../models/chats_model')({ cooler, tribeCrypto, tribesModel });
  279. const projectsModel = require("../models/projects_model")({ cooler, isPublic: config.public });
  280. const mapsModel = require("../models/maps_model")({ cooler, isPublic: config.public, tribeCrypto, tribesModel });
  281. const gamesModel = require('../models/games_model')({ cooler });
  282. const bankingModel = require("../models/banking_model")({ services: { cooler }, isPublic: config.public });
  283. const favoritesModel = require("../models/favorites_model")({ services: { cooler }, audiosModel, bookmarksModel, documentsModel, imagesModel, videosModel, mapsModel, padsModel, chatsModel, calendarsModel, torrentsModel });
  284. const logsModel = require("../models/logs_model")({ cooler });
  285. const parliamentModel = require('../models/parliament_model')({ cooler, services: { tribes: tribesModel, votes: votesModel, inhabitants: inhabitantsModel, banking: bankingModel } });
  286. const { renderGovernance: renderTribeGovernance } = require('../views/tribes_view');
  287. const viewerFilters = require('../models/viewer_filters');
  288. const scanPendingFollows = async (viewerId) => {
  289. if (!viewerId) return;
  290. if (!viewerFilters.isFrictionActive()) return;
  291. const pullStream = require('../server/node_modules/pull-stream');
  292. const ssbClient = await cooler.open();
  293. const limit = getConfig().ssbLogStream?.limit || 1000;
  294. const rows = await new Promise((res, rej) => {
  295. pullStream(
  296. ssbClient.createLogStream({ reverse: true, limit }),
  297. pullStream.collect((err, arr) => err ? rej(err) : res(arr || []))
  298. );
  299. });
  300. const accepted = new Set(viewerFilters.loadAccepted());
  301. const pendingIds = new Set(viewerFilters.listPending().map(x => x.followerId));
  302. for (const msg of rows) {
  303. const c = msg.value?.content;
  304. if (!c || c.type !== 'contact') continue;
  305. if (c.contact !== viewerId) continue;
  306. if (c.following !== true) continue;
  307. const author = msg.value?.author;
  308. if (!author || author === viewerId) continue;
  309. if (accepted.has(author)) continue;
  310. if (pendingIds.has(author)) continue;
  311. viewerFilters.enqueuePending(author);
  312. pendingIds.add(author);
  313. }
  314. };
  315. const { section: hSection } = require('../server/node_modules/hyperaxe');
  316. const renderPendingFollows = (items) => {
  317. const { template: tpl, i18n: i18nLocal } = require('../views/main_views');
  318. const { div, h2, p, form, button, input, ul, li, span, a } = require('../server/node_modules/hyperaxe');
  319. return tpl(
  320. i18nLocal.inhabitantsPendingFollowsTitle || 'Pending follow requests',
  321. hSection(
  322. div({ class: 'tags-header' },
  323. h2(i18nLocal.inhabitantsPendingFollowsTitle || 'Pending follow requests'),
  324. p(i18nLocal.pmMutualNotice || '')
  325. ),
  326. (!Array.isArray(items) || items.length === 0)
  327. ? p('—')
  328. : ul({}, items.map(it =>
  329. li({},
  330. span({ style: 'font-weight:bold' }, it.name || it.followerId),
  331. ' — ',
  332. span({ class: 'muted' }, it.followerId.slice(0, 14) + '…'),
  333. ' ',
  334. form({ method: 'POST', action: '/inhabitants/follow/accept', style: 'display:inline' },
  335. input({ type: 'hidden', name: 'followerId', value: it.followerId }),
  336. button({ type: 'submit', class: 'filter-btn' }, i18nLocal.inhabitantsPendingAccept || 'Accept')
  337. ),
  338. ' ',
  339. form({ method: 'POST', action: '/inhabitants/follow/reject', style: 'display:inline' },
  340. input({ type: 'hidden', name: 'followerId', value: it.followerId }),
  341. button({ type: 'submit', class: 'filter-btn' }, i18nLocal.inhabitantsPendingReject || 'Reject')
  342. )
  343. )
  344. ))
  345. )
  346. );
  347. };
  348. const makeCtxMutualCache = () => {
  349. const cache = new Map();
  350. const frictionActive = viewerFilters.isFrictionActive();
  351. return async (otherId) => {
  352. if (!otherId) return false;
  353. if (cache.has(otherId)) return cache.get(otherId);
  354. let rel;
  355. try { rel = await friend.getRelationship(otherId); } catch (e) { rel = null; }
  356. const basic = !!(rel && rel.following && rel.followsMe);
  357. const mutual = frictionActive ? (basic && viewerFilters.isAccepted(otherId)) : basic;
  358. cache.set(otherId, mutual);
  359. return mutual;
  360. };
  361. };
  362. const extractItemAuthor = (item) => {
  363. if (!item) return null;
  364. if (typeof item === 'string') return null;
  365. if (item.value && item.value.author) return item.value.author;
  366. if (item.author) return item.author;
  367. if (item.feed) return item.feed;
  368. if (item.organizer) return item.organizer;
  369. if (item.proposer) return item.proposer;
  370. if (item.owner) return item.owner;
  371. if (item.id && typeof item.id === 'string' && item.id.startsWith('@')) return item.id;
  372. return null;
  373. };
  374. const extractItemTribeId = (item) => {
  375. if (!item || typeof item !== 'object') return null;
  376. if (item.tribeId) return item.tribeId;
  377. if (item.value && item.value.content && item.value.content.tribeId) return item.value.content.tribeId;
  378. if (item.content && item.content.tribeId) return item.content.tribeId;
  379. return null;
  380. };
  381. const getViewerTribeAccessSets = async (userId) => {
  382. if (!userId) return { memberOf: new Set(), createdBy: new Set(), privateNotAccessible: new Set() };
  383. try {
  384. const all = await tribesModel.listAll();
  385. const memberOf = new Set();
  386. const createdBy = new Set();
  387. const privateNotAccessible = new Set();
  388. for (const t of all) {
  389. const isMember = Array.isArray(t.members) && t.members.includes(userId);
  390. const isCreator = t.author === userId;
  391. if (isCreator) { createdBy.add(t.id); memberOf.add(t.id); }
  392. else if (isMember) memberOf.add(t.id);
  393. const ancestryPrivate = await (async () => {
  394. try { const eff = await tribesModel.getEffectiveStatus(t.id); return eff.isPrivate; } catch (e) { return !!t.isAnonymous; }
  395. })();
  396. if (ancestryPrivate && !isMember && !isCreator) privateNotAccessible.add(t.id);
  397. }
  398. return { memberOf, createdBy, privateNotAccessible };
  399. } catch (e) {
  400. return { memberOf: new Set(), createdBy: new Set(), privateNotAccessible: new Set() };
  401. }
  402. };
  403. const applyListFilters = async (items, ctx, opts = {}) => {
  404. if (!Array.isArray(items)) return items;
  405. const cfg = getConfig();
  406. const viewer = getViewerId();
  407. const wishMutuals = cfg.wish === 'mutuals';
  408. let out = items;
  409. if (!opts.skipTribeAccess) {
  410. const { memberOf, createdBy, privateNotAccessible } = await getViewerTribeAccessSets(viewer);
  411. out = out.filter(it => {
  412. const tid = extractItemTribeId(it);
  413. if (!tid) return true;
  414. if (memberOf.has(tid) || createdBy.has(tid)) return true;
  415. if (privateNotAccessible.has(tid)) return false;
  416. return true;
  417. });
  418. }
  419. if (wishMutuals && !opts.skipMutual) {
  420. const isMutual = makeCtxMutualCache();
  421. const filtered = [];
  422. for (const it of out) {
  423. const a = extractItemAuthor(it);
  424. if (!a || a === viewer) { filtered.push(it); continue; }
  425. if (await isMutual(a)) filtered.push(it);
  426. }
  427. out = filtered;
  428. }
  429. return out;
  430. };
  431. const courtsModel = require('../models/courts_model')({ cooler, services: { votes: votesModel, inhabitants: inhabitantsModel, tribes: tribesModel, banking: bankingModel }, tribeCrypto });
  432. tribesModel.processIncomingKeys().then(async () => {
  433. try {
  434. const viewerId = getViewerId();
  435. const mine = (await tribesModel.listAll()).filter(t => t.author === viewerId);
  436. for (const t of mine) {
  437. await tribesModel.ensureTribeKeyDistribution(t.id).catch(() => {});
  438. }
  439. } catch (_) {}
  440. }).catch(err => {
  441. if (config.debug) console.error('tribe-keys scan error:', err.message);
  442. });
  443. courtsModel.processIncomingCourtsKeys().catch(err => {
  444. if (config.debug) console.error('courts-keys scan error:', err.message);
  445. });
  446. const getVoteComments = async (voteId) => {
  447. const raw = await post.topicComments(voteId);
  448. return (raw || []).filter(c => c?.value?.content?.type === 'post' && c.value.content.root === voteId)
  449. .sort((a, b) => (a?.value?.timestamp || 0) - (b?.value?.timestamp || 0));
  450. };
  451. const enrichWithComments = async (items, idKey = 'id') => {
  452. await Promise.all(items.map(async x => { x.commentCount = (await getVoteComments(x[idKey] || x.key || x.rootId)).length; }));
  453. return items;
  454. };
  455. const withCount = (item, comments) => ({ ...item, commentCount: comments.length });
  456. const resolveMapUrl = async (mapUrl) => {
  457. if (!mapUrl) return null;
  458. try {
  459. const mapKey = decodeURIComponent(String(mapUrl).replace(/^\/maps\//, ''));
  460. return await mapsModel.getMapById(mapKey, null);
  461. } catch (_) { return null; }
  462. };
  463. const mediaResolvers = {
  464. images: id => imagesModel.resolveRootId(id),
  465. audios: id => audiosModel.resolveRootId(id),
  466. videos: id => videosModel.resolveRootId(id),
  467. documents: id => documentsModel.resolveRootId(id),
  468. bookmarks: id => bookmarksModel.resolveRootId(id),
  469. shops: id => shopsModel.resolveRootId(id),
  470. chats: id => chatsModel.resolveRootId(id),
  471. maps: id => mapsModel.resolveRootId(id),
  472. pads: id => padsModel.resolveRootId(id),
  473. calendars: id => calendarsModel.resolveRootId(id),
  474. torrents: id => torrentsModel.resolveRootId(id)
  475. };
  476. const mediaModCheck = { images: 'imagesMod', audios: 'audiosMod', videos: 'videosMod', documents: 'documentsMod', bookmarks: 'bookmarksMod', market: 'marketMod', jobs: 'jobsMod', projects: 'projectsMod', shops: 'shopsMod', chats: 'chatsMod', maps: 'mapsMod', pads: 'padsMod', calendars: 'calendarsMod', torrents: 'torrentsMod' };
  477. const favAction = async (ctx, kind, action) => {
  478. if (!checkMod(ctx, mediaModCheck[kind])) { ctx.redirect('/modules'); return; }
  479. try {
  480. const rootId = await mediaResolvers[kind](ctx.params.id);
  481. if (rootId) await mediaFavorites[action + 'Favorite'](kind, rootId);
  482. } catch (_) {}
  483. ctx.redirect(safeReturnTo(ctx, `/${kind}`, [`/${kind}`]));
  484. };
  485. const commentAction = async (ctx, kind, idParam) => {
  486. const modKey = mediaModCheck[kind];
  487. if (modKey && !checkMod(ctx, modKey)) { ctx.redirect('/modules'); return; }
  488. const itemId = ctx.params[idParam];
  489. let text = stripDangerousTags((ctx.request.body.text || '').trim());
  490. const rt = safeReturnTo(ctx, `/${kind}/${encodeURIComponent(itemId)}`, [`/${kind}`]);
  491. const blobMarkdown = await handleBlobUpload(ctx, 'blob');
  492. if (blobMarkdown) text += blobMarkdown;
  493. if (!text) { ctx.redirect(rt); return; }
  494. await post.publish({ text, root: itemId, dest: itemId });
  495. ctx.redirect(rt);
  496. };
  497. const opinionModels = { images: imagesModel, audios: audiosModel, videos: videosModel, documents: documentsModel, bookmarks: bookmarksModel, torrents: torrentsModel };
  498. const deleteModels = { images: imagesModel, audios: audiosModel, videos: videosModel, documents: documentsModel, bookmarks: bookmarksModel, torrents: torrentsModel };
  499. const opinionAction = async (ctx, kind, idParam) => {
  500. const modKey = mediaModCheck[kind];
  501. if (modKey && !checkMod(ctx, modKey)) { ctx.redirect('/modules'); return; }
  502. await opinionModels[kind].createOpinion(ctx.params[idParam], ctx.params.category);
  503. ctx.redirect(safeReturnTo(ctx, `/${kind}`, [`/${kind}`]));
  504. };
  505. const deleteAction = async (ctx, kind, deleteFn = 'delete' + kind.charAt(0).toUpperCase() + kind.slice(1, -1) + 'ById') => {
  506. const modKey = mediaModCheck[kind];
  507. if (modKey && !checkMod(ctx, modKey)) { ctx.redirect('/modules'); return; }
  508. await deleteModels[kind][deleteFn](ctx.params.id);
  509. ctx.redirect(safeReturnTo(ctx, `/${kind}?filter=mine`, [`/${kind}`]));
  510. };
  511. const mediaCreateModels = { audios: audiosModel, videos: videosModel };
  512. const mediaCreateAction = async (ctx, kind) => {
  513. const modKey = mediaModCheck[kind];
  514. if (modKey && !checkMod(ctx, modKey)) { ctx.redirect('/modules'); return; }
  515. const blob = await handleBlobUpload(ctx, kind.slice(0, -1));
  516. const { tags, title, description, mapUrl } = ctx.request.body;
  517. await mediaCreateModels[kind][`create${kind.charAt(0).toUpperCase()}${kind.slice(1, -1)}`](blob, stripDangerousTags(tags), stripDangerousTags(title), stripDangerousTags(description), stripDangerousTags(mapUrl || ""));
  518. ctx.redirect(safeReturnTo(ctx, `/${kind}?filter=all`, [`/${kind}`]));
  519. };
  520. const mediaUpdateAction = async (ctx, kind) => {
  521. const modKey = mediaModCheck[kind];
  522. if (modKey && !checkMod(ctx, modKey)) { ctx.redirect('/modules'); return; }
  523. const { tags, title, description, mapUrl } = ctx.request.body;
  524. const singular = kind.slice(0, -1);
  525. const blob = ctx.request.files?.[singular] ? await handleBlobUpload(ctx, singular) : null;
  526. await mediaCreateModels[kind][`update${kind.charAt(0).toUpperCase()}${kind.slice(1, -1)}ById`](ctx.params.id, blob, stripDangerousTags(tags), stripDangerousTags(title), stripDangerousTags(description), stripDangerousTags(mapUrl || ""));
  527. ctx.redirect(safeReturnTo(ctx, `/${kind}?filter=mine`, [`/${kind}`]));
  528. };
  529. const qf = (ctx, def = 'all') => ctx.query.filter || def;
  530. const qp = (ctx, def = 1) => Math.max(1, parseInt(ctx.query.page) || def);
  531. about._startNameWarmup();
  532. async function renderBlobMarkdown(text, mentions = {}, myFeedId, myUsername) {
  533. if (!text) return '';
  534. const mentionByFeed = {};
  535. Object.values(mentions).forEach(arr => {
  536. arr.forEach(m => {
  537. mentionByFeed[m.feed] = m;
  538. });
  539. });
  540. text = text.replace(/\[@([^\]]+)\]\(([^)]+)\)/g, (_, name, id) => {
  541. return `<a class="mention" href="/author/${encodeURIComponent(id)}">@${name}</a>`;
  542. });
  543. const words = text.split(' ');
  544. text = (await Promise.all(
  545. words.map(async (word) => {
  546. const match = /@([A-Za-z0-9_\-\.+=\/]+\.ed25519)/.exec(word);
  547. if (match && match[1]) {
  548. const feedId = match[1];
  549. const feedWithAt = feedId.startsWith('@') ? feedId : `@${feedId}`;
  550. let resolvedName;
  551. if (feedId === myFeedId || feedWithAt === myFeedId) {
  552. resolvedName = myUsername;
  553. } else {
  554. try { resolvedName = await about.name(feedWithAt); } catch { resolvedName = feedId.slice(0, 8); }
  555. }
  556. return word.replace(match[0], `<a class="mention" href="/author/${encodeURIComponent(feedWithAt)}">@${resolvedName}</a>`);
  557. }
  558. return word;
  559. })
  560. )).join(' ');
  561. text = text
  562. .replace(/!\[image:[^\]]+\]\(([^)]+)\)/g, (_, id) =>
  563. `<img src="/blob/${encodeURIComponent(id)}" alt="image" class="post-image" />`)
  564. .replace(/\[audio:[^\]]+\]\(([^)]+)\)/g, (_, id) =>
  565. `<audio controls class="post-audio" src="/blob/${encodeURIComponent(id)}"></audio>`)
  566. .replace(/\[video:[^\]]+\]\(([^)]+)\)/g, (_, id) =>
  567. `<video controls class="post-video" src="/blob/${encodeURIComponent(id)}"></video>`)
  568. .replace(/\[pdf:([^\]]*)\]\(([^)]+)\)/g, (_, name, id) => {
  569. const { i18n } = require("../views/main_views");
  570. return `<a class="post-pdf" href="/blob/${encodeURIComponent(id)}" target="_blank">${name || (i18n && i18n.pdfFallbackLabel) || 'PDF'}</a>`;
  571. });
  572. return text;
  573. }
  574. async function resolveMentionText(text) {
  575. if (!text || typeof text !== 'string') return text;
  576. const mentionRe = /@([A-Za-z0-9_\-\.+=\/]+\.ed25519)/g;
  577. const matches = [...text.matchAll(mentionRe)];
  578. if (!matches.length) return text;
  579. const seen = new Map();
  580. for (const m of matches) {
  581. const raw = m[1];
  582. const feed = raw.startsWith('@') ? raw : `@${raw}`;
  583. if (seen.has(feed)) continue;
  584. let name;
  585. try { name = await about.name(feed); } catch { name = feed.slice(1, 9); }
  586. seen.set(feed, name);
  587. }
  588. return text.replace(mentionRe, (full, id) => {
  589. const feed = id.startsWith('@') ? id : `@${id}`;
  590. const name = seen.get(feed) || feed.slice(1, 9);
  591. return `[@${name}](${feed})`;
  592. });
  593. }
  594. const preparePreview = async function (ctx) {
  595. let text = String(ctx.request.body.text || "")
  596. const contentWarning = stripDangerousTags(String(ctx.request.body.contentWarning || ""))
  597. const ensureAt = (id) => {
  598. const s = String(id || "")
  599. if (!s) return ""
  600. return s.startsWith("@") ? s : `@${s.replace(/^@+/, "")}`
  601. }
  602. const stripAt = (id) => String(id || "").replace(/^@+/, "")
  603. const norm = (s) => String(s || "").trim().toLowerCase()
  604. const ssbClient = await cooler.open()
  605. const authorMeta = {
  606. id: ssbClient.id,
  607. name: await about.name(ssbClient.id),
  608. image: await about.image(ssbClient.id),
  609. }
  610. const myId = String(authorMeta.id)
  611. text = text.replace(
  612. /\[@([^\]]+)\]\s*\(\s*@?([^) \t\r\n]+\.ed25519)\s*\)/g,
  613. (_m, label, feed) => `[@${label}](@${stripAt(feed)})`
  614. )
  615. const mentions = {}
  616. const normalizeMatch = (m) => {
  617. const feed = ensureAt(m?.feed || m?.link || m?.id || "")
  618. const name = String(m?.name || "")
  619. const img = m?.img || m?.image || null
  620. const rel = m?.rel || {}
  621. return { ...m, feed, name, img, rel }
  622. }
  623. const pushUnique = (key, arr) => {
  624. const prev = Array.isArray(mentions[key]) ? mentions[key] : []
  625. const seen = new Set(prev.map((x) => String(x?.feed || "")))
  626. const out = prev.slice()
  627. for (const x of arr) {
  628. const f = String(x?.feed || "")
  629. if (!f) continue
  630. if (seen.has(f)) continue
  631. seen.add(f)
  632. out.push(x)
  633. }
  634. if (out.length) mentions[key] = out
  635. }
  636. const chooseByPhrase = (matches, phrase) => {
  637. const p = norm(phrase)
  638. const exact = matches.filter((mm) => norm(mm.name) === p)
  639. if (exact.length) return exact
  640. const starts = matches.filter((mm) => norm(mm.name).startsWith(p))
  641. if (starts.length) return starts
  642. const incl = matches.filter((mm) => norm(mm.name).includes(p))
  643. if (incl.length) return incl
  644. return null
  645. }
  646. const rex = /(^|\s)(?!\[)@([a-zA-Z0-9\-/.=+]{3,})(?:\s+([a-zA-Z0-9][a-zA-Z0-9\-/.=+]{1,}))?(?:\s+([a-zA-Z0-9][a-zA-Z0-9\-/.=+]{1,}))?\b/g
  647. let m
  648. while ((m = rex.exec(text)) !== null) {
  649. const w1 = m[2]
  650. const w2 = m[3]
  651. const w3 = m[4]
  652. if (/\.ed25519$/.test(w1)) {
  653. const feed = ensureAt(w1)
  654. const [name, img, rel] = await Promise.all([
  655. about.name(feed),
  656. about.image(feed),
  657. friend.getRelationship(feed).catch(() => ({ followsMe: false, following: false, blocking: false, me: false }))
  658. ])
  659. pushUnique(w1, [{ feed, name, img, rel }])
  660. continue
  661. }
  662. const phrase1 = w1
  663. const phrase2 = w2 ? `${w1} ${w2}` : null
  664. const phrase3 = w3 ? `${w1} ${w2 ? w2 : ""} ${w3}`.replace(/\s+/g, " ").trim() : null
  665. const matchesRaw = about.named(w1) || []
  666. const matchesAll = matchesRaw.map(normalizeMatch)
  667. const matches = matchesAll.filter((mm) => String(mm.feed) !== myId && !mm?.rel?.me)
  668. let chosenKey = phrase1
  669. let chosenMatches = matches
  670. if (phrase3) {
  671. const best3 = chooseByPhrase(matches, phrase3)
  672. if (best3 && best3.length) {
  673. chosenKey = phrase3
  674. chosenMatches = best3
  675. } else if (phrase2) {
  676. const best2 = chooseByPhrase(matches, phrase2)
  677. if (best2 && best2.length) {
  678. chosenKey = phrase2
  679. chosenMatches = best2
  680. }
  681. }
  682. } else if (phrase2) {
  683. const best2 = chooseByPhrase(matches, phrase2)
  684. if (best2 && best2.length) {
  685. chosenKey = phrase2
  686. chosenMatches = best2
  687. }
  688. }
  689. if (chosenMatches.length > 0) {
  690. pushUnique(chosenKey, chosenMatches)
  691. }
  692. }
  693. Object.keys(mentions).forEach((key) => {
  694. const matches = Array.isArray(mentions[key]) ? mentions[key] : []
  695. const meaningful = matches.filter((mm) => (mm?.rel?.followsMe || mm?.rel?.following) && !mm?.rel?.blocking && String(mm?.feed || "") !== myId && !mm?.rel?.me)
  696. mentions[key] = meaningful.length > 0 ? meaningful : matches
  697. })
  698. const rexReplace = /(^|\s)(?!\[)@([a-zA-Z0-9\-/.=+]{3,})(?:\s+([a-zA-Z0-9][a-zA-Z0-9\-/.=+]{1,}))?(?:\s+([a-zA-Z0-9][a-zA-Z0-9\-/.=+]{1,}))?\b/g
  699. const replacer = (match, prefix, w1, w2, w3) => {
  700. const phrase1 = w1
  701. const phrase2 = w2 ? `${w1} ${w2}` : null
  702. const phrase3 = w3 ? `${w1} ${w2 ? w2 : ""} ${w3}`.replace(/\s+/g, " ").trim() : null
  703. const tryKey = (k) => {
  704. const arr = mentions[k]
  705. if (arr && arr.length === 1) {
  706. return `${prefix}[@${arr[0].name}](${ensureAt(arr[0].feed)})`
  707. }
  708. return null
  709. }
  710. if (/\.ed25519$/.test(w1)) {
  711. const arr = mentions[w1]
  712. if (arr && arr.length === 1) return `${prefix}[@${arr[0].name}](${ensureAt(arr[0].feed)})`
  713. return match
  714. }
  715. const r3 = phrase3 ? tryKey(phrase3) : null
  716. if (r3) return r3
  717. const r2 = phrase2 ? tryKey(phrase2) : null
  718. if (r2) return r2
  719. const r1 = tryKey(phrase1)
  720. if (r1) return r1
  721. return match
  722. }
  723. text = text.replace(rexReplace, replacer)
  724. const blobMarkdown = await handleBlobUpload(ctx, "blob")
  725. if (blobMarkdown) {
  726. text += blobMarkdown
  727. }
  728. const renderedText = await renderBlobMarkdown(
  729. text,
  730. mentions,
  731. authorMeta.id,
  732. authorMeta.name
  733. )
  734. const hasBrTags = /<br\s*\/?>/i.test(renderedText)
  735. const hasBlockTags = /<(p|div|ul|ol|li|pre|blockquote|h[1-6]|table|tr|td|th|section|article)\b/i.test(renderedText)
  736. let formattedText = renderedText
  737. if (!hasBrTags && !hasBlockTags && /[\r\n]/.test(renderedText)) {
  738. formattedText = renderedText.replace(/\r\n|\r|\n/g, "<br>")
  739. }
  740. return { authorMeta, text, formattedText, mentions, contentWarning }
  741. }
  742. const megabyte = Math.pow(2, 20);
  743. const maxSize = 50 * megabyte;
  744. const homeDir = os.homedir();
  745. const blobsPath = path.join(homeDir, '.ssb', 'blobs', 'tmp');
  746. const gossipPath = path.join(homeDir, '.ssb', 'gossip.json');
  747. const unfollowedPath = path.join(homeDir, '.ssb', 'gossip_unfollowed.json');
  748. const ensureJSONFile = (p, init = []) => { fs.mkdirSync(path.dirname(p), { recursive: true }); if (!fs.existsSync(p)) fs.writeFileSync(p, JSON.stringify(init, null, 2), 'utf8'); };
  749. const readJSON = p => { ensureJSONFile(p, []); try { return JSON.parse(fs.readFileSync(p, 'utf8') || '[]'); } catch { return []; } };
  750. const writeJSON = (p, d) => { fs.mkdirSync(path.dirname(p), { recursive: true }); fs.writeFileSync(p, JSON.stringify(d, null, 2), 'utf8'); };
  751. const canonicalKey = k => { let c = String(k).replace(/^@/, '').replace(/\.ed25519$/, '').replace(/-/g, '+').replace(/_/g, '/'); if (!c.endsWith('=')) c += '='; return `@${c}.ed25519`; };
  752. const msAddrFrom = (h, p, k) => `net:${h}:${Number(p) || 8008}~shs:${canonicalKey(k).slice(1, -9)}`;
  753. ensureJSONFile(gossipPath, []);
  754. ensureJSONFile(unfollowedPath, []);
  755. const koaBodyMiddleware = koaBody({
  756. multipart: true,
  757. formidable: {
  758. uploadDir: blobsPath,
  759. keepExtensions: true,
  760. maxFieldsSize: maxSize,
  761. maxFileSize: maxSize,
  762. hash: 'sha256',
  763. },
  764. parsedMethods: ['POST'],
  765. });
  766. const resolveCommentComponents = async function (ctx) {
  767. let parentId;
  768. try {
  769. parentId = decodeURIComponent(ctx.params.message);
  770. } catch {
  771. parentId = ctx.params.message;
  772. }
  773. const parentMessage = await post.get(parentId);
  774. if (!parentMessage || !parentMessage.value) {
  775. throw new Error("Invalid parentMessage or missing 'value'");
  776. }
  777. const myFeedId = await meta.myFeedId();
  778. const hasRoot =
  779. typeof parentMessage?.value?.content?.root === "string" &&
  780. ssbRef.isMsg(parentMessage.value.content.root);
  781. const hasFork =
  782. typeof parentMessage?.value?.content?.fork === "string" &&
  783. ssbRef.isMsg(parentMessage.value.content.fork);
  784. const rootMessage = hasRoot
  785. ? hasFork
  786. ? parentMessage
  787. : await post.get(parentMessage.value.content.root)
  788. : parentMessage;
  789. const messages = await post.topicComments(rootMessage.key);
  790. messages.push(rootMessage);
  791. let contentWarning;
  792. if (ctx.request.body) {
  793. const rawContentWarning = stripDangerousTags(String(ctx.request.body.contentWarning || "").trim());
  794. contentWarning = rawContentWarning.length > 0 ? rawContentWarning : undefined;
  795. }
  796. return { messages, myFeedId, parentMessage, contentWarning };
  797. };
  798. const { authorView, previewCommentView, commentView, editProfileView, extendedView, latestView, likesView, threadView, hashtagView, mentionsView, popularView, previewView, privateView, publishCustomView, publishView, previewSubtopicView, subtopicView, imageSearchView, setLanguage, topicsView, summaryView, threadsView, tribeAccessDeniedView, inviteRequiredView } = require("../views/main_views");
  799. const { activityView } = require("../views/activity_view");
  800. const { cvView, createCVView } = require("../views/cv_view");
  801. const { indexingView } = require("../views/indexing_view");
  802. const { pixeliaView } = require("../views/pixelia_view");
  803. const { gamesView } = require("../views/games_view");
  804. const { statsView } = require("../views/stats_view");
  805. const { tribesView, tribeView, renderInvitePage } = require("../views/tribes_view");
  806. const { agendaView } = require("../views/agenda_view");
  807. const { documentView, singleDocumentView } = require("../views/document_view");
  808. const { inhabitantsView, inhabitantsProfileView } = require("../views/inhabitants_view");
  809. const { walletViewRender, walletView, walletHistoryView, walletReceiveView, walletSendFormView, walletSendConfirmView, walletSendResultView, walletErrorView } = require("../views/wallet_view");
  810. const { pmView } = require("../views/pm_view");
  811. const { tagsView } = require("../views/tags_view");
  812. const { videoView, singleVideoView } = require("../views/video_view");
  813. const { audioView, singleAudioView } = require("../views/audio_view");
  814. const { torrentsView, singleTorrentView } = require("../views/torrents_view");
  815. const { eventView, singleEventView } = require("../views/event_view");
  816. const { invitesView } = require("../views/invites_view");
  817. const { modulesView } = require("../views/modules_view");
  818. const { reportView, singleReportView } = require("../views/report_view");
  819. const { taskView, singleTaskView } = require("../views/task_view");
  820. const { voteView } = require("../views/vote_view");
  821. const { bookmarkView, singleBookmarkView } = require("../views/bookmark_view");
  822. const { feedView, feedCreateView, singleFeedView } = require("../views/feed_view");
  823. const { legacyView } = require("../views/legacy_view");
  824. const { opinionsView } = require("../views/opinions_view");
  825. const { peersView } = require("../views/peers_view");
  826. const { searchView } = require("../views/search_view");
  827. const { transferView, singleTransferView } = require("../views/transfer_view");
  828. const { cipherView } = require("../views/cipher_view");
  829. const { imageView, singleImageView } = require("../views/image_view");
  830. const { mapsView, singleMapView } = require("../views/maps_view");
  831. const { settingsView } = require("../views/settings_view");
  832. const { trendingView } = require("../views/trending_view");
  833. const { marketView, singleMarketView } = require("../views/market_view");
  834. const { aiView } = require("../views/AI_view");
  835. const { forumView, singleForumView } = require("../views/forum_view");
  836. const { renderBlockchainView, renderSingleBlockView } = require("../views/blockchain_view");
  837. const { jobsView, singleJobsView, renderJobForm } = require("../views/jobs_view");
  838. const { shopsView, singleShopView, singleProductView, editProductView } = require("../views/shops_view");
  839. const { chatsView, singleChatView, renderChatInvitePage } = require("../views/chats_view");
  840. const { padsView, singlePadView, renderPadInvitePage } = require("../views/pads_view");
  841. const { calendarsView, singleCalendarView } = require("../views/calendars_view");
  842. const { projectsView, singleProjectView } = require("../views/projects_view")
  843. const { renderBankingView, renderSingleAllocationView, renderEpochView } = require("../views/banking_views")
  844. const { favoritesView } = require("../views/favorites_view");
  845. const { logsView } = require("../views/logs_view");
  846. const { buildLogsPdf } = require("./logsPdf");
  847. const { parliamentView } = require("../views/parliament_view");
  848. const { courtsView, courtsCaseView } = require('../views/courts_view');
  849. let sharp;
  850. try {
  851. sharp = require("sharp");
  852. } catch (e) {
  853. }
  854. const readmePath = path.join(__dirname, "..", ".." ,"README.md");
  855. const packagePath = path.join(__dirname, "..", "server", "package.json");
  856. const readme = fs.readFileSync(readmePath, "utf8");
  857. const version = JSON.parse(fs.readFileSync(packagePath, "utf8")).version;
  858. const nullImageId = '&0000000000000000000000000000000000000000000=.sha256';
  859. const getAvatarUrl = img => !img || img === nullImageId ? '/assets/images/default-avatar.png' : `/image/256/${encodeURIComponent(img)}`;
  860. const MAX_TITLE_LENGTH = 150;
  861. const MAX_TEXT_LENGTH = 8000;
  862. const parseSizeMB = (s) => { if (!s) return 0; const m = String(s).match(/([\d.]+)\s*(GB|MB|KB|B)/i); if (!m) return 0; const v = parseFloat(m[1]), u = m[2].toUpperCase(); return u === 'GB' ? v * 1024 : u === 'MB' ? v : u === 'KB' ? v / 1024 : v / (1024 * 1024); };
  863. const tooLong = (ctx, value, max, label) => {
  864. if (value && value.length > max) {
  865. ctx.status = 400;
  866. ctx.body = `${label} too long (max ${max})`;
  867. return true;
  868. }
  869. return false;
  870. };
  871. router
  872. .param("imageSize", (imageSize, ctx, next) => {
  873. const size = Number(imageSize);
  874. const isInteger = size % 1 === 0;
  875. const overMinSize = size > 2;
  876. const underMaxSize = size <= 256;
  877. ctx.assert(
  878. isInteger && overMinSize && underMaxSize,
  879. 400,
  880. "Invalid image size"
  881. );
  882. return next();
  883. })
  884. .param("blobId", (blobId, ctx, next) => {
  885. ctx.assert(ssbRef.isBlob(blobId), 400, "Invalid blob link");
  886. return next();
  887. })
  888. .param("message", (message, ctx, next) => {
  889. ctx.assert(ssbRef.isMsg(message), 400, "Invalid message link");
  890. return next();
  891. })
  892. .param("feed", (message, ctx, next) => {
  893. ctx.assert(ssbRef.isFeedId(message), 400, "Invalid feed link");
  894. return next();
  895. })
  896. .get("/", async (ctx) => {
  897. const currentConfig = getConfig();
  898. const homePage = currentConfig.homePage || "activity";
  899. ctx.redirect(`/${homePage}`);
  900. })
  901. .get("/robots.txt", (ctx) => {
  902. ctx.body = "User-agent: *\nDisallow: /";
  903. })
  904. .get(oasisCheckPath, (ctx) => {
  905. ctx.body = "oasis";
  906. })
  907. .get('/stats', async (ctx) => {
  908. const filter = qf(ctx, 'ALL'), stats = await statsModel.getStats(filter);
  909. const myId = getViewerId();
  910. const myAddress = await bankingModel.getUserAddress(myId);
  911. const addrRows = await bankingModel.listAddressesMerged();
  912. stats.banking = {
  913. myAddress: myAddress || null,
  914. totalAddresses: Array.isArray(addrRows) ? addrRows.length : 0
  915. };
  916. try { stats.logsCount = await logsModel.countLogs(); } catch { stats.logsCount = 0; }
  917. const totalMB = parseSizeMB(stats.statsBlobsSize) + parseSizeMB(stats.statsBlockchainSize);
  918. const hcT = parseFloat((totalMB * 0.0002 * 475).toFixed(2));
  919. const inhabitants = stats.usersKPIs?.totalInhabitants || stats.inhabitants || 1;
  920. const hcH = inhabitants > 0 ? parseFloat((hcT / inhabitants).toFixed(2)) : 0;
  921. sharedState.setCarbonHcT(hcT);
  922. sharedState.setCarbonHcH(hcH);
  923. ctx.body = statsView(stats, filter);
  924. })
  925. .get("/public/popular/:period", async (ctx) => {
  926. if (!checkMod(ctx, 'popularMod')) return ctx.redirect('/modules');
  927. const i18n = require("../client/assets/translations/i18n"), lang = ctx.cookies.get('language') || getConfig().language || 'en', t = i18n[lang] || i18n['en'];
  928. const messages = sanitizeMessages(await post.popular({ period: ctx.params.period }));
  929. ctx.body = await popularView({ messages, prefix: nav(div({ class: "filters" }, ul(['day','week','month','year'].map(p => li(form({ method: "GET", action: `/public/popular/${p}` }, button({ type: "submit", class: "filter-btn" }, t[p]))))))) });
  930. })
  931. .get("/modules", async (ctx) => {
  932. const modules = ['popular', 'topics', 'summaries', 'latest', 'threads', 'multiverse', 'invites', 'wallet', 'legacy', 'cipher', 'bookmarks', 'calendars', 'chats', 'videos', 'docs', 'audios', 'tags', 'images', 'maps', 'trending', 'events', 'tasks', 'market', 'tribes', 'votes', 'reports', 'opinions', 'pads', 'transfers', 'feed', 'pixelia', 'agenda', 'favorites', 'ai', 'forum', 'games', 'jobs', 'projects', 'shops', 'banking', 'parliament', 'courts'];
  933. const cfg = getConfig().modules;
  934. ctx.body = modulesView(modules.reduce((acc, m) => { acc[`${m}Mod`] = cfg[`${m}Mod`]; return acc; }, {}));
  935. })
  936. .get('/ai', async (ctx) => {
  937. if (!checkMod(ctx, 'aiMod')) return ctx.redirect('/modules');
  938. startAI();
  939. const lang = ctx.cookies.get('language') || getConfig().language || 'en', historyPath = path.join(__dirname, '..', '..', 'src', 'configs', 'AI-history.json');
  940. require('../views/main_views').setLanguage(lang);
  941. let chatHistory = []; try { chatHistory = JSON.parse(fs.readFileSync(historyPath, 'utf-8')); } catch {}
  942. ctx.body = aiView(chatHistory, getConfig().ai?.prompt?.trim() || '');
  943. })
  944. .get('/games', async (ctx) => {
  945. if (!checkMod(ctx, 'gamesMod')) { ctx.redirect('/modules'); return; }
  946. const filter = qf(ctx, 'all');
  947. const hall = await gamesModel.getHallOfFame();
  948. ctx.body = gamesView(filter, hall);
  949. })
  950. .get('/games/:name', async (ctx) => {
  951. if (!checkMod(ctx, 'gamesMod')) { ctx.redirect('/modules'); return; }
  952. const { gameShellView } = require('../views/games_view');
  953. ctx.body = gameShellView(ctx.params.name);
  954. })
  955. .post('/games/submit-score', koaBody(), async (ctx) => {
  956. if (!checkMod(ctx, 'gamesMod')) { ctx.redirect('/modules'); return; }
  957. const { game, score } = ctx.request.body;
  958. try { await gamesModel.submitScore(game, score); } catch (_) {}
  959. ctx.redirect('/games?filter=scoring');
  960. })
  961. .get('/pixelia', async (ctx) => {
  962. if (!checkMod(ctx, 'pixeliaMod')) { ctx.redirect('/modules'); return; }
  963. const pixelArt = await pixeliaModel.listPixels();
  964. ctx.body = pixeliaView(pixelArt);
  965. })
  966. .get('/blockexplorer', async (ctx) => {
  967. const userId = getViewerId();
  968. const query = ctx.query || {};
  969. const search = {
  970. id: query.id || '',
  971. author: query.author || '',
  972. from: query.from || '',
  973. to: query.to || ''
  974. };
  975. const searchActive = Object.values(search).some(v => String(v || '').trim().length > 0);
  976. let filter = query.filter || 'recent';
  977. if (searchActive && String(filter).toLowerCase() === 'recent') filter = 'all';
  978. const blockchainData = await blockchainModel.listBlockchain(filter, userId, search);
  979. const allTribesList = await tribesModel.listAll().catch(() => []);
  980. const anonTribeSet = new Set(allTribesList.filter(tr => tr.isAnonymous === true).map(tr => tr.id));
  981. for (const block of blockchainData) {
  982. const c = block.content || {};
  983. const t = c.type || block.type || '';
  984. const isPrivate = String(c.isPublic || '').toLowerCase() === 'private';
  985. block.restricted = t === 'tribe' || t.startsWith('courts') || t === 'job' || t === 'job_sub' ||
  986. c.status === 'INVITE-ONLY' || c.status === 'PRIVATE' ||
  987. (c.tribeId && anonTribeSet.has(c.tribeId)) || isPrivate;
  988. }
  989. ctx.body = renderBlockchainView(blockchainData, filter, userId, search);
  990. })
  991. .get('/blockexplorer/block/:id', async (ctx) => {
  992. const userId = getViewerId();
  993. const query = ctx.query || {};
  994. const search = {
  995. id: query.id || '',
  996. author: query.author || '',
  997. from: query.from || '',
  998. to: query.to || ''
  999. };
  1000. const searchActive = Object.values(search).some(v => String(v || '').trim().length > 0);
  1001. let filter = query.filter || 'recent';
  1002. if (searchActive && String(filter).toLowerCase() === 'recent') filter = 'all';
  1003. const blockId = ctx.params.id;
  1004. const block = await blockchainModel.getBlockById(blockId, userId);
  1005. const viewMode = query.view || 'block';
  1006. let restricted = false;
  1007. if (block) {
  1008. const c = block.value?.content || {};
  1009. const t = c.type || '';
  1010. const allTribes = await tribesModel.listAll().catch(() => []);
  1011. const anonTribeIds = new Set(allTribes.filter(tr => tr.isAnonymous === true).map(tr => tr.id));
  1012. const isPrivate = String(c.isPublic || '').toLowerCase() === 'private';
  1013. restricted = t === 'tribe' ||
  1014. t.startsWith('courts') ||
  1015. t === 'job' || t === 'job_sub' ||
  1016. c.status === 'INVITE-ONLY' || c.status === 'PRIVATE' ||
  1017. (c.tribeId && anonTribeIds.has(c.tribeId)) ||
  1018. isPrivate;
  1019. }
  1020. ctx.body = renderSingleBlockView(block, filter, userId, search, viewMode, restricted);
  1021. })
  1022. .get("/public/latest", async (ctx) => {
  1023. if (!checkMod(ctx, 'latestMod')) { ctx.redirect('/modules'); return; }
  1024. const messages = sanitizeMessages(await post.latest());
  1025. ctx.body = await latestView({ messages });
  1026. })
  1027. .get("/public/latest/extended", async (ctx) => {
  1028. if (!checkMod(ctx, 'extendedMod')) { ctx.redirect('/modules'); return; }
  1029. const messages = sanitizeMessages(await post.latestExtended());
  1030. ctx.body = await extendedView({ messages });
  1031. })
  1032. .get("/public/latest/topics", async (ctx) => {
  1033. if (!checkMod(ctx, 'topicsMod')) { ctx.redirect('/modules'); return; }
  1034. const messages = sanitizeMessages(await post.latestTopics());
  1035. const channels = await post.channels();
  1036. const list = channels.map((c) => {
  1037. return li(a({ href: `/hashtag/${c}` }, `#${c}`));
  1038. });
  1039. const prefix = nav(ul(list));
  1040. ctx.body = await topicsView({ messages, prefix });
  1041. })
  1042. .get("/public/latest/summaries", async (ctx) => {
  1043. if (!checkMod(ctx, 'summariesMod')) { ctx.redirect('/modules'); return; }
  1044. const messages = sanitizeMessages(await post.latestSummaries());
  1045. ctx.body = await summaryView({ messages });
  1046. })
  1047. .get("/public/latest/threads", async (ctx) => {
  1048. if (!checkMod(ctx, 'threadsMod')) { ctx.redirect('/modules'); return; }
  1049. const messages = sanitizeMessages(await post.latestThreads());
  1050. ctx.body = await threadsView({ messages });
  1051. })
  1052. .get('/author/:feed', async (ctx) => {
  1053. const feedId = decodeURIComponent(ctx.params.feed || ''), gt = Number(ctx.request.query.gt || -1), lt = Number(ctx.request.query.lt || -1);
  1054. if (lt > 0 && gt > 0 && gt >= lt) throw new Error('Given search range is empty');
  1055. const [description, name, image, messages, firstPost, lastPost, relationship, ecoAddress, bankData] = await Promise.all([
  1056. about.description(feedId), about.name(feedId), about.image(feedId), post.fromPublicFeed(feedId, gt, lt),
  1057. post.firstBy(feedId), post.latestBy(feedId), friend.getRelationship(feedId), bankingModel.getUserAddress(feedId), bankingModel.getBankingData(feedId)
  1058. ]);
  1059. const sanitizedMsgs = sanitizeMessages(messages);
  1060. const normTs = t => { const n = Number(t || 0); return !isFinite(n) || n <= 0 ? 0 : n < 1e12 ? n * 1000 : n; };
  1061. const pull = require('../server/node_modules/pull-stream'), ssb = await require('../client/gui')({ offline: require('../server/ssb_config').offline }).open();
  1062. const latestFromStream = await new Promise(res => pull(ssb.createUserStream({ id: feedId, reverse: true }), pull.filter(m => m?.value?.content?.type !== 'tombstone'), pull.take(1), pull.collect((err, arr) => res(!err && arr?.[0] ? normTs(arr[0].value?.timestamp || arr[0].timestamp) : 0))));
  1063. const days = latestFromStream ? (Date.now() - latestFromStream) / 86400000 : Infinity;
  1064. ctx.body = await authorView({ feedId, messages: sanitizedMsgs, firstPost, lastPost, name, description, avatarUrl: getAvatarUrl(image), relationship, ecoAddress, karmaScore: bankData.karmaScore, estimatedUBI: bankData.estimatedUBI || 0, lastClaimedDate: bankData.lastClaimedDate || null, totalClaimed: bankData.totalClaimed || 0, lastActivityBucket: days < 14 ? 'green' : days < 182.5 ? 'orange' : 'red' });
  1065. })
  1066. .get("/search", async (ctx) => {
  1067. const query = ctx.query.query || '';
  1068. if (!query) return ctx.body = await searchView({ messages: [], query, types: [] });
  1069. const userId = getViewerId();
  1070. const allTribes = await tribesModel.listAll();
  1071. const anonTribeIds = new Set(allTribes.filter(t => t.isAnonymous === true).map(t => t.id));
  1072. const applySearchPrivacy = (msgs) => msgs.filter(msg => {
  1073. const c = msg.value?.content;
  1074. if (!c) return true;
  1075. if (c.tribeId && anonTribeIds.has(c.tribeId)) return false;
  1076. if (c.type === 'event' && c.isPublic === 'private' && c.organizer !== userId && !(Array.isArray(c.attendees) && c.attendees.includes(userId))) return false;
  1077. if (c.type === 'task' && String(c.isPublic).toUpperCase() === 'PRIVATE' && c.author !== userId && !(Array.isArray(c.assignees) && c.assignees.includes(userId))) return false;
  1078. if (c.status === 'PRIVATE') return false;
  1079. if (c.type === 'shop' && c.visibility === 'CLOSED' && c.author !== userId) return false;
  1080. return true;
  1081. });
  1082. const results = await searchModel.search({ query, types: [] });
  1083. const cfgNow = getConfig();
  1084. const wishMutuals = cfgNow.wish === 'mutuals';
  1085. const mutualCache = wishMutuals ? makeCtxMutualCache() : null;
  1086. const accessSets = await getViewerTribeAccessSets(userId);
  1087. const finalResults = {};
  1088. for (const [type, msgs] of Object.entries(results)) {
  1089. const privacyFiltered = applySearchPrivacy(msgs).filter(msg => {
  1090. const c = msg.value?.content;
  1091. if (c && c.tribeId && accessSets.privateNotAccessible.has(c.tribeId)) return false;
  1092. return true;
  1093. });
  1094. let after = privacyFiltered;
  1095. if (wishMutuals) {
  1096. const out = [];
  1097. for (const m of privacyFiltered) {
  1098. const a = m.value?.author || m.value?.content?.author;
  1099. if (!a || a === userId) { out.push(m); continue; }
  1100. if (await mutualCache(a)) out.push(m);
  1101. }
  1102. after = out;
  1103. }
  1104. const mapped = after.map(msg => (!msg.value?.content) ? {} : { ...msg, content: msg.value.content, author: msg.value.content.author || 'Unknown' });
  1105. if (mapped.length > 0) finalResults[type] = mapped;
  1106. }
  1107. ctx.body = await searchView({ results: finalResults, query, types: [] });
  1108. })
  1109. .get("/images", async (ctx) => {
  1110. if (!checkMod(ctx, 'imagesMod')) { ctx.redirect('/modules'); return; }
  1111. const { filter = 'all', q = '', sort = 'recent' } = ctx.query;
  1112. const items = await imagesModel.listAll({ filter: filter === 'favorites' ? 'all' : filter, q, sort, viewerId: getViewerId() });
  1113. const fav = await mediaFavorites.getFavoriteSet('images');
  1114. let enriched = items.map(x => ({ ...x, isFavorite: fav.has(String(x.rootId || x.key)) }));
  1115. if (filter === 'favorites') enriched = enriched.filter(x => x.isFavorite);
  1116. enriched = await applyListFilters(enriched, ctx);
  1117. await Promise.all(enriched.map(async x => { x.commentCount = (await getVoteComments(x.key)).length; }));
  1118. ctx.body = await imageView(enriched, filter, null, { q, sort });
  1119. })
  1120. .get("/images/edit/:id", async (ctx) => {
  1121. if (!checkMod(ctx, 'imagesMod')) { ctx.redirect('/modules'); return; }
  1122. const img = await imagesModel.getImageById(ctx.params.id, getViewerId());
  1123. const fav = await mediaFavorites.getFavoriteSet('images');
  1124. ctx.body = await imageView([{ ...img, isFavorite: fav.has(String(img.rootId || img.key)) }], 'edit', img.key, { returnTo: ctx.query.returnTo || '' });
  1125. })
  1126. .get("/images/:imageId", async (ctx) => {
  1127. if (!checkMod(ctx, 'imagesMod')) { ctx.redirect('/modules'); return; }
  1128. const { imageId } = ctx.params; const { filter = 'all', q = '', sort = 'recent' } = ctx.query;
  1129. const img = await imagesModel.getImageById(imageId, getViewerId());
  1130. const fav = await mediaFavorites.getFavoriteSet('images');
  1131. const comments = await getVoteComments(img.key);
  1132. ctx.body = await singleImageView({ ...img, isFavorite: fav.has(String(img.rootId || img.key)), commentCount: comments.length }, filter, comments, { q, sort, returnTo: safeReturnTo(ctx, `/images?filter=${encodeURIComponent(filter)}`, ['/images']) });
  1133. })
  1134. .get("/maps", async (ctx) => {
  1135. if (!checkMod(ctx, 'mapsMod')) { ctx.redirect('/modules'); return; }
  1136. const { filter = 'all', q = '', lat, lng, zoom, tribeId, title, description, markerLabel, tags, mapType } = ctx.query;
  1137. const uid = getViewerId();
  1138. const items = await mapsModel.listAll({ filter: filter === 'favorites' ? 'all' : filter, q, viewerId: uid });
  1139. const fav = await mediaFavorites.getFavoriteSet('maps');
  1140. let enriched = items.map(x => ({ ...x, isFavorite: fav.has(String(x.rootId || x.key)) }));
  1141. if (filter === 'favorites') enriched = enriched.filter(x => x.isFavorite);
  1142. const myTribeIds = await getUserTribeIds(uid);
  1143. enriched = enriched.filter(x => !x.tribeId);
  1144. enriched = await applyListFilters(enriched, ctx);
  1145. try {
  1146. ctx.body = await mapsView(enriched, filter, null, { q, lat, lng, zoom, title, description, markerLabel, tags, mapType, ...(tribeId ? { tribeId } : {}) });
  1147. } catch (e) {
  1148. console.error("maps render:", e.message);
  1149. ctx.body = await mapsView(enriched, filter, null, { q });
  1150. }
  1151. })
  1152. .get("/maps/edit/:id", async (ctx) => {
  1153. if (!checkMod(ctx, 'mapsMod')) { ctx.redirect('/modules'); return; }
  1154. let mapItem;
  1155. try { mapItem = await mapsModel.getMapById(ctx.params.id, getViewerId()); } catch (_) { ctx.redirect('/maps?filter=all'); return; }
  1156. if (!mapItem) { ctx.redirect('/maps?filter=all'); return; }
  1157. if (mapItem.author !== getViewerId()) { ctx.redirect(`/maps/${encodeURIComponent(mapItem.key)}`); return; }
  1158. const fav = await mediaFavorites.getFavoriteSet('maps');
  1159. ctx.body = await mapsView([{ ...mapItem, isFavorite: fav.has(String(mapItem.rootId || mapItem.key)) }], 'edit', mapItem.key, { returnTo: ctx.query.returnTo || '' });
  1160. })
  1161. .get("/maps/:mapId", async (ctx) => {
  1162. if (!checkMod(ctx, 'mapsMod')) { ctx.redirect('/modules'); return; }
  1163. const { mapId } = ctx.params; const { filter = 'all', q = '', zoom = '0', mkLat = '', mkLng = '', label: mkMarkerLabel = '' } = ctx.query;
  1164. const uid = getViewerId();
  1165. let mapItem;
  1166. try {
  1167. mapItem = await mapsModel.getMapById(mapId, uid);
  1168. } catch (e) {
  1169. ctx.redirect('/maps?filter=all');
  1170. return;
  1171. }
  1172. if (!mapItem) { ctx.redirect('/maps?filter=all'); return; }
  1173. const fav = await mediaFavorites.getFavoriteSet('maps');
  1174. let tribeMembers = [];
  1175. let parentTribe = null;
  1176. if (mapItem.tribeId) {
  1177. try {
  1178. parentTribe = await tribesModel.getTribeById(mapItem.tribeId);
  1179. if (!parentTribe.members.includes(uid)) { ctx.body = tribeAccessDeniedView(parentTribe); return; }
  1180. tribeMembers = parentTribe.members;
  1181. } catch { ctx.redirect('/tribes'); return; }
  1182. }
  1183. if (String(mapItem.mapType || '').toUpperCase() === 'CLOSED' && mapItem.author !== uid && mapItem.tribeId) {
  1184. ctx.body = tribeAccessDeniedView(parentTribe); return;
  1185. }
  1186. ctx.body = await singleMapView({ ...mapItem, isFavorite: fav.has(String(mapItem.rootId || mapItem.key)) }, filter, { q, zoom, mkLat, mkLng, mkMarkerLabel, tribeMembers, returnTo: safeReturnTo(ctx, `/maps?filter=${encodeURIComponent(filter)}`, ['/maps']) });
  1187. })
  1188. .get("/audios", async (ctx) => {
  1189. if (!checkMod(ctx, 'audiosMod')) { ctx.redirect('/modules'); return; }
  1190. const { filter = 'all', q = '', sort = 'recent' } = ctx.query;
  1191. const items = await audiosModel.listAll({ filter: filter === 'favorites' ? 'all' : filter, q, sort, viewerId: getViewerId() });
  1192. const fav = await mediaFavorites.getFavoriteSet('audios');
  1193. let enriched = items.map(x => ({ ...x, isFavorite: fav.has(String(x.rootId || x.key)) }));
  1194. if (filter === 'favorites') enriched = enriched.filter(x => x.isFavorite);
  1195. enriched = await applyListFilters(enriched, ctx);
  1196. await Promise.all(enriched.map(async x => { x.commentCount = (await getVoteComments(x.key)).length; }));
  1197. ctx.body = await audioView(enriched, filter, null, { q, sort });
  1198. })
  1199. .get("/audios/edit/:id", async (ctx) => {
  1200. if (!checkMod(ctx, 'audiosMod')) { ctx.redirect('/modules'); return; }
  1201. const audio = await audiosModel.getAudioById(ctx.params.id, getViewerId());
  1202. const fav = await mediaFavorites.getFavoriteSet('audios');
  1203. ctx.body = await audioView([{ ...audio, isFavorite: fav.has(String(audio.rootId || audio.key)) }], 'edit', audio.key, { returnTo: ctx.query.returnTo || '' });
  1204. })
  1205. .get("/audios/:audioId", async (ctx) => {
  1206. if (!checkMod(ctx, 'audiosMod')) { ctx.redirect('/modules'); return; }
  1207. const { audioId } = ctx.params; const { filter = 'all', q = '', sort = 'recent' } = ctx.query;
  1208. const audio = await audiosModel.getAudioById(audioId, getViewerId());
  1209. const fav = await mediaFavorites.getFavoriteSet('audios');
  1210. const comments = await getVoteComments(audio.key);
  1211. ctx.body = await singleAudioView({ ...audio, isFavorite: fav.has(String(audio.rootId || audio.key)), commentCount: comments.length }, filter, comments, { q, sort, returnTo: safeReturnTo(ctx, `/audios?filter=${encodeURIComponent(filter)}`, ['/audios']) });
  1212. })
  1213. .get("/torrents", async (ctx) => {
  1214. if (!checkMod(ctx, 'torrentsMod')) { ctx.redirect('/modules'); return; }
  1215. const { filter = 'all', q = '', sort = 'recent', tribeId = '' } = ctx.query;
  1216. const items = await torrentsModel.listAll({ filter: filter === 'favorites' ? 'all' : filter, q, sort, viewerId: getViewerId() });
  1217. const fav = await mediaFavorites.getFavoriteSet('torrents');
  1218. let enriched = items.filter(x => !x.tribeId).map(x => ({ ...x, isFavorite: fav.has(String(x.rootId || x.key)) }));
  1219. if (filter === 'favorites') enriched = enriched.filter(x => x.isFavorite);
  1220. enriched = await applyListFilters(enriched, ctx);
  1221. ctx.body = await torrentsView(enriched, filter, null, { q, sort, ...(tribeId ? { tribeId } : {}) });
  1222. })
  1223. .get("/torrents/edit/:id", async (ctx) => {
  1224. if (!checkMod(ctx, 'torrentsMod')) { ctx.redirect('/modules'); return; }
  1225. const torrent = await torrentsModel.getTorrentById(ctx.params.id, getViewerId());
  1226. const fav = await mediaFavorites.getFavoriteSet('torrents');
  1227. ctx.body = await torrentsView([{ ...torrent, isFavorite: fav.has(String(torrent.rootId || torrent.key)) }], 'edit', torrent.key, { returnTo: ctx.query.returnTo || '' });
  1228. })
  1229. .get("/torrents/:torrentId", async (ctx) => {
  1230. if (!checkMod(ctx, 'torrentsMod')) { ctx.redirect('/modules'); return; }
  1231. const { torrentId } = ctx.params; const { filter = 'all', q = '', sort = 'recent' } = ctx.query;
  1232. const torrent = await torrentsModel.getTorrentById(torrentId, getViewerId());
  1233. const fav = await mediaFavorites.getFavoriteSet('torrents');
  1234. const comments = await getVoteComments(torrent.key);
  1235. ctx.body = await singleTorrentView({ ...torrent, isFavorite: fav.has(String(torrent.rootId || torrent.key)), commentCount: comments.length }, filter, comments, { q, sort, returnTo: safeReturnTo(ctx, `/torrents?filter=${encodeURIComponent(filter)}`, ['/torrents']) });
  1236. })
  1237. .get("/videos", async (ctx) => {
  1238. if (!checkMod(ctx, 'videosMod')) { ctx.redirect('/modules'); return; }
  1239. const { filter = 'all', q = '', sort = 'recent' } = ctx.query;
  1240. const items = await videosModel.listAll({ filter: filter === 'favorites' ? 'all' : filter, q, sort, viewerId: getViewerId() });
  1241. const fav = await mediaFavorites.getFavoriteSet('videos');
  1242. let enriched = items.map(x => ({ ...x, isFavorite: fav.has(String(x.rootId || x.key)) }));
  1243. if (filter === 'favorites') enriched = enriched.filter(x => x.isFavorite);
  1244. enriched = await applyListFilters(enriched, ctx);
  1245. await Promise.all(enriched.map(async x => { x.commentCount = (await getVoteComments(x.key)).length; }));
  1246. ctx.body = await videoView(enriched, filter, null, { q, sort });
  1247. })
  1248. .get("/videos/edit/:id", async (ctx) => {
  1249. if (!checkMod(ctx, 'videosMod')) { ctx.redirect('/modules'); return; }
  1250. const video = await videosModel.getVideoById(ctx.params.id, getViewerId());
  1251. const fav = await mediaFavorites.getFavoriteSet('videos');
  1252. ctx.body = await videoView([{ ...video, isFavorite: fav.has(String(video.rootId || video.key)) }], 'edit', video.key, { returnTo: ctx.query.returnTo || '' });
  1253. })
  1254. .get("/videos/:videoId", async (ctx) => {
  1255. if (!checkMod(ctx, 'videosMod')) { ctx.redirect('/modules'); return; }
  1256. const { videoId } = ctx.params; const { filter = 'all', q = '', sort = 'recent' } = ctx.query;
  1257. const video = await videosModel.getVideoById(videoId, getViewerId());
  1258. const fav = await mediaFavorites.getFavoriteSet('videos');
  1259. const comments = await getVoteComments(video.key);
  1260. ctx.body = await singleVideoView({ ...video, isFavorite: fav.has(String(video.rootId || video.key)), commentCount: comments.length }, filter, comments, { q, sort, returnTo: safeReturnTo(ctx, `/videos?filter=${encodeURIComponent(filter)}`, ['/videos']) });
  1261. })
  1262. .get("/documents", async (ctx) => {
  1263. const { filter = 'all', q = '', sort = 'recent' } = ctx.query;
  1264. const items = await documentsModel.listAll({ filter: filter === 'favorites' ? 'all' : filter, q, sort });
  1265. const fav = await mediaFavorites.getFavoriteSet('documents');
  1266. let enriched = items.map(x => ({ ...x, isFavorite: fav.has(String(x.rootId || x.key)) }));
  1267. if (filter === 'favorites') enriched = enriched.filter(x => x.isFavorite);
  1268. enriched = await applyListFilters(enriched, ctx);
  1269. await Promise.all(enriched.map(async x => { x.commentCount = (await getVoteComments(x.rootId || x.key)).length; }));
  1270. ctx.body = await documentView(enriched, filter, null, { q, sort });
  1271. })
  1272. .get("/documents/edit/:id", async (ctx) => {
  1273. const doc = await documentsModel.getDocumentById(ctx.params.id);
  1274. const fav = await mediaFavorites.getFavoriteSet('documents');
  1275. ctx.body = await documentView([{ ...doc, isFavorite: fav.has(String(doc.rootId || doc.key)) }], 'edit', doc.key, { returnTo: ctx.query.returnTo || '' });
  1276. })
  1277. .get("/documents/:documentId", async (ctx) => {
  1278. const { filter = "all", q = "", sort = "recent" } = ctx.query;
  1279. const document = await documentsModel.getDocumentById(ctx.params.documentId);
  1280. const fav = await mediaFavorites.getFavoriteSet('documents');
  1281. Object.assign(document, { isFavorite: fav.has(String(document.rootId || document.key)) });
  1282. const comments = await getVoteComments(document.rootId || document.key);
  1283. ctx.body = await singleDocumentView(withCount(document, comments), filter, comments, {
  1284. q, sort,
  1285. returnTo: safeReturnTo(ctx, `/documents/${encodeURIComponent(document.key)}?filter=${encodeURIComponent(filter)}${q ? `&q=${encodeURIComponent(q)}` : ""}${sort ? `&sort=${encodeURIComponent(sort)}` : ""}`, ["/documents"])
  1286. });
  1287. })
  1288. .get('/cv', async ctx => {
  1289. const cv = await cvModel.getCVByUserId()
  1290. ctx.body = await cvView(cv)
  1291. })
  1292. .get('/cv/create', async ctx => {
  1293. ctx.body = await createCVView()
  1294. })
  1295. .get('/cv/edit/:id', async ctx => {
  1296. const cv = await cvModel.getCVByUserId()
  1297. ctx.body = await createCVView(cv, true)
  1298. })
  1299. .get('/pm', async ctx => {
  1300. const { recipients = '', subject = '', quote = '', preview = '' } = ctx.query;
  1301. const quoted = quote ? quote.split('\n').map(l => '> ' + l).join('\n') + '\n\n' : '';
  1302. const showPreview = preview === '1';
  1303. ctx.body = await pmView(recipients, subject, quoted, showPreview);
  1304. })
  1305. .get('/inbox', async ctx => {
  1306. if (!checkMod(ctx, 'inboxMod')) { ctx.redirect('/modules'); return; }
  1307. let messages = sanitizeMessages(await pmModel.listAllPrivate());
  1308. const cfgNow = getConfig();
  1309. if (cfgNow.pmVisibility === 'mutuals') {
  1310. const viewer = getViewerId();
  1311. const mutualCache = new Map();
  1312. const isMutual = async (id) => {
  1313. if (id === viewer) return true;
  1314. if (mutualCache.has(id)) return mutualCache.get(id);
  1315. let rel;
  1316. try { rel = await friend.getRelationship(id); } catch (e) { rel = null; }
  1317. const m = !!(rel && rel.following && rel.followsMe);
  1318. mutualCache.set(id, m);
  1319. return m;
  1320. };
  1321. const filtered = [];
  1322. for (const msg of messages) {
  1323. const author = msg?.value?.author || msg?.author;
  1324. if (author === viewer) { filtered.push(msg); continue; }
  1325. if (await isMutual(author)) filtered.push(msg);
  1326. }
  1327. messages = filtered;
  1328. }
  1329. await refreshInboxCount(messages);
  1330. ctx.body = await privateView({ messages }, ctx.query.filter || undefined);
  1331. })
  1332. .get('/tags', async ctx => {
  1333. const filter = qf(ctx), tags = await tagsModel.listTags(filter);
  1334. ctx.body = await tagsView(tags, filter);
  1335. })
  1336. .get('/reports', async ctx => {
  1337. const filter = qf(ctx);
  1338. let reports = await enrichWithComments(await reportsModel.listAll());
  1339. reports = await applyListFilters(reports, ctx);
  1340. ctx.body = await reportView(reports, filter, null, ctx.query.category || '');
  1341. })
  1342. .get('/reports/edit/:id', async ctx => {
  1343. const report = await reportsModel.getReportById(ctx.params.id);
  1344. ctx.body = await reportView([report], 'edit', ctx.params.id);
  1345. })
  1346. .get('/reports/:reportId', async ctx => {
  1347. const { reportId } = ctx.params, filter = qf(ctx), report = await reportsModel.getReportById(reportId);
  1348. const comments = await getVoteComments(reportId);
  1349. ctx.body = await singleReportView(withCount(report, comments), filter, comments);
  1350. })
  1351. .get('/trending', async (ctx) => {
  1352. const filter = qf(ctx, 'RECENT');
  1353. let { filtered = [] } = await trendingModel.listTrending(filter);
  1354. filtered = await applyListFilters(filtered, ctx);
  1355. ctx.body = await trendingView(filtered, filter, trendingModel.categories);
  1356. })
  1357. .get('/agenda', async (ctx) => {
  1358. const filter = qf(ctx);
  1359. let data = await agendaModel.listAgenda(filter);
  1360. if (Array.isArray(data)) data = await applyListFilters(data, ctx);
  1361. ctx.body = await agendaView(data, filter);
  1362. })
  1363. .get("/hashtag/:hashtag", async (ctx) => {
  1364. const { hashtag } = ctx.params;
  1365. const messages = sanitizeMessages(await post.fromHashtag(hashtag));
  1366. ctx.body = await hashtagView({ hashtag, messages });
  1367. })
  1368. .get('/inhabitants', async (ctx) => {
  1369. const filter = qf(ctx);
  1370. const query = { search: ctx.query.search || '' };
  1371. const userId = getViewerId();
  1372. if (filter === 'pending') {
  1373. try { await scanPendingFollows(userId); } catch (e) {}
  1374. const pending = viewerFilters.listPending();
  1375. const enriched = await Promise.all(pending.map(async (p) => {
  1376. let name = p.followerId;
  1377. try { name = await about.name(p.followerId); } catch (_) {}
  1378. return { ...p, name };
  1379. }));
  1380. ctx.body = renderPendingFollows(enriched);
  1381. return;
  1382. }
  1383. if (['CVs', 'MATCHSKILLS'].includes(filter)) {
  1384. Object.assign(query, {
  1385. location: ctx.query.location || '',
  1386. language: ctx.query.language || '',
  1387. skills: ctx.query.skills || ''
  1388. });
  1389. }
  1390. const inhabitants = await inhabitantsModel.listInhabitants({ filter, ...query });
  1391. const [addresses, karmaList] = await Promise.all([
  1392. bankingModel.listAddressesMerged(),
  1393. Promise.all(
  1394. inhabitants.map(async (u) => {
  1395. try {
  1396. const bank = await bankingModel.getBankingData(u.id);
  1397. return { id: u.id, karmaScore: bank?.karmaScore || 0, estimatedUBI: bank?.estimatedUBI || 0, lastClaimedDate: bank?.lastClaimedDate || null, totalClaimed: bank?.totalClaimed || 0 };
  1398. } catch {
  1399. return { id: u.id, karmaScore: 0, estimatedUBI: 0, lastClaimedDate: null, totalClaimed: 0 };
  1400. }
  1401. })
  1402. )
  1403. ]);
  1404. const activityList = await Promise.all(
  1405. inhabitants.map(async (u) => {
  1406. try {
  1407. const ts = await inhabitantsModel.getLastActivityTimestampByUserId(u.id);
  1408. const { bucket } = inhabitantsModel.bucketLastActivity(ts || null);
  1409. return { id: u.id, lastActivityBucket: bucket };
  1410. } catch {
  1411. return { id: u.id, lastActivityBucket: 'red' };
  1412. }
  1413. })
  1414. );
  1415. const addrMap = new Map(addresses.map(x => [x.id, x.address]));
  1416. const karmaMap = new Map(karmaList.map(x => [x.id, { karmaScore: x.karmaScore, estimatedUBI: x.estimatedUBI, lastClaimedDate: x.lastClaimedDate, totalClaimed: x.totalClaimed }]));
  1417. const activityMap = new Map(activityList.map(x => [x.id, x.lastActivityBucket]));
  1418. let enriched = inhabitants.map(u => {
  1419. const kd = karmaMap.get(u.id) || {};
  1420. return {
  1421. ...u,
  1422. ecoAddress: addrMap.get(u.id) || null,
  1423. karmaScore: kd.karmaScore ?? (typeof u.karmaScore === 'number' ? u.karmaScore : 0),
  1424. estimatedUBI: kd.estimatedUBI || 0,
  1425. lastClaimedDate: kd.lastClaimedDate || null,
  1426. totalClaimed: kd.totalClaimed || 0,
  1427. lastActivityBucket: activityMap.get(u.id)
  1428. };
  1429. });
  1430. if (filter === 'TOP KARMA') {
  1431. enriched = enriched.sort((a, b) => (b.karmaScore || 0) - (a.karmaScore || 0));
  1432. }
  1433. if (filter === 'TOP ACTIVITY') {
  1434. const order = { green: 0, orange: 1, red: 2 };
  1435. enriched = enriched.sort(
  1436. (a, b) => (order[a.lastActivityBucket] ?? 3) - (order[b.lastActivityBucket] ?? 3)
  1437. );
  1438. }
  1439. ctx.body = await inhabitantsView(enriched, filter, query, userId);
  1440. })
  1441. .get('/inhabitant/:id', async (ctx) => {
  1442. const id = ctx.params.id;
  1443. const [about, cv, feed, photo, bank, lastTs] = await Promise.all([
  1444. inhabitantsModel.getLatestAboutById(id),
  1445. inhabitantsModel.getCVByUserId(id),
  1446. inhabitantsModel.getFeedByUserId(id),
  1447. inhabitantsModel.getPhotoUrlByUserId(id, 256),
  1448. bankingModel.getBankingData(id).catch(() => ({ karmaScore: 0 })),
  1449. inhabitantsModel.getLastActivityTimestampByUserId(id).catch(() => null)
  1450. ]);
  1451. const bucketInfo = inhabitantsModel.bucketLastActivity(lastTs || null);
  1452. const currentUserId = getViewerId();
  1453. const karmaScore = bank && typeof bank.karmaScore === 'number' ? bank.karmaScore : 0;
  1454. const estimatedUBI = bank?.estimatedUBI || 0;
  1455. const lastClaimedDate = bank?.lastClaimedDate || null;
  1456. const totalClaimed = bank?.totalClaimed || 0;
  1457. ctx.body = await inhabitantsProfileView({ about, cv, feed, photo, karmaScore, estimatedUBI, lastClaimedDate, totalClaimed, lastActivityBucket: bucketInfo.bucket, viewedId: id }, currentUserId);
  1458. })
  1459. .get('/parliament', async (ctx) => {
  1460. if (!checkMod(ctx, 'parliamentMod')) return ctx.redirect('/modules');
  1461. const filter = (ctx.query.filter || 'government').toLowerCase();
  1462. await ensureTerm();
  1463. await runSweepOnce();
  1464. const [governmentCardRaw, candidatures, proposals, futureLaws, canPropose, laws, historical, leaders, revocations, futureRevocations, revocationsEnactedCount, inhabitantsAll] = await Promise.all([
  1465. parliamentModel.getGovernmentCard(),
  1466. parliamentModel.listCandidatures('OPEN'),
  1467. parliamentModel.listProposalsCurrent(),
  1468. parliamentModel.listFutureLawsCurrent(),
  1469. parliamentModel.canPropose(),
  1470. parliamentModel.listLaws(),
  1471. parliamentModel.listHistorical(),
  1472. parliamentModel.listLeaders(),
  1473. parliamentModel.listRevocationsCurrent(),
  1474. parliamentModel.listFutureRevocationsCurrent(),
  1475. parliamentModel.countRevocationsEnacted(),
  1476. inhabitantsModel.listInhabitants({ filter: 'all', includeInactive: true })
  1477. ]);
  1478. const inhabitantsTotal = Array.isArray(inhabitantsAll) ? inhabitantsAll.length : 0;
  1479. const governmentCard = governmentCardRaw ? { ...governmentCardRaw, inhabitantsTotal } : null;
  1480. const leader = pickLeader(candidatures || []);
  1481. const getActorMeta = async (type, id) => (type === 'tribe' || type === 'inhabitant') ? parliamentModel.getActorMeta({ targetType: type, targetId: id }) : null;
  1482. const leaderMeta = leader ? await getActorMeta(leader.targetType || leader.powerType || 'inhabitant', leader.targetId || leader.powerId) : null;
  1483. const powerMeta = governmentCard ? await getActorMeta(governmentCard.powerType, governmentCard.powerId) : null;
  1484. const buildMetas = async (items, limit) => {
  1485. const m = {};
  1486. for (const g of (items || []).slice(0, limit)) {
  1487. if (g.powerType === 'tribe' || g.powerType === 'inhabitant') {
  1488. const k = `${g.powerType}:${g.powerId}`;
  1489. if (!m[k]) m[k] = await getActorMeta(g.powerType, g.powerId);
  1490. }
  1491. }
  1492. return m;
  1493. };
  1494. const [historicalMetas, leadersMetas] = await Promise.all([buildMetas(historical, 12), buildMetas(leaders, 20)]);
  1495. ctx.body = await parliamentView({
  1496. filter,
  1497. inhabitantsTotal,
  1498. governmentCard,
  1499. candidatures,
  1500. proposals,
  1501. futureLaws,
  1502. canPropose,
  1503. laws,
  1504. historical,
  1505. leaders,
  1506. leaderMeta,
  1507. powerMeta,
  1508. historicalMetas,
  1509. leadersMetas,
  1510. revocations,
  1511. futureRevocations,
  1512. revocationsEnactedCount
  1513. });
  1514. })
  1515. .get('/courts', async (ctx) => {
  1516. if (!checkMod(ctx, 'courtsMod')) return ctx.redirect('/modules');
  1517. const filter = String(ctx.query.filter || 'cases').toLowerCase(), search = String(ctx.query.search || '').trim();
  1518. const currentUserId = await courtsModel.getCurrentUserId();
  1519. const state = { filter, search, cases: [], myCases: [], trials: [], history: [], nominations: [], userId: currentUserId };
  1520. const searchFilter = (items) => !search ? items : items.filter(c => [c.title, c.description].some(s => String(s || '').toLowerCase().includes(search.toLowerCase())));
  1521. if (filter === 'cases') state.cases = searchFilter((await courtsModel.listCases('open')).map(c => ({ ...c, respondent: c.respondentId || c.respondent })));
  1522. if (filter === 'mycases' || filter === 'actions') {
  1523. let myCases = searchFilter(await courtsModel.listCasesForUser(currentUserId));
  1524. if (filter === 'actions') myCases = myCases.filter(c => {
  1525. const s = String(c.status || '').toUpperCase(), m = String(c.method || '').toUpperCase(), id = String(currentUserId || '');
  1526. const roles = { a: !!c.isAccuser, r: !!c.isRespondent, m: !!c.isMediator, j: !!c.isJudge, d: !!c.isDictator };
  1527. const open = s === 'OPEN' || s === 'IN_PROGRESS';
  1528. return (roles.r && open) || (m === 'JUDGE' && !c.judgeId && (roles.a || roles.r) && open) || ((roles.j || roles.d || roles.m) && s === 'OPEN') || ((roles.a || roles.r || roles.m) && m === 'MEDIATION' && open) || ((roles.a || roles.r || roles.m || roles.j || roles.d) && open);
  1529. });
  1530. state.myCases = myCases;
  1531. }
  1532. if (filter === 'judges') state.nominations = (await courtsModel.listNominations()) || [];
  1533. if (filter === 'history') {
  1534. const id = String(currentUserId || '');
  1535. state.history = searchFilter((await courtsModel.listCases('history')).map(c => {
  1536. const ma = Array.isArray(c.mediatorsAccuser) ? c.mediatorsAccuser : [], mr = Array.isArray(c.mediatorsRespondent) ? c.mediatorsRespondent : [];
  1537. return { ...c, respondent: c.respondentId || c.respondent, mine: [c.accuser, c.respondentId, c.judgeId].map(String).includes(id) || ma.includes(id) || mr.includes(id), publicDetails: c.publicPrefAccuser && c.publicPrefRespondent, decidedAt: c.verdictAt || c.closedAt || c.decidedAt };
  1538. }));
  1539. }
  1540. ctx.body = await courtsView(state);
  1541. })
  1542. .get('/courts/cases/:id', async (ctx) => {
  1543. if (!checkMod(ctx, 'courtsMod')) return ctx.redirect('/modules');
  1544. ctx.body = await courtsCaseView({ caseData: await courtsModel.getCaseDetails({ caseId: ctx.params.id }).catch(() => null) });
  1545. })
  1546. .get('/tribes', async ctx => {
  1547. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  1548. const filter = qf(ctx), search = ctx.query.search || '', tribes = await tribesModel.listAll();
  1549. const filteredTribes = search ? tribes.filter(t => t.title.toLowerCase().includes(search.toLowerCase())) : tribes;
  1550. ctx.body = await tribesView(filteredTribes, filter, null, ctx.query, tribes);
  1551. })
  1552. .get('/tribes/create', async ctx => {
  1553. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  1554. ctx.body = await tribesView([], 'create', null)
  1555. })
  1556. .get('/tribes/edit/:id', async ctx => {
  1557. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  1558. const tribe = await tribesModel.getTribeById(ctx.params.id)
  1559. ctx.body = await tribesView([tribe], 'edit', ctx.params.id)
  1560. })
  1561. .get('/tribe/:tribeId', async ctx => {
  1562. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  1563. await tribesModel.processIncomingKeys().catch(() => {});
  1564. await tribesModel.ensureTribeKeyDistribution(ctx.params.tribeId).catch(() => {});
  1565. await tribesModel.ensureFollowTribeMembers(ctx.params.tribeId).catch(() => {});
  1566. const listByTribeAllChain = async (tribeId, contentType) => {
  1567. const chainIds = await tribesModel.getChainIds(tribeId).catch(() => [tribeId]);
  1568. const results = await Promise.all(chainIds.map(id => tribesContentModel.listByTribe(id, contentType).catch(() => [])));
  1569. const seen = new Set();
  1570. return results.flat().filter(item => { const k = item.id || item.key; if (seen.has(k)) return false; seen.add(k); return true; });
  1571. };
  1572. const tribe = await tribesModel.getTribeById(ctx.params.tribeId);
  1573. const uid = getViewerId();
  1574. const query = { feedFilter: 'TOP', ...ctx.query };
  1575. if (!tribe.members.includes(uid)) {
  1576. ctx.redirect('/tribes');
  1577. return;
  1578. }
  1579. const section = ctx.query.section || 'activity';
  1580. const contentTypeMap = { events: 'event', tasks: 'task', reports: 'report', votations: 'votation', market: 'market', jobs: 'job', projects: 'project', media: 'media' };
  1581. const mediaSections = { 'media-audio': 'media', 'media-video': 'media', 'media-images': 'media', 'media-documents': 'media', 'media-bookmarks': 'media', 'images': 'media', 'audios': 'media', 'videos': 'media', 'documents': 'media', 'bookmarks': 'media' };
  1582. let sectionData = null;
  1583. if (section === 'inhabitants') {
  1584. const allInhabitants = await inhabitantsModel.listInhabitants({ filter: 'all', includeInactive: true });
  1585. sectionData = allInhabitants.filter(u => tribe.members.includes(u.id));
  1586. } else if (section === 'feed') {
  1587. sectionData = await listByTribeAllChain(tribe.id, 'feed').catch(() => []);
  1588. } else if (section === 'forum') {
  1589. const forums = await listByTribeAllChain(tribe.id, 'forum');
  1590. const replies = await listByTribeAllChain(tribe.id, 'forum-reply');
  1591. sectionData = [...forums, ...replies];
  1592. } else if (section === 'subtribes') {
  1593. sectionData = await tribesModel.listSubTribes(tribe.id);
  1594. } else if (mediaSections[section]) {
  1595. sectionData = await listByTribeAllChain(tribe.id, 'media');
  1596. } else if (contentTypeMap[section]) {
  1597. sectionData = await listByTribeAllChain(tribe.id, contentTypeMap[section]);
  1598. } else if (section === 'activity') {
  1599. const allContent = await listByTribeAllChain(tribe.id, null);
  1600. const subTribes = await tribesModel.listSubTribes(tribe.id);
  1601. const subContent = [];
  1602. for (const st of subTribes) {
  1603. const stItems = await listByTribeAllChain(st.id, null).catch(() => []);
  1604. subContent.push(...stItems.map(item => ({ ...item, tribeName: st.title })));
  1605. }
  1606. const [allPadsRaw, allChatsRaw, allCalsRaw, allMapsRaw, allTorrentsRaw, tribeChain] = await Promise.all([
  1607. padsModel.listAll({ filter: 'all', viewerId: uid }).catch(() => []),
  1608. chatsModel.listAll({ filter: 'all', viewerId: uid }).catch(() => []),
  1609. calendarsModel.listAll({ filter: 'all', viewerId: uid }).catch(() => []),
  1610. mapsModel.listAll({ filter: 'all', q: '', viewerId: uid }).catch(() => []),
  1611. torrentsModel.listAll({ filter: 'all', viewerId: uid }).catch(() => []),
  1612. tribesModel.getChainIds(tribe.id).catch(() => [tribe.id])
  1613. ]);
  1614. const tribeChainSet = new Set(tribeChain);
  1615. const toStandalone = (type, url) => (item) => ({ contentType: type, id: item.rootId || item.key, title: item.title || '', author: item.author, createdAt: item.createdAt, directUrl: url(item) });
  1616. const standaloneItems = [
  1617. ...allPadsRaw.filter(p => tribeChainSet.has(p.tribeId)).map(toStandalone('pad', p => `/pads/${encodeURIComponent(p.rootId)}`)),
  1618. ...allChatsRaw.filter(c => tribeChainSet.has(c.tribeId)).map(toStandalone('chat', c => `/chats/${encodeURIComponent(c.rootId || c.key)}`)),
  1619. ...allCalsRaw.filter(c => tribeChainSet.has(c.tribeId)).map(toStandalone('calendar', c => `/calendars/${encodeURIComponent(c.rootId)}`)),
  1620. ...allMapsRaw.filter(m => tribeChainSet.has(m.tribeId)).map(toStandalone('map', m => `/maps/${encodeURIComponent(m.key || m.id)}`)),
  1621. ...allTorrentsRaw.filter(t => tribeChainSet.has(t.tribeId)).map(toStandalone('torrent', t => `/torrents/${encodeURIComponent(t.rootId || t.key)}`))
  1622. ];
  1623. const combined = [...allContent, ...subContent, ...standaloneItems];
  1624. const allInhabitants = await inhabitantsModel.listInhabitants({ filter: 'all', includeInactive: true });
  1625. const allMembers = [...new Set([...tribe.members, ...subTribes.flatMap(st => st.members || [])])];
  1626. const memberMap = new Map(allInhabitants.filter(u => allMembers.includes(u.id)).map(u => [u.id, u]));
  1627. const activities = combined.map(item => ({ ...item, authorName: memberMap.get(item.author)?.name || item.author, timestamp: Date.parse(item.createdAt) || item._ts || 0 })).sort((a, b) => b.timestamp - a.timestamp);
  1628. sectionData = { activities, memberMap };
  1629. } else if (section === 'trending') {
  1630. const allContent = await listByTribeAllChain(tribe.id, null);
  1631. const period = ctx.query.period || 'all';
  1632. let items = allContent.filter(i => i.contentType !== 'forum-reply' && i.contentType !== 'pixelia');
  1633. if (period === 'day') items = items.filter(i => (Date.parse(i.createdAt) || i._ts || 0) >= Date.now() - 86400000);
  1634. else if (period === 'week') items = items.filter(i => (Date.parse(i.createdAt) || i._ts || 0) >= Date.now() - 7 * 86400000);
  1635. items.sort((a, b) => {
  1636. const score = i => (i.refeeds || 0) + (Array.isArray(i.attendees) ? i.attendees.length : 0) + Object.values(i.votes || {}).reduce((s, arr) => s + (Array.isArray(arr) ? arr.length : 0), 0) + (Array.isArray(i.assignees) ? i.assignees.length : 0) + (Array.isArray(i.opinions_inhabitants) ? i.opinions_inhabitants.length : 0);
  1637. return score(b) - score(a);
  1638. });
  1639. sectionData = { items, period };
  1640. } else if (section === 'tags') {
  1641. const allContent = await listByTribeAllChain(tribe.id, null);
  1642. const [allPadsT, allChatsT, allCalsT, allMapsT, allTorrentsT, subTribesT, tribeChainT] = await Promise.all([
  1643. padsModel.listAll({ filter: 'all', viewerId: uid }).catch(() => []),
  1644. chatsModel.listAll({ filter: 'all', viewerId: uid }).catch(() => []),
  1645. calendarsModel.listAll({ filter: 'all', viewerId: uid }).catch(() => []),
  1646. mapsModel.listAll({ filter: 'all', q: '', viewerId: uid }).catch(() => []),
  1647. torrentsModel.listAll({ filter: 'all', viewerId: uid }).catch(() => []),
  1648. tribesModel.listSubTribes(tribe.id).catch(() => []),
  1649. tribesModel.getChainIds(tribe.id).catch(() => [tribe.id])
  1650. ]);
  1651. const tribeChainSetT = new Set(tribeChainT);
  1652. const standaloneTagged = [
  1653. ...allPadsT.filter(p => tribeChainSetT.has(p.tribeId)).map(p => ({ ...p, contentType: 'pad', id: p.rootId || p.key })),
  1654. ...allChatsT.filter(c => tribeChainSetT.has(c.tribeId)).map(c => ({ ...c, contentType: 'chat', id: c.rootId || c.key })),
  1655. ...allCalsT.filter(c => tribeChainSetT.has(c.tribeId)).map(c => ({ ...c, contentType: 'calendar', id: c.rootId || c.key })),
  1656. ...allMapsT.filter(m => tribeChainSetT.has(m.tribeId)).map(m => ({ ...m, contentType: 'map', id: m.rootId || m.key })),
  1657. ...allTorrentsT.filter(t => tribeChainSetT.has(t.tribeId)).map(t => ({ ...t, contentType: 'torrent', id: t.rootId || t.key })),
  1658. ...subTribesT.map(st => ({ ...st, contentType: 'tribe', tags: Array.isArray(st.tags) ? st.tags : [], title: st.title, description: st.description, author: st.author, createdAt: st.createdAt }))
  1659. ];
  1660. const allTaggable = [...allContent, ...standaloneTagged];
  1661. const tagMap = new Map();
  1662. for (const item of allTaggable) {
  1663. for (const tag of (item.tags || []).filter(Boolean)) {
  1664. const lower = String(tag).toLowerCase().trim();
  1665. if (!lower) continue;
  1666. if (!tagMap.has(lower)) tagMap.set(lower, { tag: lower, count: 0, items: [] });
  1667. const entry = tagMap.get(lower);
  1668. entry.count++;
  1669. entry.items.push(item);
  1670. }
  1671. }
  1672. const selectedTag = (ctx.query.tag || '').toLowerCase().trim();
  1673. sectionData = { tags: [...tagMap.values()].sort((a, b) => b.count - a.count), selectedTag, filteredItems: selectedTag && tagMap.has(selectedTag) ? tagMap.get(selectedTag).items : [] };
  1674. } else if (section === 'maps') {
  1675. const [allMaps, tribeChain] = await Promise.all([
  1676. mapsModel.listAll({ filter: 'all', q: '', viewerId: uid }).catch(() => []),
  1677. tribesModel.getChainIds(tribe.id).catch(() => [tribe.id])
  1678. ]);
  1679. const tribeChainSet = new Set(tribeChain);
  1680. sectionData = allMaps.filter(m => tribeChainSet.has(m.tribeId));
  1681. } else if (section === 'pads') {
  1682. const [allPads, tribeChain] = await Promise.all([
  1683. padsModel.listAll({ filter: 'all', viewerId: uid }).catch(() => []),
  1684. tribesModel.getChainIds(tribe.id).catch(() => [tribe.id])
  1685. ]);
  1686. const tribeChainSet = new Set(tribeChain);
  1687. sectionData = allPads.filter(p => tribeChainSet.has(p.tribeId));
  1688. } else if (section === 'chats') {
  1689. const [allChats, tribeChain] = await Promise.all([
  1690. chatsModel.listAll({ filter: 'all', viewerId: uid }).catch(() => []),
  1691. tribesModel.getChainIds(tribe.id).catch(() => [tribe.id])
  1692. ]);
  1693. const tribeChainSet = new Set(tribeChain);
  1694. sectionData = allChats.filter(c => tribeChainSet.has(c.tribeId));
  1695. } else if (section === 'calendars') {
  1696. const [allCals, tribeChain] = await Promise.all([
  1697. calendarsModel.listAll({ filter: 'all', viewerId: uid }).catch(() => []),
  1698. tribesModel.getChainIds(tribe.id).catch(() => [tribe.id])
  1699. ]);
  1700. const tribeChainSet = new Set(tribeChain);
  1701. sectionData = allCals.filter(c => tribeChainSet.has(c.tribeId));
  1702. } else if (section === 'torrents') {
  1703. const [allTorrents, tribeChain] = await Promise.all([
  1704. torrentsModel.listAll({ filter: 'all', viewerId: uid }).catch(() => []),
  1705. tribesModel.getChainIds(tribe.id).catch(() => [tribe.id])
  1706. ]);
  1707. const tribeChainSet = new Set(tribeChain);
  1708. const standaloneTorrents = allTorrents.filter(t => tribeChainSet.has(t.tribeId));
  1709. const mediaTorrents = (await listByTribeAllChain(tribe.id, 'media').catch(() => []))
  1710. .filter(m => m.mediaType === 'torrent')
  1711. .map(m => ({
  1712. key: m.id,
  1713. rootId: m.id,
  1714. title: m.title || '',
  1715. description: m.description || '',
  1716. url: m.image || '',
  1717. tags: Array.isArray(m.tags) ? m.tags : [],
  1718. author: m.author,
  1719. createdAt: m.createdAt,
  1720. updatedAt: m.updatedAt,
  1721. tribeId: m.tribeId,
  1722. _isMedia: true
  1723. }));
  1724. sectionData = [...standaloneTorrents, ...mediaTorrents].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
  1725. } else if (section === 'search') {
  1726. const sq = (ctx.query.q || '').trim().toLowerCase();
  1727. let results = [];
  1728. if (sq.length >= 2) {
  1729. const allContent = await listByTribeAllChain(tribe.id, null);
  1730. results = allContent.filter(item => (item.title || '').toLowerCase().includes(sq) || (item.description || '').toLowerCase().includes(sq) || (item.tags || []).join(' ').toLowerCase().includes(sq));
  1731. }
  1732. sectionData = { query: ctx.query.q || '', results };
  1733. } else if (section === 'opinions') {
  1734. const allContent = await listByTribeAllChain(tribe.id, null);
  1735. const opinionated = allContent.filter(i => i.opinions && Object.keys(i.opinions).length > 0).sort((a, b) => {
  1736. const sum = o => Object.values(o.opinions || {}).reduce((s, n) => s + n, 0);
  1737. return sum(b) - sum(a);
  1738. });
  1739. sectionData = { items: allContent.filter(i => i.contentType !== 'forum-reply' && i.contentType !== 'pixelia'), opinionated };
  1740. } else if (section === 'pixelia') {
  1741. const pixels = await listByTribeAllChain(tribe.id, 'pixelia');
  1742. const coordMap = new Map();
  1743. for (const px of pixels) { const existing = coordMap.get(px.title); if (!existing || (Date.parse(px.createdAt) || 0) > (Date.parse(existing.createdAt) || 0)) coordMap.set(px.title, px); }
  1744. sectionData = { pixels: [...coordMap.values()] };
  1745. } else if (section === 'overview') {
  1746. const events = await listByTribeAllChain(tribe.id, 'event').catch(() => []);
  1747. const tasks = await listByTribeAllChain(tribe.id, 'task').catch(() => []);
  1748. const feed = await listByTribeAllChain(tribe.id, 'feed').catch(() => []);
  1749. sectionData = { events, tasks, feed };
  1750. } else if (section === 'governance') {
  1751. if (tribe.parentTribeId) { ctx.redirect(`/tribe/${encodeURIComponent(tribe.id)}?section=activity`); return; }
  1752. const gf = String(ctx.query.filter || 'government');
  1753. const isCreator = tribe.author === uid;
  1754. const isMember = Array.isArray(tribe.members) && tribe.members.includes(uid);
  1755. if (isCreator) { try { await parliamentModel.tribe.ensureTerm(tribe.id); } catch (_) {} }
  1756. const [term, candidatures, rules, globalTermBase] = await Promise.all([
  1757. parliamentModel.tribe.getCurrentTerm(tribe.id).catch(() => null),
  1758. parliamentModel.tribe.listCandidatures(tribe.id).catch(() => []),
  1759. parliamentModel.tribe.listRules(tribe.id).catch(() => []),
  1760. parliamentModel.getCurrentTerm().catch(() => null)
  1761. ]);
  1762. const globalStart = globalTermBase?.startAt || null;
  1763. const alreadyPublishedThisGlobalCycle = await parliamentModel.tribe.hasCandidatureInGlobalCycle(tribe.id, globalStart).catch(() => false);
  1764. const leaders = Array.isArray(term?.leaders) ? term.leaders : [];
  1765. const hasElectedCandidate = Array.isArray(candidatures) && candidatures.some(c => (c.status || 'OPEN') === 'OPEN' && Number(c.votes || 0) > 0);
  1766. sectionData = { filter: gf, term, candidatures, rules, leaders, isCreator, isMember, canPublishToGlobal: isMember || isCreator, alreadyPublishedThisGlobalCycle, hasElectedCandidate };
  1767. }
  1768. const subTribes = await tribesModel.listSubTribes(tribe.id);
  1769. tribe.subTribes = subTribes;
  1770. if (tribe.parentTribeId) {
  1771. try { tribe.parentTribe = await tribesModel.getTribeById(tribe.parentTribeId); } catch (_) {}
  1772. }
  1773. const resolveItemMentions = async (items) => {
  1774. if (!Array.isArray(items)) return items;
  1775. for (const item of items) {
  1776. if (item.description) item.description = await resolveMentionText(item.description);
  1777. }
  1778. return items;
  1779. };
  1780. if (Array.isArray(sectionData)) {
  1781. await resolveItemMentions(sectionData);
  1782. } else if (sectionData && typeof sectionData === 'object') {
  1783. if (sectionData.activities) await resolveItemMentions(sectionData.activities);
  1784. if (sectionData.items) await resolveItemMentions(sectionData.items);
  1785. if (sectionData.results) await resolveItemMentions(sectionData.results);
  1786. if (sectionData.events) await resolveItemMentions(sectionData.events);
  1787. if (sectionData.tasks) await resolveItemMentions(sectionData.tasks);
  1788. if (sectionData.feed) await resolveItemMentions(sectionData.feed);
  1789. }
  1790. ctx.body = await tribeView(tribe, uid, query, section, sectionData);
  1791. })
  1792. .get('/activity', async ctx => {
  1793. const filter = qf(ctx, 'recent'), userId = getViewerId();
  1794. const q = String((ctx.query && ctx.query.q) || '');
  1795. try { await bankingModel.ensureSelfAddressPublished(); } catch (_) {}
  1796. try { await bankingModel.getUserEngagementScore(userId); } catch (_) {}
  1797. let allActions = await activityModel.listFeed('all');
  1798. for (const action of allActions) {
  1799. if (action.type === 'pad') {
  1800. const c = action.value?.content || action.content || {};
  1801. const rootId = action.id || action.key || '';
  1802. const decrypted = await padsModel.decryptContent(c, rootId);
  1803. if (decrypted.title) {
  1804. if (action.value?.content) { action.value.content.title = decrypted.title; action.value.content.deadline = decrypted.deadline; }
  1805. else if (action.content) { action.content.title = decrypted.title; action.content.deadline = decrypted.deadline; }
  1806. }
  1807. }
  1808. }
  1809. allActions = await applyListFilters(allActions, ctx);
  1810. ctx.body = activityView(allActions, filter, userId, q);
  1811. })
  1812. .get("/profile", async (ctx) => {
  1813. const myFeedId = await meta.myFeedId(), gt = Number(ctx.request.query.gt || -1), lt = Number(ctx.request.query.lt || -1);
  1814. if (lt > 0 && gt > 0 && gt >= lt) throw new Error("Given search range is empty");
  1815. const [description, name, image, messages, firstPost, lastPost, ecoAddress, bankData] = await Promise.all([
  1816. about.description(myFeedId), about.name(myFeedId), about.image(myFeedId), post.fromPublicFeed(myFeedId, gt, lt),
  1817. post.firstBy(myFeedId), post.latestBy(myFeedId), bankingModel.getUserAddress(myFeedId), bankingModel.getBankingData(myFeedId)
  1818. ]);
  1819. const normTs = t => { const n = Number(t || 0); return !isFinite(n) || n <= 0 ? 0 : n < 1e12 ? n * 1000 : n; };
  1820. const pickTs = obj => { if (!obj) return 0; const v = obj.value || obj; return normTs(v.timestamp || v.ts || v.time || v.meta?.timestamp || 0); };
  1821. let lastActivityTs = Math.max(Array.isArray(messages) && messages.length ? Math.max(...messages.map(pickTs)) : 0, pickTs(lastPost), pickTs(firstPost));
  1822. if (!lastActivityTs) {
  1823. const pull = require("../server/node_modules/pull-stream"), ssb = await require("../client/gui")({ offline: require("../server/ssb_config").offline }).open();
  1824. lastActivityTs = await new Promise(res => pull(ssb.createUserStream({ id: myFeedId, reverse: true }), pull.filter(m => m?.value?.content?.type !== "tombstone"), pull.take(1), pull.collect((err, arr) => res(!err && arr?.[0] ? normTs(arr[0].value?.timestamp || arr[0].timestamp) : 0))));
  1825. }
  1826. const days = lastActivityTs ? (Date.now() - lastActivityTs) / 86400000 : Infinity;
  1827. ctx.body = await authorView({ feedId: myFeedId, messages: sanitizeMessages(messages), firstPost, lastPost, name, description, avatarUrl: getAvatarUrl(image), relationship: { me: true }, ecoAddress, karmaScore: bankData.karmaScore, estimatedUBI: bankData.estimatedUBI || 0, lastClaimedDate: bankData.lastClaimedDate || null, totalClaimed: bankData.totalClaimed || 0, lastActivityBucket: days < 14 ? "green" : days < 182.5 ? "orange" : "red" });
  1828. })
  1829. .get("/profile/edit", async (ctx) => {
  1830. const myFeedId = await meta.myFeedId();
  1831. ctx.body = await editProfileView({ name: await about.name(myFeedId), description: await about.description(myFeedId) });
  1832. })
  1833. .post("/profile/edit", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  1834. const imageFile = ctx.request.files?.image;
  1835. const mime = imageFile?.mimetype || imageFile?.type || '';
  1836. const isImage = mime.startsWith('image/');
  1837. const imageData = isImage && imageFile?.filepath ? await promisesFs.readFile(imageFile.filepath).catch(() => undefined) : undefined;
  1838. await post.publishProfileEdit({
  1839. name: stripDangerousTags(String(ctx.request.body?.name || '')),
  1840. description: stripDangerousTags(String(ctx.request.body?.description || '')),
  1841. image: imageData
  1842. });
  1843. ctx.redirect("/profile");
  1844. })
  1845. .get("/publish/custom", async (ctx) => {
  1846. ctx.body = await publishCustomView();
  1847. })
  1848. .get("/json/:message", async (ctx) => {
  1849. if (config.public) {
  1850. throw new Error(
  1851. "Sorry, many actions are unavailable when Oasis is running in public mode. Please run Oasis in the default mode and try again."
  1852. );
  1853. }
  1854. const { message } = ctx.params;
  1855. ctx.type = "application/json";
  1856. const json = async (message) => {
  1857. const json = await meta.get(message);
  1858. return JSON.stringify(json, null, 2);
  1859. };
  1860. ctx.body = await json(message);
  1861. })
  1862. .get("/blob/:blobId", serveBlob)
  1863. .get("/image/:imageSize/:blobId", async (ctx) => {
  1864. const { blobId, imageSize } = ctx.params;
  1865. const size = Number(imageSize);
  1866. const fallbackPixel = Buffer.from(
  1867. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
  1868. "base64"
  1869. );
  1870. const fakeImage = () => {
  1871. if (typeof sharp !== "function") {
  1872. return Promise.resolve(fallbackPixel);
  1873. }
  1874. return sharp({
  1875. create: {
  1876. width: size,
  1877. height: size,
  1878. channels: 4,
  1879. background: { r: 0, g: 0, b: 0, alpha: 0.5 },
  1880. },
  1881. }).png().toBuffer();
  1882. };
  1883. try {
  1884. const buffer = await blob.getResolved({ blobId });
  1885. if (!buffer) {
  1886. ctx.set("Content-Type", "image/png");
  1887. ctx.body = await fakeImage();
  1888. return;
  1889. }
  1890. const fileType = await FileType.fromBuffer(buffer);
  1891. const mimeType = fileType?.mime || "application/octet-stream";
  1892. ctx.set("Content-Type", mimeType);
  1893. if (typeof sharp === "function") {
  1894. ctx.body = await sharp(buffer)
  1895. .resize(size, size)
  1896. .png()
  1897. .toBuffer();
  1898. } else {
  1899. ctx.body = buffer;
  1900. }
  1901. } catch (err) {
  1902. ctx.set("Content-Type", "image/png");
  1903. ctx.body = await fakeImage();
  1904. }
  1905. })
  1906. .get("/settings", async (ctx) => {
  1907. const cfg = getConfig(), theme = ctx.cookies.get("theme") || "Dark-SNH";
  1908. ctx.body = await settingsView({ theme, version: version.toString(), aiPrompt: cfg.ai?.prompt || "" });
  1909. })
  1910. .get("/peers", async (ctx) => {
  1911. const { discoveredPeers, unknownPeers } = await meta.discovered();
  1912. ctx.body = await peersView({ onlinePeers: await meta.onlinePeers(), discoveredPeers, unknownPeers });
  1913. })
  1914. .get("/invites", async (ctx) => {
  1915. if (!checkMod(ctx, 'invitesMod')) return ctx.redirect('/modules');
  1916. ctx.body = await invitesView({});
  1917. })
  1918. .get("/likes/:feed", async (ctx) => {
  1919. const { feed } = ctx.params;
  1920. ctx.body = await likesView({ messages: await post.likes({ feed }), feed, name: await about.name(feed) });
  1921. })
  1922. .get("/mentions", async (ctx) => {
  1923. const { messages, myFeedId } = await post.mentionsMe();
  1924. const tribeMentions = [];
  1925. try {
  1926. const allTribes = await tribesModel.listAll();
  1927. const myTribes = allTribes.filter(t => t.members.includes(myFeedId));
  1928. for (const t of myTribes) {
  1929. const items = await tribesContentModel.listByTribe(t.id, null).catch(() => []);
  1930. for (const item of items) {
  1931. const text = (item.description || '') + ' ' + (item.title || '');
  1932. if (text.includes(myFeedId) || text.includes(myFeedId.slice(1))) {
  1933. tribeMentions.push({
  1934. key: item.id,
  1935. value: {
  1936. author: item.author,
  1937. timestamp: Date.parse(item.createdAt) || item._ts || Date.now(),
  1938. content: {
  1939. type: 'tribe-content',
  1940. text: item.description || item.title || '',
  1941. tribeId: t.id,
  1942. tribeName: t.title,
  1943. contentType: item.contentType,
  1944. mentions: { _self: [{ link: myFeedId }] }
  1945. }
  1946. }
  1947. });
  1948. }
  1949. }
  1950. }
  1951. } catch (_) {}
  1952. const combined = [...(Array.isArray(messages) ? messages : []), ...tribeMentions];
  1953. for (const msg of combined) {
  1954. if (!msg.value) continue;
  1955. const authorId = msg.value.author;
  1956. if (authorId) {
  1957. if (!msg.value.meta) msg.value.meta = {};
  1958. if (!msg.value.meta.author) msg.value.meta.author = {};
  1959. if (!msg.value.meta.author.name) {
  1960. try { msg.value.meta.author.name = await about.name(authorId); } catch (_) {}
  1961. }
  1962. }
  1963. }
  1964. ctx.body = await mentionsView({ messages: combined, myFeedId });
  1965. })
  1966. .get('/opinions', async (ctx) => {
  1967. const filter = qf(ctx, 'RECENT');
  1968. let opinions = await opinionsModel.listOpinions(filter);
  1969. if (Array.isArray(opinions)) opinions = await applyListFilters(opinions, ctx);
  1970. ctx.body = await opinionsView(opinions, filter);
  1971. })
  1972. .get("/feed", async (ctx) => {
  1973. const filter = String(ctx.query.filter || "ALL").toUpperCase();
  1974. const q = typeof ctx.query.q === "string" ? ctx.query.q : "";
  1975. const tag = typeof ctx.query.tag === "string" ? ctx.query.tag : "";
  1976. const msg = typeof ctx.query.msg === "string" ? ctx.query.msg : "";
  1977. let feeds = await feedModel.listFeeds({ filter, q, tag });
  1978. feeds = await applyListFilters(feeds, ctx);
  1979. ctx.body = feedView(feeds, { filter, q, tag, msg });
  1980. })
  1981. .get("/feed/create", async (ctx) => {
  1982. const q = typeof ctx.query.q === "string" ? ctx.query.q : "";
  1983. const tag = typeof ctx.query.tag === "string" ? ctx.query.tag : "";
  1984. ctx.body = feedCreateView({ q, tag });
  1985. })
  1986. .get("/feed/:feedId", async (ctx) => {
  1987. const feed = await feedModel.getFeedById(ctx.params.feedId);
  1988. if (!feed) { ctx.redirect('/feed'); return; }
  1989. const comments = await feedModel.getComments(ctx.params.feedId).catch(() => []);
  1990. ctx.body = singleFeedView(feed, comments);
  1991. })
  1992. .get('/forum', async ctx => {
  1993. if (!checkMod(ctx, 'forumMod')) { ctx.redirect('/modules'); return; }
  1994. const filter = qf(ctx, 'hot');
  1995. let forums = await forumModel.listAll(filter);
  1996. forums = await applyListFilters(forums, ctx);
  1997. ctx.body = await forumView(forums, filter);
  1998. })
  1999. .get('/forum/:forumId', async ctx => {
  2000. const msg = await forumModel.getMessageById(ctx.params.forumId), isReply = Boolean(msg.root), forumId = isReply ? msg.root : ctx.params.forumId;
  2001. ctx.body = await singleForumView(await forumModel.getForumById(forumId), await forumModel.getMessagesByForumId(forumId), ctx.query.filter, isReply ? ctx.params.forumId : null);
  2002. })
  2003. .get('/legacy', async (ctx) => {
  2004. if (!checkMod(ctx, 'legacyMod')) return ctx.redirect('/modules');
  2005. try { ctx.body = await legacyView(); } catch (error) { ctx.body = { error: error.message }; }
  2006. })
  2007. .get('/bookmarks', async (ctx) => {
  2008. if (!checkMod(ctx, 'bookmarksMod')) return ctx.redirect('/modules');
  2009. const filter = qf(ctx), q = ctx.query.q || '', sort = ctx.query.sort || 'recent', viewerId = getViewerId();
  2010. const favs = await mediaFavorites.getFavoriteSet("bookmarks");
  2011. let bookmarks = (await bookmarksModel.listAll({ viewerId, filter: filter === "favorites" ? "all" : filter, q, sort })).map(b => ({ ...b, isFavorite: favs.has(String(b.rootId || b.id)) }));
  2012. if (filter === "favorites") bookmarks = bookmarks.filter(b => b.isFavorite);
  2013. bookmarks = await applyListFilters(bookmarks, ctx);
  2014. await enrichWithComments(bookmarks, 'rootId');
  2015. ctx.body = await bookmarkView(bookmarks, filter, null, { q, sort });
  2016. })
  2017. .get("/bookmarks/edit/:id", async (ctx) => {
  2018. if (!checkMod(ctx, 'bookmarksMod')) return ctx.redirect('/modules');
  2019. const bookmark = await bookmarksModel.getBookmarkById(ctx.params.id, getViewerId()), favs = await mediaFavorites.getFavoriteSet("bookmarks");
  2020. ctx.body = await bookmarkView([{ ...bookmark, isFavorite: favs.has(String(bookmark.rootId || bookmark.id)) }], "edit", bookmark.id, { returnTo: ctx.query.returnTo || "" });
  2021. })
  2022. .get('/bookmarks/:bookmarkId', async (ctx) => {
  2023. if (!checkMod(ctx, 'bookmarksMod')) return ctx.redirect('/modules');
  2024. const filter = qf(ctx), q = ctx.query.q || '', sort = ctx.query.sort || 'recent', favs = await mediaFavorites.getFavoriteSet("bookmarks");
  2025. const bookmark = await bookmarksModel.getBookmarkById(ctx.params.bookmarkId), root = bookmark.rootId || bookmark.id, comments = await getVoteComments(root);
  2026. ctx.body = await singleBookmarkView({ ...bookmark, commentCount: comments.length, isFavorite: favs.has(String(root)) }, filter, comments, { q, sort, returnTo: safeReturnTo(ctx, `/bookmarks?filter=${encodeURIComponent(filter)}`, ['/bookmarks']) });
  2027. })
  2028. .get('/tasks', async ctx => {
  2029. const filter = qf(ctx);
  2030. let tasks = await enrichWithComments(await tasksModel.listAll());
  2031. tasks = await applyListFilters(tasks, ctx);
  2032. ctx.body = await taskView(tasks, filter, null, ctx.query.returnTo);
  2033. })
  2034. .get('/tasks/edit/:id', async ctx => {
  2035. const id = ctx.params.id;
  2036. const task = await tasksModel.getTaskById(id);
  2037. ctx.body = await taskView(task, 'edit', id, ctx.query.returnTo);
  2038. })
  2039. .get('/tasks/:taskId', async ctx => {
  2040. const { taskId } = ctx.params, filter = qf(ctx), task = await tasksModel.getTaskById(taskId);
  2041. const comments = await getVoteComments(taskId);
  2042. ctx.body = await singleTaskView(withCount(task, comments), filter, comments);
  2043. })
  2044. .get('/events', async (ctx) => {
  2045. if (!checkMod(ctx, 'eventsMod')) { ctx.redirect('/modules'); return; }
  2046. const filter = qf(ctx);
  2047. let events = await enrichWithComments(await eventsModel.listAll(null, filter));
  2048. events = await applyListFilters(events, ctx);
  2049. ctx.body = await eventView(events, filter, null, ctx.query.returnTo);
  2050. })
  2051. .get('/events/edit/:id', async (ctx) => {
  2052. if (!checkMod(ctx, 'eventsMod')) { ctx.redirect('/modules'); return; }
  2053. const eventId = ctx.params.id;
  2054. const event = await eventsModel.getEventById(eventId);
  2055. ctx.body = await eventView([event], 'edit', eventId, ctx.query.returnTo);
  2056. })
  2057. .get('/events/:eventId', async ctx => {
  2058. const { eventId } = ctx.params, filter = qf(ctx), event = await eventsModel.getEventById(eventId);
  2059. const [comments, mapData] = await Promise.all([getVoteComments(eventId), resolveMapUrl(event.mapUrl)]);
  2060. ctx.body = await singleEventView(withCount(event, comments), filter, comments, { mapData });
  2061. })
  2062. .get('/votes', async ctx => {
  2063. const filter = qf(ctx);
  2064. let voteList = await enrichWithComments(await votesModel.listAll(filter));
  2065. voteList = await applyListFilters(voteList, ctx);
  2066. ctx.body = await voteView(voteList, filter, null, [], filter);
  2067. })
  2068. .get('/votes/edit/:id', async ctx => {
  2069. const id = ctx.params.id;
  2070. const activeFilter = (ctx.query.filter || 'mine');
  2071. const voteData = await votesModel.getVoteById(id);
  2072. ctx.body = await voteView([voteData], 'edit', id, [], activeFilter);
  2073. })
  2074. .get('/votes/:voteId', async ctx => {
  2075. const { voteId } = ctx.params, filter = qf(ctx), voteData = await votesModel.getVoteById(voteId);
  2076. const comments = await getVoteComments(voteId);
  2077. ctx.body = await voteView([withCount(voteData, comments)], 'detail', voteId, comments, filter);
  2078. })
  2079. .get("/market", async (ctx) => {
  2080. if (!checkMod(ctx, 'marketMod')) { ctx.redirect('/modules'); return; }
  2081. const filter = qf(ctx), q = ctx.query.q || "", minPrice = ctx.query.minPrice ?? "", maxPrice = ctx.query.maxPrice ?? "", sort = ctx.query.sort || "recent";
  2082. let marketItems = await marketModel.listAllItems("all");
  2083. await marketModel.checkAuctionItemsStatus(marketItems);
  2084. marketItems = await marketModel.listAllItems("all");
  2085. await enrichWithComments(marketItems);
  2086. marketItems = await applyListFilters(marketItems, ctx);
  2087. ctx.body = await marketView(marketItems, filter, null, { q, minPrice, maxPrice, sort });
  2088. })
  2089. .get("/market/edit/:id", async (ctx) => {
  2090. if (!checkMod(ctx, 'marketMod')) { ctx.redirect('/modules'); return; }
  2091. const id = ctx.params.id
  2092. let marketItem = await marketModel.getItemById(id)
  2093. if (!marketItem) ctx.throw(404, "Item not found")
  2094. await marketModel.checkAuctionItemsStatus([marketItem])
  2095. marketItem = await marketModel.getItemById(id)
  2096. if (!marketItem) ctx.throw(404, "Item not found")
  2097. ctx.body = await marketView([marketItem], "edit", marketItem, { q: "", minPrice: "", maxPrice: "", sort: "recent" })
  2098. })
  2099. .get("/market/:itemId", async (ctx) => {
  2100. if (!checkMod(ctx, 'marketMod')) { ctx.redirect('/modules'); return; }
  2101. const { itemId } = ctx.params, filter = qf(ctx), q = ctx.query.q || "", minPrice = ctx.query.minPrice ?? "", maxPrice = ctx.query.maxPrice ?? "", sort = ctx.query.sort || "recent";
  2102. let item = await marketModel.getItemById(itemId)
  2103. if (!item) ctx.throw(404, "Item not found")
  2104. await marketModel.checkAuctionItemsStatus([item])
  2105. item = await marketModel.getItemById(itemId)
  2106. if (!item) ctx.throw(404, "Item not found")
  2107. const zoom = parseInt(ctx.query.zoom) || 2;
  2108. const [comments, mapData] = await Promise.all([getVoteComments(itemId), resolveMapUrl(item.mapUrl)])
  2109. const returnTo = (() => {
  2110. const params = []
  2111. if (filter) params.push(`filter=${encodeURIComponent(filter)}`)
  2112. if (q) params.push(`q=${encodeURIComponent(q)}`)
  2113. if (minPrice !== "" && minPrice != null) params.push(`minPrice=${encodeURIComponent(String(minPrice))}`)
  2114. if (maxPrice !== "" && maxPrice != null) params.push(`maxPrice=${encodeURIComponent(String(maxPrice))}`)
  2115. if (sort) params.push(`sort=${encodeURIComponent(sort)}`)
  2116. return `/market${params.length ? `?${params.join("&")}` : ""}`
  2117. })()
  2118. ctx.body = await singleMarketView(withCount(item, comments), filter, comments, { q, minPrice, maxPrice, sort, returnTo, mapData, zoom })
  2119. })
  2120. .get('/jobs', async (ctx) => {
  2121. if (!checkMod(ctx, 'jobsMod')) { ctx.redirect('/modules'); return; }
  2122. let filter = String(ctx.query.filter || 'ALL').toUpperCase()
  2123. if (filter === 'FAVS' || filter === 'NEEDS') filter = 'ALL'
  2124. const query = {
  2125. search: ctx.query.search || '',
  2126. minSalary: ctx.query.minSalary ?? '',
  2127. maxSalary: ctx.query.maxSalary ?? '',
  2128. sort: ctx.query.sort || 'recent'
  2129. }
  2130. if (filter === 'CREATE') {
  2131. ctx.body = await jobsView([], 'CREATE', query)
  2132. return
  2133. }
  2134. if (filter === 'CV') {
  2135. query.location = ctx.query.location || ''
  2136. query.language = ctx.query.language || ''
  2137. query.skills = ctx.query.skills || ''
  2138. const inhabitants = await inhabitantsModel.listInhabitants({
  2139. filter: 'CVs',
  2140. ...query
  2141. })
  2142. ctx.body = await jobsView(inhabitants, filter, query)
  2143. return
  2144. }
  2145. const viewerId = getViewerId()
  2146. let jobs = await jobsModel.listJobs(filter, viewerId, query)
  2147. await enrichWithComments(jobs)
  2148. jobs = await applyListFilters(jobs, ctx)
  2149. ctx.body = await jobsView(jobs, filter, query)
  2150. })
  2151. .get('/jobs/edit/:id', async (ctx) => {
  2152. if (!checkMod(ctx, 'jobsMod')) { ctx.redirect('/modules'); return; }
  2153. const id = ctx.params.id
  2154. const viewerId = getViewerId()
  2155. const job = await jobsModel.getJobById(id, viewerId)
  2156. ctx.body = await jobsView([job], 'EDIT', {})
  2157. })
  2158. .get('/jobs/:jobId', async (ctx) => {
  2159. if (!checkMod(ctx, 'jobsMod')) { ctx.redirect('/modules'); return; }
  2160. const jobId = ctx.params.jobId
  2161. let filter = String(ctx.query.filter || 'ALL').toUpperCase()
  2162. if (filter === 'FAVS' || filter === 'NEEDS') filter = 'ALL'
  2163. const viewerId = getViewerId()
  2164. const params = {
  2165. search: ctx.query.search || '',
  2166. minSalary: ctx.query.minSalary ?? '',
  2167. maxSalary: ctx.query.maxSalary ?? '',
  2168. sort: ctx.query.sort || 'recent',
  2169. returnTo: safeReturnTo(ctx, `/jobs?filter=${encodeURIComponent(filter)}`, ['/jobs'])
  2170. }
  2171. const job = await jobsModel.getJobById(jobId, viewerId)
  2172. const [comments, mapData] = await Promise.all([getVoteComments(jobId), resolveMapUrl(job.mapUrl)])
  2173. ctx.body = await singleJobsView(withCount(job, comments), filter, comments, { ...params, mapData })
  2174. })
  2175. .get("/shops", async (ctx) => {
  2176. if (!checkMod(ctx, 'shopsMod')) { ctx.redirect('/modules'); return; }
  2177. const { filter = 'all', q = '', sort = 'recent' } = ctx.query;
  2178. if (filter === 'products' || filter === 'prices') {
  2179. const products = await shopsModel.listAllProducts({ filter: 'top', sort, viewerId: getViewerId() });
  2180. const enriched = await Promise.all(products.map(async (prod) => {
  2181. try {
  2182. const shop = await shopsModel.getShopById(prod.shopId);
  2183. return { ...prod, shopTitle: shop ? shop.title : '' };
  2184. } catch (_) { return prod; }
  2185. }));
  2186. ctx.body = await shopsView(enriched, filter, null, { q, sort });
  2187. return;
  2188. }
  2189. const items = await shopsModel.listAll({ filter: filter === 'favorites' ? 'all' : filter, q, sort, viewerId: getViewerId() });
  2190. const fav = await mediaFavorites.getFavoriteSet('shops');
  2191. let enriched = items.map(x => ({ ...x, isFavorite: fav.has(String(x.rootId || x.key)) }));
  2192. if (filter === 'favorites') enriched = enriched.filter(x => x.isFavorite);
  2193. enriched = await applyListFilters(enriched, ctx);
  2194. const withFeatured = await Promise.all(enriched.map(async (shop) => {
  2195. shop.featuredProducts = await shopsModel.listFeaturedProducts(shop.rootId || shop.key);
  2196. return shop;
  2197. }));
  2198. ctx.body = await shopsView(withFeatured, filter, null, { q, sort });
  2199. })
  2200. .get("/shops/edit/:id", async (ctx) => {
  2201. if (!checkMod(ctx, 'shopsMod')) { ctx.redirect('/modules'); return; }
  2202. const shop = await shopsModel.getShopById(ctx.params.id);
  2203. if (!shop) { ctx.redirect('/shops'); return; }
  2204. const fav = await mediaFavorites.getFavoriteSet('shops');
  2205. ctx.body = await shopsView([{ ...shop, isFavorite: fav.has(String(shop.rootId || shop.key)) }], 'edit', shop, { returnTo: ctx.query.returnTo || '' });
  2206. })
  2207. .get("/shops/product/edit/:id", async (ctx) => {
  2208. if (!checkMod(ctx, 'shopsMod')) { ctx.redirect('/modules'); return; }
  2209. const product = await shopsModel.getProductById(ctx.params.id);
  2210. if (!product) { ctx.redirect('/shops'); return; }
  2211. ctx.body = await editProductView(product, ctx.query.shopId || product.shopId, { returnTo: ctx.query.returnTo || '' });
  2212. })
  2213. .get("/shops/product/:productId", async (ctx) => {
  2214. if (!checkMod(ctx, 'shopsMod')) { ctx.redirect('/modules'); return; }
  2215. const product = await shopsModel.getProductById(ctx.params.productId);
  2216. if (!product) { ctx.redirect('/shops'); return; }
  2217. const shop = await shopsModel.getShopById(product.shopId);
  2218. const comments = await getVoteComments(product.key);
  2219. ctx.body = await singleProductView(withCount(product, comments), shop, comments, { shopId: product.shopId, returnTo: safeReturnTo(ctx, `/shops/${encodeURIComponent(product.shopId)}`, ['/shops']) });
  2220. })
  2221. .get("/shops/:shopId", async (ctx) => {
  2222. if (!checkMod(ctx, 'shopsMod')) { ctx.redirect('/modules'); return; }
  2223. const { filter = 'all', q = '', sort = 'recent' } = ctx.query;
  2224. const shop = await shopsModel.getShopById(ctx.params.shopId);
  2225. if (!shop) { ctx.redirect('/shops'); return; }
  2226. const fav = await mediaFavorites.getFavoriteSet('shops');
  2227. const [products, comments, mapData] = await Promise.all([shopsModel.listProducts(shop.rootId || shop.key), getVoteComments(shop.key), resolveMapUrl(shop.mapUrl)]);
  2228. ctx.body = await singleShopView({ ...shop, isFavorite: fav.has(String(shop.rootId || shop.key)), commentCount: comments.length }, filter, products, comments, { q, sort, returnTo: safeReturnTo(ctx, `/shops?filter=${encodeURIComponent(filter)}`, ['/shops']), mapData });
  2229. })
  2230. .get("/chats", async (ctx) => {
  2231. if (!checkMod(ctx, 'chatsMod')) { ctx.redirect('/modules'); return; }
  2232. const { filter = 'all', q = '', tribeId = '' } = ctx.query;
  2233. const viewerId = getViewerId();
  2234. if (filter === 'create') {
  2235. ctx.body = await chatsView([], 'create', null, { q, ...(tribeId ? { tribeId } : {}) });
  2236. return;
  2237. }
  2238. const modelFilter = filter === "favorites" ? "all" : filter;
  2239. const items = await chatsModel.listAll({ filter: modelFilter, q, viewerId });
  2240. const fav = await mediaFavorites.getFavoriteSet('chats');
  2241. const myTribeIds = await getUserTribeIds(viewerId);
  2242. const enriched = items.filter(x => !x.tribeId).map(x => ({ ...x, isFavorite: fav.has(String(x.rootId || x.key)) }));
  2243. let finalList = filter === "favorites" ? enriched.filter(x => x.isFavorite) : enriched;
  2244. finalList = await applyListFilters(finalList, ctx);
  2245. ctx.body = await chatsView(finalList, filter, null, { q });
  2246. })
  2247. .get("/chats/edit/:id", async (ctx) => {
  2248. if (!checkMod(ctx, 'chatsMod')) { ctx.redirect('/modules'); return; }
  2249. const chat = await chatsModel.getChatById(ctx.params.id);
  2250. if (!chat) { ctx.redirect('/chats'); return; }
  2251. ctx.body = await chatsView([], 'edit', chat, { returnTo: ctx.query.returnTo || '' });
  2252. })
  2253. .get("/chats/:chatId", async (ctx) => {
  2254. if (!checkMod(ctx, 'chatsMod')) { ctx.redirect('/modules'); return; }
  2255. const { filter = 'all', q = '' } = ctx.query;
  2256. const uid = getViewerId();
  2257. let chat = await chatsModel.getChatById(ctx.params.chatId);
  2258. if (!chat) { ctx.redirect('/chats'); return; }
  2259. let parentTribe = null;
  2260. if (chat.tribeId) {
  2261. try {
  2262. parentTribe = await tribesModel.getTribeById(chat.tribeId);
  2263. if (!parentTribe.members.includes(uid)) { ctx.body = tribeAccessDeniedView(parentTribe); return; }
  2264. await tribesModel.processIncomingKeys().catch(() => {});
  2265. chat = await chatsModel.getChatById(ctx.params.chatId);
  2266. } catch { ctx.redirect('/tribes'); return; }
  2267. }
  2268. const fav = await mediaFavorites.getFavoriteSet('chats');
  2269. const messages = await chatsModel.listMessages(chat.rootId || chat.key);
  2270. const isTribeMember = !!parentTribe;
  2271. ctx.body = await singleChatView({ ...chat, isFavorite: fav.has(String(chat.rootId || chat.key)), isTribeMember }, filter, messages, { q, returnTo: safeReturnTo(ctx, `/chats?filter=${encodeURIComponent(filter)}`, ['/chats']) });
  2272. })
  2273. .get("/pads", async (ctx) => {
  2274. if (!checkMod(ctx, 'padsMod')) { ctx.redirect('/modules'); return; }
  2275. const filter = String(ctx.query.filter || "all").toLowerCase();
  2276. const uid = getViewerId();
  2277. if (filter === "edit") {
  2278. const id = ctx.query.id;
  2279. if (!id) { ctx.redirect('/pads'); return; }
  2280. const pad = await padsModel.getPadById(id);
  2281. if (!pad || pad.author !== uid) { ctx.redirect('/pads'); return; }
  2282. ctx.body = await padsView([], "edit", pad, {});
  2283. return;
  2284. }
  2285. const q = String(ctx.query.q || "").trim();
  2286. const tribeId = ctx.query.tribeId || "";
  2287. const pads = await padsModel.listAll({ filter, viewerId: uid });
  2288. const fav = await mediaFavorites.getFavoriteSet('pads');
  2289. let enriched = pads.filter(p => !p.tribeId).map(p => ({ ...p, isFavorite: fav.has(String(p.rootId)) }));
  2290. enriched = await applyListFilters(enriched, ctx);
  2291. ctx.body = await padsView(enriched, filter, null, { q, ...(tribeId ? { tribeId } : {}) });
  2292. })
  2293. .get("/pads/:padId", async (ctx) => {
  2294. if (!checkMod(ctx, 'padsMod')) { ctx.redirect('/modules'); return; }
  2295. const uid = getViewerId();
  2296. let pad = await padsModel.getPadById(ctx.params.padId);
  2297. if (!pad) { ctx.redirect('/pads'); return; }
  2298. let parentTribe = null;
  2299. if (pad.tribeId) {
  2300. try {
  2301. parentTribe = await tribesModel.getTribeById(pad.tribeId);
  2302. if (!parentTribe.members.includes(uid)) { ctx.body = tribeAccessDeniedView(parentTribe); return; }
  2303. await tribesModel.processIncomingKeys().catch(() => {});
  2304. pad = await padsModel.getPadById(ctx.params.padId);
  2305. } catch { ctx.redirect('/tribes'); return; }
  2306. }
  2307. const fav = await mediaFavorites.getFavoriteSet('pads');
  2308. const entries = await padsModel.getEntries(pad.rootId);
  2309. const versionKey = ctx.query.version || null;
  2310. const selectedVersion = versionKey
  2311. ? (entries.find(e => e.key === versionKey) || entries[parseInt(versionKey)] || null)
  2312. : null;
  2313. const baseUrl = `${ctx.protocol}://${ctx.host}`;
  2314. const isTribeMember = !!parentTribe;
  2315. ctx.body = await singlePadView({ ...pad, isFavorite: fav.has(String(pad.rootId)), isTribeMember }, entries, { baseUrl, selectedVersion });
  2316. })
  2317. .get("/calendars", async (ctx) => {
  2318. if (!checkMod(ctx, 'calendarsMod')) { ctx.redirect('/modules'); return; }
  2319. const filter = String(ctx.query.filter || "all").toLowerCase();
  2320. const uid = getViewerId();
  2321. if (filter === "edit") {
  2322. const id = ctx.query.id;
  2323. if (!id) { ctx.redirect('/calendars'); return; }
  2324. const cal = await calendarsModel.getCalendarById(id);
  2325. if (!cal || cal.author !== uid) { ctx.redirect('/calendars'); return; }
  2326. ctx.body = await calendarsView([], "edit", cal, {});
  2327. return;
  2328. }
  2329. const q = String(ctx.query.q || "").trim();
  2330. const tribeId = ctx.query.tribeId || "";
  2331. const modelFilter = filter === "favorites" ? "all" : filter;
  2332. const calendars = await calendarsModel.listAll({ filter: modelFilter, viewerId: uid });
  2333. const fav = await mediaFavorites.getFavoriteSet('calendars');
  2334. const myTribeIds = await getUserTribeIds(uid);
  2335. const enriched = calendars.filter(c => !c.tribeId).map(c => ({ ...c, isFavorite: fav.has(String(c.rootId)) }));
  2336. let finalList = filter === "favorites" ? enriched.filter(c => c.isFavorite) : enriched;
  2337. finalList = await applyListFilters(finalList, ctx);
  2338. ctx.body = await calendarsView(finalList, filter, null, { q, ...(tribeId ? { tribeId } : {}) });
  2339. })
  2340. .get("/calendars/:calId", async (ctx) => {
  2341. if (!checkMod(ctx, 'calendarsMod')) { ctx.redirect('/modules'); return; }
  2342. const uid = getViewerId();
  2343. const cal = await calendarsModel.getCalendarById(ctx.params.calId);
  2344. if (!cal) { ctx.redirect('/calendars'); return; }
  2345. let parentTribe = null;
  2346. if (cal.tribeId) {
  2347. try {
  2348. parentTribe = await tribesModel.getTribeById(cal.tribeId);
  2349. if (!parentTribe.members.includes(uid)) { ctx.body = tribeAccessDeniedView(parentTribe); return; }
  2350. } catch { ctx.redirect('/tribes'); return; }
  2351. }
  2352. if (String(cal.status || '').toUpperCase() === 'CLOSED' && cal.author !== uid) {
  2353. ctx.body = tribeAccessDeniedView(parentTribe); return;
  2354. }
  2355. const dates = await calendarsModel.getDatesForCalendar(cal.rootId);
  2356. const notesByDate = {};
  2357. for (const d of dates) {
  2358. notesByDate[d.key] = await calendarsModel.getNotesForDate(cal.rootId, d.key);
  2359. }
  2360. const fav = await mediaFavorites.getFavoriteSet('calendars');
  2361. const month = String(ctx.query.month || "").trim() || null;
  2362. const day = String(ctx.query.day || "").trim() || null;
  2363. ctx.body = await singleCalendarView({ ...cal, isFavorite: fav.has(String(cal.rootId)) }, dates, notesByDate, { month, day });
  2364. })
  2365. .get("/projects", async (ctx) => {
  2366. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  2367. const filter = String(ctx.query.filter || "ALL").toUpperCase()
  2368. if (filter === "CREATE") {
  2369. ctx.body = await projectsView([], "CREATE")
  2370. return
  2371. }
  2372. const modelFilter = filter === "BACKERS" ? "ALL" : filter
  2373. let projects = await projectsModel.listProjects(modelFilter)
  2374. await enrichWithComments(projects)
  2375. projects = await applyListFilters(projects, ctx)
  2376. ctx.body = await projectsView(projects, filter)
  2377. })
  2378. .get("/projects/edit/:id", async (ctx) => {
  2379. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  2380. const id = ctx.params.id
  2381. const pr = await projectsModel.getProjectById(id)
  2382. ctx.body = await projectsView([pr], "EDIT")
  2383. })
  2384. .get("/projects/:projectId", async (ctx) => {
  2385. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  2386. const projectId = ctx.params.projectId
  2387. const filter = String(ctx.query.filter || "ALL").toUpperCase()
  2388. const project = await projectsModel.getProjectById(projectId)
  2389. const zoom = parseInt(ctx.query.zoom) || 2;
  2390. const [comments, mapData] = await Promise.all([getVoteComments(projectId), resolveMapUrl(project.mapUrl)])
  2391. ctx.body = await singleProjectView(withCount(project, comments), filter, comments, { mapData, zoom })
  2392. })
  2393. .get("/banking", async (ctx) => {
  2394. if (!checkMod(ctx, 'bankingMod')) { ctx.redirect('/modules'); return; }
  2395. const userId = getViewerId();
  2396. const query = ctx.query;
  2397. const filter = (query.filter || 'overview').toLowerCase();
  2398. const q = (query.q || '').trim();
  2399. const msg = (query.msg || '').trim();
  2400. await bankingModel.ensureSelfAddressPublished();
  2401. if (bankingModel.isPubNode() && filter === 'overview') {
  2402. try { await bankingModel.executeEpoch({}); } catch (_) {}
  2403. try { await bankingModel.processPendingClaims(); } catch (_) {}
  2404. }
  2405. const data = await bankingModel.listBanking(filter, userId);
  2406. data.isPub = bankingModel.isPubNode();
  2407. data.alreadyClaimed = data.summary?.alreadyClaimed || false;
  2408. if (filter === 'overview') {
  2409. const pending = (data.allocations || []).find(a => a.to === userId && (a.status === "UNCLAIMED" || a.status === "UNCONFIRMED"));
  2410. data.pendingUBI = pending || null;
  2411. }
  2412. if (filter === 'addresses' && q) {
  2413. data.addresses = (data.addresses || []).filter(x =>
  2414. String(x.id).toLowerCase().includes(q.toLowerCase()) ||
  2415. String(x.address).toLowerCase().includes(q.toLowerCase())
  2416. );
  2417. data.search = q;
  2418. }
  2419. data.flash = msg || '';
  2420. const { ecoValue, inflationFactor, inflationMonthly, ecoTimeMs, currentSupply, isSynced } = await bankingModel.calculateEcoinValue();
  2421. data.exchange = {
  2422. ecoValue,
  2423. inflationFactor,
  2424. inflationMonthly,
  2425. ecoTimeMs,
  2426. currentSupply,
  2427. totalSupply: 25500000,
  2428. isSynced
  2429. };
  2430. ctx.body = renderBankingView(data, filter, userId, data.isPub);
  2431. })
  2432. .get("/banking/allocation/:id", async (ctx) => {
  2433. const userId = getViewerId();
  2434. const allocation = await bankingModel.getAllocationById(ctx.params.id);
  2435. ctx.body = renderSingleAllocationView(allocation, userId);
  2436. })
  2437. .get("/banking/epoch/:id", async (ctx) => {
  2438. const epoch = await bankingModel.getEpochById(ctx.params.id);
  2439. const allocations = await bankingModel.listEpochAllocations(ctx.params.id);
  2440. ctx.body = renderEpochView(epoch, allocations);
  2441. })
  2442. .get("/favorites", async (ctx) => {
  2443. const filter = qf(ctx), data = await favoritesModel.listAll({ filter });
  2444. ctx.body = await favoritesView(data.items, filter, data.counts);
  2445. })
  2446. .get("/logs", async (ctx) => {
  2447. if (!checkMod(ctx, 'logsMod')) { ctx.redirect('/modules'); return; }
  2448. const view = String(ctx.query.view || 'list');
  2449. const aiModOn = logsModel.isAImodOn();
  2450. if (view === 'create') {
  2451. const mode = ctx.query.mode === 'ai' ? 'ai' : 'manual';
  2452. ctx.body = logsView([], 'today', mode, { view: 'create', aiModOn });
  2453. return;
  2454. }
  2455. if (view === 'edit') {
  2456. const id = String(ctx.query.id || '');
  2457. const entry = id ? await logsModel.getLogById(id) : null;
  2458. if (!entry) { ctx.redirect('/logs'); return; }
  2459. ctx.body = logsView([], 'today', entry.mode, { view: 'edit', aiModOn, entry });
  2460. return;
  2461. }
  2462. const filter = qf(ctx, 'today');
  2463. const q = String(ctx.query.q || '').trim().toLowerCase();
  2464. const typeQ = String(ctx.query.type || '').trim().toLowerCase();
  2465. const dateQ = String(ctx.query.date || '').trim();
  2466. let items = await logsModel.listLogs(filter);
  2467. if (q) items = items.filter(i => String(i.text || '').toLowerCase().includes(q) || String(i.label || '').toLowerCase().includes(q));
  2468. if (typeQ === 'ai' || typeQ === 'manual') items = items.filter(i => (i.mode === 'ai' ? 'ai' : 'manual') === typeQ);
  2469. if (/^\d{4}-\d{2}-\d{2}$/.test(dateQ)) {
  2470. const start = new Date(dateQ + 'T00:00:00').getTime();
  2471. const end = start + 24 * 60 * 60 * 1000;
  2472. items = items.filter(i => i.ts >= start && i.ts < end);
  2473. }
  2474. ctx.body = logsView(items, filter, null, { view: 'list', aiModOn, search: { q: ctx.query.q || '', type: typeQ, date: dateQ } });
  2475. })
  2476. .get("/logs/view/:id", async (ctx) => {
  2477. if (!checkMod(ctx, 'logsMod')) { ctx.redirect('/modules'); return; }
  2478. const entry = await logsModel.getLogById(ctx.params.id);
  2479. if (!entry) { ctx.redirect('/logs'); return; }
  2480. const aiModOn = logsModel.isAImodOn();
  2481. ctx.body = logsView([], 'today', entry.mode, { view: 'detail', aiModOn, entry });
  2482. })
  2483. .post("/logs/create", koaBody(), async (ctx) => {
  2484. if (!checkMod(ctx, 'logsMod')) { ctx.redirect('/modules'); return; }
  2485. const b = ctx.request.body || {};
  2486. const mode = b.mode === 'ai' ? 'ai' : 'manual';
  2487. try {
  2488. if (mode === 'ai') { startAI(); await logsModel.createAI(); }
  2489. else await logsModel.createManual(b.label || '', b.text || '');
  2490. } catch (_) {}
  2491. ctx.redirect('/logs');
  2492. })
  2493. .post("/logs/edit/:id", koaBody(), async (ctx) => {
  2494. if (!checkMod(ctx, 'logsMod')) { ctx.redirect('/modules'); return; }
  2495. const b = ctx.request.body || {};
  2496. try { await logsModel.updateLog(ctx.params.id, { label: b.label || '', text: b.text || '' }); } catch (_) {}
  2497. ctx.redirect('/logs');
  2498. })
  2499. .post("/logs/delete/:id", koaBody(), async (ctx) => {
  2500. if (!checkMod(ctx, 'logsMod')) { ctx.redirect('/modules'); return; }
  2501. try { await logsModel.deleteLog(ctx.params.id); } catch (_) {}
  2502. ctx.redirect('/logs');
  2503. })
  2504. .get("/logs/export", async (ctx) => {
  2505. if (!checkMod(ctx, 'logsMod')) { ctx.redirect('/modules'); return; }
  2506. const items = await logsModel.listLogs('always');
  2507. const pdf = await buildLogsPdf(items, getViewerId());
  2508. ctx.set('Content-Type', 'application/pdf');
  2509. ctx.set('Content-Disposition', `attachment; filename="oasis-logs-${Date.now()}.pdf"`);
  2510. ctx.body = pdf;
  2511. })
  2512. .get("/logs/export/:id", async (ctx) => {
  2513. if (!checkMod(ctx, 'logsMod')) { ctx.redirect('/modules'); return; }
  2514. const entry = await logsModel.getLogById(ctx.params.id);
  2515. if (!entry) { ctx.redirect('/logs'); return; }
  2516. const pdf = await buildLogsPdf([entry], getViewerId());
  2517. ctx.set('Content-Type', 'application/pdf');
  2518. ctx.set('Content-Disposition', `attachment; filename="oasis-log-${Date.now()}.pdf"`);
  2519. ctx.body = pdf;
  2520. })
  2521. .get('/cipher', async (ctx) => {
  2522. if (!checkMod(ctx, 'cipherMod')) { ctx.redirect('/modules'); return; }
  2523. try {
  2524. ctx.body = await cipherView();
  2525. } catch (error) {
  2526. ctx.body = { error: error.message };
  2527. }
  2528. })
  2529. .get("/thread/:message", async (ctx) => {
  2530. const { message } = ctx.params;
  2531. const thread = async (message) => {
  2532. const messages = await post.fromThread(message);
  2533. return threadView({ messages });
  2534. };
  2535. ctx.body = await thread(message);
  2536. })
  2537. .get("/subtopic/:message", async (ctx) => {
  2538. const { message } = ctx.params;
  2539. const rootMessage = await post.get(message);
  2540. const myFeedId = await meta.myFeedId();
  2541. debug("%O", rootMessage);
  2542. const messages = [rootMessage];
  2543. ctx.body = await subtopicView({ messages, myFeedId });
  2544. })
  2545. .get("/publish", async (ctx) => {
  2546. ctx.body = await publishView();
  2547. })
  2548. .get("/comment/:message", async (ctx) => {
  2549. const { messages, myFeedId, parentMessage } =
  2550. await resolveCommentComponents(ctx);
  2551. ctx.body = await commentView({ messages, myFeedId, parentMessage });
  2552. })
  2553. .get("/wallet", async (ctx) => {
  2554. const { url, user, pass } = getConfig().wallet;
  2555. if (!checkMod(ctx, 'walletMod')) { ctx.redirect('/modules'); return; }
  2556. try {
  2557. const balance = await walletModel.getBalance(url, user, pass);
  2558. const address = await walletModel.getAddress(url, user, pass);
  2559. const userId = getViewerId();
  2560. if (address && typeof address === "string") {
  2561. const map = readAddrMap();
  2562. const was = map[userId];
  2563. if (was !== address) {
  2564. map[userId] = address;
  2565. writeAddrMap(map);
  2566. try { await publishActivity({ type: 'bankWallet', address }); } catch (e) {}
  2567. }
  2568. }
  2569. ctx.body = await walletView(balance, address);
  2570. } catch (error) {
  2571. ctx.body = await walletErrorView(error);
  2572. }
  2573. })
  2574. .get("/wallet/history", async (ctx) => {
  2575. const { url, user, pass } = getConfig().wallet;
  2576. try {
  2577. const balance = await walletModel.getBalance(url, user, pass);
  2578. const transactions = await walletModel.listTransactions(url, user, pass);
  2579. const address = await walletModel.getAddress(url, user, pass);
  2580. const userId = getViewerId();
  2581. if (address && typeof address === "string") {
  2582. const map = readAddrMap();
  2583. const was = map[userId];
  2584. if (was !== address) {
  2585. map[userId] = address;
  2586. writeAddrMap(map);
  2587. try { await publishActivity({ type: 'bankWallet', address }); } catch (e) {}
  2588. }
  2589. }
  2590. ctx.body = await walletHistoryView(balance, transactions, address);
  2591. } catch (error) {
  2592. ctx.body = await walletErrorView(error);
  2593. }
  2594. })
  2595. .get("/wallet/receive", async (ctx) => {
  2596. const { url, user, pass } = getConfig().wallet;
  2597. try {
  2598. const balance = await walletModel.getBalance(url, user, pass);
  2599. const address = await walletModel.getAddress(url, user, pass);
  2600. const userId = getViewerId();
  2601. if (address && typeof address === "string") {
  2602. const map = readAddrMap();
  2603. const was = map[userId];
  2604. if (was !== address) {
  2605. map[userId] = address;
  2606. writeAddrMap(map);
  2607. try { await publishActivity({ type: 'bankWallet', address }); } catch (e) {}
  2608. }
  2609. }
  2610. ctx.body = await walletReceiveView(balance, address);
  2611. } catch (error) {
  2612. ctx.body = await walletErrorView(error);
  2613. }
  2614. })
  2615. .get("/wallet/send", async (ctx) => {
  2616. const { url, user, pass, fee } = getConfig().wallet;
  2617. try {
  2618. const balance = await walletModel.getBalance(url, user, pass);
  2619. const address = await walletModel.getAddress(url, user, pass);
  2620. const userId = getViewerId();
  2621. if (address && typeof address === "string") {
  2622. const map = readAddrMap();
  2623. const was = map[userId];
  2624. if (was !== address) {
  2625. map[userId] = address;
  2626. writeAddrMap(map);
  2627. try { await publishActivity({ type: 'bankWallet', address }); } catch (e) {}
  2628. }
  2629. }
  2630. ctx.body = await walletSendFormView(balance, null, null, fee, null, address);
  2631. } catch (error) {
  2632. ctx.body = await walletErrorView(error);
  2633. }
  2634. })
  2635. .get('/transfers', async ctx => {
  2636. if (!checkMod(ctx, 'transfersMod')) { ctx.redirect('/modules'); return; }
  2637. let filter = ctx.query.filter || 'all'; if (filter === 'favs') filter = 'all';
  2638. const list = await transfersModel.listAll(filter, getViewerId());
  2639. ctx.body = await transferView(list, filter, null, { q: ctx.query.q || '', minAmount: ctx.query.minAmount ?? '', maxAmount: ctx.query.maxAmount ?? '', sort: ctx.query.sort || 'recent' });
  2640. })
  2641. .get('/transfers/edit/:id', async ctx => {
  2642. if (!checkMod(ctx, 'transfersMod')) { ctx.redirect('/modules'); return; }
  2643. const tr = await transfersModel.getTransferById(ctx.params.id, getViewerId());
  2644. ctx.body = await transferView([tr], 'edit', ctx.params.id, {});
  2645. })
  2646. .get('/transfers/:transferId', async ctx => {
  2647. if (!checkMod(ctx, 'transfersMod')) { ctx.redirect('/modules'); return; }
  2648. let filter = ctx.query.filter || 'all'; if (filter === 'favs') filter = 'all';
  2649. const transfer = await transfersModel.getTransferById(ctx.params.transferId, getViewerId());
  2650. ctx.body = await singleTransferView(transfer, filter, { q: ctx.query.q || '', minAmount: ctx.query.minAmount ?? '', maxAmount: ctx.query.maxAmount ?? '', sort: ctx.query.sort || 'recent', returnTo: safeReturnTo(ctx, `/transfers?filter=${encodeURIComponent(filter)}`, ['/transfers']) });
  2651. })
  2652. .post('/ai', koaBody(), async (ctx) => {
  2653. const { input } = ctx.request.body;
  2654. if (!input) {
  2655. ctx.status = 400;
  2656. ctx.body = { error: 'No input provided' };
  2657. return;
  2658. }
  2659. startAI();
  2660. const i18nAll = require('../client/assets/translations/i18n');
  2661. const lang = ctx.cookies.get('language') || getConfig().language || 'en';
  2662. const translations = i18nAll[lang] || i18nAll['en'];
  2663. const { setLanguage } = require('../views/main_views');
  2664. setLanguage(lang);
  2665. const historyPath = path.join(__dirname, '..', '..', 'src', 'configs', 'AI-history.json');
  2666. let chatHistory = [];
  2667. try {
  2668. const fileData = fs.readFileSync(historyPath, 'utf-8');
  2669. chatHistory = JSON.parse(fileData);
  2670. } catch {
  2671. chatHistory = [];
  2672. }
  2673. const config = getConfig();
  2674. const userPrompt = config.ai?.prompt?.trim() || 'Provide an informative and precise response.';
  2675. try {
  2676. let aiResponse = '';
  2677. let snippets = [];
  2678. const trained = await getBestTrainedAnswer(input);
  2679. if (trained && trained.answer) {
  2680. aiResponse = trained.answer;
  2681. snippets = Array.isArray(trained.ctx) ? trained.ctx : [];
  2682. } else {
  2683. const response = await axios.post('http://localhost:4001/ai', { input });
  2684. aiResponse = response.data.answer;
  2685. snippets = Array.isArray(response.data.snippets) ? response.data.snippets : [];
  2686. }
  2687. chatHistory.unshift({
  2688. prompt: userPrompt,
  2689. question: input,
  2690. answer: aiResponse,
  2691. timestamp: Date.now(),
  2692. trainStatus: 'pending',
  2693. snippets
  2694. });
  2695. } catch (e) {
  2696. chatHistory.unshift({
  2697. prompt: userPrompt,
  2698. question: input,
  2699. answer: translations.aiServerError || 'The AI could not answer. Please try again.',
  2700. timestamp: Date.now(),
  2701. trainStatus: 'rejected',
  2702. snippets: []
  2703. });
  2704. }
  2705. chatHistory = chatHistory.slice(0, 20);
  2706. fs.writeFileSync(historyPath, JSON.stringify(chatHistory, null, 2), 'utf-8');
  2707. ctx.body = aiView(chatHistory, userPrompt);
  2708. })
  2709. .post('/ai/approve', koaBody(), async (ctx) => {
  2710. const ts = String(ctx.request.body.ts || '');
  2711. const custom = String(ctx.request.body.custom || '').trim();
  2712. const historyPath = path.join(__dirname, '..', '..', 'src', 'configs', 'AI-history.json');
  2713. let chatHistory = [];
  2714. try {
  2715. const fileData = fs.readFileSync(historyPath, 'utf-8');
  2716. chatHistory = JSON.parse(fileData);
  2717. } catch {
  2718. chatHistory = [];
  2719. }
  2720. const item = chatHistory.find(e => String(e.timestamp) === ts);
  2721. if (item) {
  2722. try {
  2723. if (custom) item.answer = stripDangerousTags(custom);
  2724. item.type = 'aiExchange';
  2725. let snippets = fieldsForSnippet('aiExchange', item);
  2726. if (snippets.length === 0) {
  2727. const context = await buildContext();
  2728. snippets = [context];
  2729. } else {
  2730. snippets = snippets.map(snippet => clip(snippet, 200));
  2731. }
  2732. await publishExchange({
  2733. q: item.question,
  2734. a: item.answer,
  2735. ctx: snippets,
  2736. tokens: {}
  2737. });
  2738. item.trainStatus = 'approved';
  2739. } catch {
  2740. item.trainStatus = 'failed';
  2741. }
  2742. fs.writeFileSync(historyPath, JSON.stringify(chatHistory, null, 2), 'utf-8');
  2743. }
  2744. const config = getConfig();
  2745. const userPrompt = config.ai?.prompt?.trim() || '';
  2746. ctx.body = aiView(chatHistory, userPrompt);
  2747. })
  2748. .post('/ai/reject', koaBody(), async (ctx) => {
  2749. const i18nAll = require('../client/assets/translations/i18n');
  2750. const lang = ctx.cookies.get('language') || getConfig().language || 'en';
  2751. const { setLanguage } = require('../views/main_views');
  2752. setLanguage(lang);
  2753. const ts = String(ctx.request.body.ts || '');
  2754. const historyPath = path.join(__dirname, '..', '..', 'src', 'configs', 'AI-history.json');
  2755. let chatHistory = [];
  2756. try {
  2757. const fileData = fs.readFileSync(historyPath, 'utf-8');
  2758. chatHistory = JSON.parse(fileData);
  2759. } catch {
  2760. chatHistory = [];
  2761. }
  2762. const item = chatHistory.find(e => String(e.timestamp) === ts);
  2763. if (item) {
  2764. item.trainStatus = 'rejected';
  2765. fs.writeFileSync(historyPath, JSON.stringify(chatHistory, null, 2), 'utf-8');
  2766. }
  2767. const config = getConfig();
  2768. const userPrompt = config.ai?.prompt?.trim() || '';
  2769. ctx.body = aiView(chatHistory, userPrompt);
  2770. })
  2771. .post('/ai/clear', async (ctx) => {
  2772. const i18nAll = require('../client/assets/translations/i18n');
  2773. const lang = ctx.cookies.get('language') || getConfig().language || 'en';
  2774. const { setLanguage } = require('../views/main_views');
  2775. setLanguage(lang);
  2776. const historyPath = path.join(__dirname, '..', '..', 'src', 'configs', 'AI-history.json');
  2777. fs.writeFileSync(historyPath, '[]', 'utf-8');
  2778. const config = getConfig();
  2779. const userPrompt = config.ai?.prompt?.trim() || '';
  2780. ctx.body = aiView([], userPrompt);
  2781. })
  2782. .post('/pixelia/paint', koaBody(), async (ctx) => {
  2783. const x = Number(ctx.request.body.x), y = Number(ctx.request.body.y), color = ctx.request.body.color;
  2784. if (!Number.isFinite(x) || !Number.isFinite(y) || x < 1 || x > 50 || y < 1 || y > 200) {
  2785. const errorMessage = 'Coordinates are wrong!';
  2786. const pixelArt = await pixeliaModel.listPixels();
  2787. ctx.body = pixeliaView(pixelArt, errorMessage);
  2788. return;
  2789. }
  2790. await pixeliaModel.paintPixel(x, y, color);
  2791. ctx.redirect('/pixelia');
  2792. })
  2793. .post('/pm', koaBody(), async ctx => {
  2794. const { recipients, subject, text } = ctx.request.body;
  2795. const recipientsArr = (recipients || '').split(',').map(s => s.trim()).filter(Boolean).filter(id => ssbRef.isFeedId(id));
  2796. if (recipientsArr.length === 0) { ctx.throw(400, 'No valid recipients'); return; }
  2797. const cfgNow = getConfig();
  2798. if (cfgNow.pmVisibility === 'mutuals') {
  2799. const viewer = getViewerId();
  2800. for (const rid of recipientsArr) {
  2801. if (rid === viewer) continue;
  2802. let rel;
  2803. try { rel = await friend.getRelationship(rid); } catch (e) { rel = null; }
  2804. const mutual = !!(rel && rel.following && rel.followsMe);
  2805. if (!mutual) ctx.throw(403, 'You can only send private messages to habitants with mutual support.');
  2806. }
  2807. }
  2808. await pmModel.sendMessage(recipientsArr, stripDangerousTags(subject), stripDangerousTags(text));
  2809. await refreshInboxCount();
  2810. ctx.redirect('/inbox?filter=sent');
  2811. })
  2812. .post('/pm/preview', koaBody(), async ctx => {
  2813. const { recipients = '', subject = '', text = '' } = ctx.request.body;
  2814. ctx.body = await pmView(recipients, subject, text, true);
  2815. })
  2816. .post('/inbox/delete/:id', koaBody(), async ctx => {
  2817. await pmModel.deleteMessageById(ctx.params.id);
  2818. await refreshInboxCount();
  2819. ctx.redirect('/inbox');
  2820. })
  2821. .post("/search", koaBody(), async (ctx) => {
  2822. const b = ctx.request.body, query = b.query || "";
  2823. let types = b.type || [];
  2824. if (typeof types === "string") types = [types];
  2825. if (!Array.isArray(types)) types = [];
  2826. if (!query) return ctx.body = await searchView({ messages: [], query, types });
  2827. const userId = getViewerId();
  2828. const allTribes = await tribesModel.listAll();
  2829. const anonTribeIds = new Set(allTribes.filter(t => t.isAnonymous === true).map(t => t.id));
  2830. const applySearchPrivacy = (msgs) => msgs.filter(msg => {
  2831. const c = msg.value?.content;
  2832. if (!c) return true;
  2833. if (c.tribeId && anonTribeIds.has(c.tribeId)) return false;
  2834. if (c.type === 'event' && c.isPublic === 'private' && c.organizer !== userId && !(Array.isArray(c.attendees) && c.attendees.includes(userId))) return false;
  2835. if (c.type === 'task' && String(c.isPublic).toUpperCase() === 'PRIVATE' && c.author !== userId && !(Array.isArray(c.assignees) && c.assignees.includes(userId))) return false;
  2836. if (c.status === 'PRIVATE') return false;
  2837. if (c.type === 'shop' && c.visibility === 'CLOSED' && c.author !== userId) return false;
  2838. return true;
  2839. });
  2840. const results = await searchModel.search({ query, types });
  2841. ctx.body = await searchView({ results: Object.entries(results).reduce((acc, [type, msgs]) => {
  2842. const filtered = applySearchPrivacy(msgs).map(msg => (!msg.value?.content) ? {} : { ...msg, content: msg.value.content, author: msg.value.content.author || 'Unknown' });
  2843. if (filtered.length > 0) acc[type] = filtered;
  2844. return acc;
  2845. }, {}), query, types });
  2846. })
  2847. .post("/subtopic/preview/:message",
  2848. koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }),
  2849. async (ctx) => {
  2850. const { message } = ctx.params;
  2851. const rootMessage = await post.get(message);
  2852. const myFeedId = await meta.myFeedId();
  2853. const rawContentWarning = stripDangerousTags(String(ctx.request.body.contentWarning).trim());
  2854. const contentWarning =
  2855. rawContentWarning.length > 0 ? rawContentWarning : undefined;
  2856. const messages = [rootMessage];
  2857. const previewData = await preparePreview(ctx);
  2858. ctx.body = await previewSubtopicView({
  2859. messages,
  2860. myFeedId,
  2861. previewData,
  2862. contentWarning,
  2863. });
  2864. }
  2865. )
  2866. .post("/subtopic/:message", koaBody(), async (ctx) => {
  2867. const { message } = ctx.params;
  2868. const text = stripDangerousTags(String(ctx.request.body.text));
  2869. const rawContentWarning = stripDangerousTags(String(ctx.request.body.contentWarning).trim());
  2870. const contentWarning =
  2871. rawContentWarning.length > 0 ? rawContentWarning : undefined;
  2872. const publishSubtopic = async ({ message, text }) => {
  2873. const mentions = extractMentions(text);
  2874. const parent = await post.get(message);
  2875. return post.subtopic({
  2876. parent,
  2877. message: { text, mentions, contentWarning },
  2878. });
  2879. };
  2880. ctx.body = await publishSubtopic({ message, text });
  2881. ctx.redirect(`/thread/${encodeURIComponent(message)}`);
  2882. })
  2883. .post("/comment/preview/:message", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  2884. const { messages, contentWarning, myFeedId, parentMessage } = await resolveCommentComponents(ctx);
  2885. const previewData = await preparePreview(ctx);
  2886. ctx.body = await previewCommentView({
  2887. messages,
  2888. myFeedId,
  2889. contentWarning,
  2890. previewData,
  2891. parentMessage,
  2892. });
  2893. })
  2894. .post("/comment/:message", koaBody(), async (ctx) => {
  2895. let decodedMessage;
  2896. try {
  2897. decodedMessage = decodeURIComponent(ctx.params.message);
  2898. } catch {
  2899. decodedMessage = ctx.params.message;
  2900. }
  2901. const text = stripDangerousTags(String(ctx.request.body.text));
  2902. const rawContentWarning = stripDangerousTags(String(ctx.request.body.contentWarning));
  2903. const contentWarning =
  2904. rawContentWarning.length > 0 ? rawContentWarning : undefined;
  2905. let mentions = extractMentions(text);
  2906. if (!Array.isArray(mentions)) mentions = [];
  2907. const parent = await meta.get(decodedMessage);
  2908. ctx.body = await post.comment({
  2909. parent,
  2910. message: {
  2911. text,
  2912. mentions,
  2913. contentWarning
  2914. },
  2915. });
  2916. ctx.redirect(`/thread/${encodeURIComponent(parent.key)}`);
  2917. })
  2918. .post("/publish/preview", koaBody({multipart: true, formidable: { multiples: false, maxFileSize: maxSize }, urlencoded: true }), async (ctx) => {
  2919. const cw = stripDangerousTags(ctx.request.body.contentWarning?.toString().trim() || "");
  2920. ctx.body = await previewView({ previewData: await preparePreview(ctx), contentWarning: cw.length > 0 ? cw : undefined });
  2921. })
  2922. .post("/publish", koaBody({ multipart: true, urlencoded: true, formidable: { multiples: false, maxFileSize: maxSize } }), async (ctx) => {
  2923. const b = ctx.request.body, text = stripDangerousTags(b.text?.toString().trim() || ""), cw = stripDangerousTags(b.contentWarning?.toString().trim() || "");
  2924. let mentions = [];
  2925. try { mentions = JSON.parse(b.mentions || "[]"); } catch { mentions = await extractMentions(text); }
  2926. await post.root({ text, mentions, contentWarning: cw.length > 0 ? cw : undefined });
  2927. ctx.redirect("/public/latest");
  2928. })
  2929. .post("/publish/custom", koaBody(), async (ctx) => {
  2930. const text = String(ctx.request.body.text);
  2931. const obj = JSON.parse(text);
  2932. const ALLOWED_TYPES = ['post','about','contact','vote','pub','channel'];
  2933. if (!obj.type || !ALLOWED_TYPES.includes(obj.type)) { ctx.throw(400, 'Invalid message type'); return; }
  2934. const sanitizeObj = (o) => { for (const k of Object.keys(o)) { if (typeof o[k] === 'string') o[k] = stripDangerousTags(o[k]); else if (o[k] && typeof o[k] === 'object') sanitizeObj(o[k]); } };
  2935. sanitizeObj(obj);
  2936. ctx.body = await post.publishCustom(obj);
  2937. ctx.redirect(`/public/latest`);
  2938. })
  2939. .post("/follow/:feed", koaBody(), async (ctx) => {
  2940. ctx.body = await friend.follow(ctx.params.feed);
  2941. ctx.redirect(new URL(ctx.request.header.referer).href);
  2942. })
  2943. .post("/unfollow/:feed", koaBody(), async (ctx) => {
  2944. ctx.body = await friend.unfollow(ctx.params.feed);
  2945. ctx.redirect(new URL(ctx.request.header.referer).href);
  2946. })
  2947. .post("/block/:feed", koaBody(), async (ctx) => {
  2948. ctx.body = await friend.block(ctx.params.feed);
  2949. ctx.redirect(new URL(ctx.request.header.referer).href);
  2950. })
  2951. .post("/unblock/:feed", koaBody(), async (ctx) => {
  2952. ctx.body = await friend.unblock(ctx.params.feed);
  2953. ctx.redirect(new URL(ctx.request.header.referer).href);
  2954. })
  2955. .post("/like/:message", koaBody(), async (ctx) => {
  2956. const { message } = ctx.params, voteValue = Number(ctx.request.body.voteValue);
  2957. const referer = new URL(ctx.request.header.referer);
  2958. referer.hash = `centered-footer-${encodeURIComponent(message)}`;
  2959. const msgData = await post.get(message);
  2960. const isPrivate = msgData.value.meta.private === true;
  2961. const normalized = (isPrivate ? msgData.value.content.recps : []).map(r => typeof r === 'string' ? r : r?.link).filter(Boolean);
  2962. ctx.body = await vote.publish({ messageKey: message, value: voteValue, recps: normalized.length ? normalized : undefined });
  2963. ctx.redirect(referer.href);
  2964. })
  2965. .post('/forum/create', koaBody(), async ctx => {
  2966. const { category, title, text } = ctx.request.body;
  2967. await forumModel.createForum(category, stripDangerousTags(title), stripDangerousTags(text));
  2968. ctx.redirect('/forum');
  2969. })
  2970. .post('/forum/:id/message', koaBody(), async ctx => {
  2971. const { message, parentId } = ctx.request.body;
  2972. const cleanedMsg = stripDangerousTags(message);
  2973. const mentions = await extractMentions(cleanedMsg);
  2974. await forumModel.addMessageToForum(ctx.params.id, { text: cleanedMsg, author: getViewerId(), timestamp: new Date().toISOString(), mentions: mentions.length > 0 ? mentions : undefined }, parentId);
  2975. ctx.redirect(`/forum/${encodeURIComponent(ctx.params.id)}`);
  2976. })
  2977. .post('/forum/:forumId/vote', koaBody(), async ctx => {
  2978. await forumModel.voteContent(ctx.request.body.target, parseInt(ctx.request.body.value, 10));
  2979. ctx.redirect(ctx.get('referer') || `/forum/${encodeURIComponent(ctx.params.forumId)}`);
  2980. })
  2981. .post('/forum/delete/:id', koaBody(), async ctx => {
  2982. const forum = await forumModel.getForumById(ctx.params.id).catch(() => null);
  2983. if (!forum || forum.author !== getViewerId()) { ctx.status = 403; ctx.body = 'Forbidden'; return; }
  2984. await forumModel.deleteForumById(ctx.params.id);
  2985. ctx.redirect('/forum');
  2986. })
  2987. .post('/legacy/export', koaBody(), async (ctx) => {
  2988. const pw = ctx.request.body.password;
  2989. if (!pw || pw.length < 32) return ctx.redirect('/legacy');
  2990. try {
  2991. ctx.body = { message: 'Data exported successfully!', file: await legacyModel.exportData({ password: pw }) };
  2992. ctx.redirect('/legacy');
  2993. } catch (error) { ctx.status = 500; ctx.body = { error: `Error: ${error.message}` }; ctx.redirect('/legacy'); }
  2994. })
  2995. .post('/legacy/import', koaBody({
  2996. multipart: true,
  2997. formidable: {
  2998. keepExtensions: true,
  2999. uploadDir: '/tmp',
  3000. }
  3001. }), async (ctx) => {
  3002. const uploadedFile = ctx.request.files?.uploadedFile, pw = ctx.request.body.importPassword;
  3003. if (!uploadedFile) { ctx.body = { error: 'No file uploaded' }; return ctx.redirect('/legacy'); }
  3004. if (!pw || pw.length < 32) { ctx.body = { error: 'Password is too short or missing.' }; return ctx.redirect('/legacy'); }
  3005. try {
  3006. await legacyModel.importData({ filePath: uploadedFile.filepath, password: pw });
  3007. ctx.body = { message: 'Data imported successfully!' };
  3008. ctx.redirect('/legacy');
  3009. } catch (error) { ctx.body = { error: error.message }; ctx.redirect('/legacy'); }
  3010. })
  3011. .post('/trending/:contentId/:category', async (ctx) => {
  3012. const { contentId, category } = ctx.params, voterId = SSBconfig?.keys?.id;
  3013. if ((await trendingModel.getMessageById(contentId))?.content?.opinions_inhabitants?.includes(voterId)) {
  3014. ctx.flash = { message: 'You have already opined.' }; return ctx.redirect('/trending');
  3015. }
  3016. await trendingModel.createVote(contentId, category); ctx.redirect('/trending');
  3017. })
  3018. .post('/opinions/:contentId/:category', async (ctx) => {
  3019. const { contentId, category } = ctx.params, voterId = SSBconfig?.keys?.id;
  3020. if ((await opinionsModel.getMessageById(contentId))?.content?.opinions_inhabitants?.includes(voterId)) {
  3021. ctx.flash = { message: 'You have already opined.' }; return ctx.redirect('/opinions');
  3022. }
  3023. await opinionsModel.createVote(contentId, category); ctx.redirect('/opinions');
  3024. })
  3025. .post('/agenda/discard/:itemId', async (ctx) => {
  3026. await agendaModel.discardItem(ctx.params.itemId); ctx.redirect('/agenda');
  3027. })
  3028. .post('/agenda/restore/:itemId', async (ctx) => {
  3029. await agendaModel.restoreItem(ctx.params.itemId); ctx.redirect('/agenda?filter=discarded');
  3030. })
  3031. .post("/feed/create", koaBody(), async (ctx) => {
  3032. const text = ctx.request.body?.text != null ? stripDangerousTags(String(ctx.request.body.text)) : "";
  3033. const mentions = await extractMentions(text);
  3034. await feedModel.createFeed(text, mentions);
  3035. ctx.redirect("/feed?filter=ALL&msg=feedPublished");
  3036. })
  3037. .post("/feed/opinions/:feedId/:category", async (ctx) => {
  3038. const { feedId, category } = ctx.params;
  3039. try {
  3040. await feedModel.addOpinion(feedId, category);
  3041. } catch { /* already voted or invalid — ignore */ }
  3042. ctx.redirect(ctx.get("Referer") || "/feed");
  3043. })
  3044. .post("/feed/refeed/:id", koaBody(), async (ctx) => {
  3045. try {
  3046. await feedModel.createRefeed(ctx.params.id);
  3047. } catch (e) {
  3048. if (e.message !== "Already refeeded") throw e;
  3049. }
  3050. ctx.redirect(ctx.get("Referer") || "/feed");
  3051. })
  3052. .post("/feed/:feedId/comments", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3053. const text = ctx.request.body?.text != null ? stripDangerousTags(String(ctx.request.body.text)) : "";
  3054. const imageMarkdown = ctx.request.files?.blob ? await handleBlobUpload(ctx, 'blob') : null;
  3055. const fullText = imageMarkdown ? (text ? text + '\n' : '') + imageMarkdown : text;
  3056. await feedModel.addComment(ctx.params.feedId, fullText);
  3057. ctx.redirect(`/feed/${encodeURIComponent(ctx.params.feedId)}`);
  3058. })
  3059. .post("/bookmarks/create", koaBody(), async (ctx) => {
  3060. if (!checkMod(ctx, 'bookmarksMod')) { ctx.redirect('/modules'); return; }
  3061. const b = ctx.request.body;
  3062. await bookmarksModel.createBookmark(stripDangerousTags(b.url), b.tags, stripDangerousTags(b.description), b.category, b.lastVisit);
  3063. ctx.redirect(safeReturnTo(ctx, '/bookmarks?filter=all', ['/bookmarks']));
  3064. })
  3065. .post("/bookmarks/update/:id", koaBody(), async (ctx) => {
  3066. if (!checkMod(ctx, 'bookmarksMod')) { ctx.redirect('/modules'); return; }
  3067. const b = ctx.request.body;
  3068. await bookmarksModel.updateBookmarkById(ctx.params.id, { url: stripDangerousTags(b.url), tags: b.tags, description: stripDangerousTags(b.description), category: b.category, lastVisit: b.lastVisit });
  3069. ctx.redirect(safeReturnTo(ctx, '/bookmarks?filter=mine', ['/bookmarks']));
  3070. })
  3071. .post("/bookmarks/delete/:id", koaBody(), async ctx => deleteAction(ctx, 'bookmarks'))
  3072. .post("/bookmarks/opinions/:bookmarkId/:category", koaBody(), async ctx => opinionAction(ctx, 'bookmarks', 'bookmarkId'))
  3073. .post("/bookmarks/favorites/add/:id", koaBody(), async ctx => favAction(ctx, 'bookmarks', 'add'))
  3074. .post("/bookmarks/favorites/remove/:id", koaBody(), async ctx => favAction(ctx, 'bookmarks', 'remove'))
  3075. .post("/bookmarks/:bookmarkId/comments", koaBodyMiddleware, async ctx => commentAction(ctx, 'bookmarks', 'bookmarkId'))
  3076. .post("/images/create", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3077. if (!checkMod(ctx, 'imagesMod')) { ctx.redirect('/modules'); return; }
  3078. const blob = await handleBlobUpload(ctx, 'image'), b = ctx.request.body;
  3079. await imagesModel.createImage(blob, b.tags, stripDangerousTags(b.title), stripDangerousTags(b.description), parseBool01(b.meme), stripDangerousTags(b.mapUrl || ""));
  3080. ctx.redirect(safeReturnTo(ctx, '/images?filter=all', ['/images']));
  3081. })
  3082. .post("/images/update/:id", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3083. if (!checkMod(ctx, 'imagesMod')) { ctx.redirect('/modules'); return; }
  3084. const b = ctx.request.body, blob = ctx.request.files?.image ? await handleBlobUpload(ctx, 'image') : null;
  3085. await imagesModel.updateImageById(ctx.params.id, blob, b.tags, stripDangerousTags(b.title), stripDangerousTags(b.description), parseBool01(b.meme), stripDangerousTags(b.mapUrl || ""));
  3086. ctx.redirect(safeReturnTo(ctx, '/images?filter=mine', ['/images']));
  3087. })
  3088. .post("/images/delete/:id", koaBody(), async ctx => deleteAction(ctx, 'images'))
  3089. .post("/images/opinions/:imageId/:category", koaBody(), async ctx => opinionAction(ctx, 'images', 'imageId'))
  3090. .post("/images/favorites/add/:id", koaBody(), async ctx => favAction(ctx, 'images', 'add'))
  3091. .post("/images/favorites/remove/:id", koaBody(), async ctx => favAction(ctx, 'images', 'remove'))
  3092. .post("/images/:imageId/comments", koaBodyMiddleware, async ctx => commentAction(ctx, 'images', 'imageId'))
  3093. .post("/maps/create", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3094. if (!checkMod(ctx, 'mapsMod')) { ctx.redirect('/modules'); return; }
  3095. const b = ctx.request.body;
  3096. if (b.tribeId) {
  3097. const t = await tribesModel.getTribeById(b.tribeId).catch(() => null);
  3098. if (!t || !t.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3099. }
  3100. const imageId = extractBlobId(await handleBlobUpload(ctx, 'image')) || "";
  3101. const newMap = await mapsModel.createMap(b.lat, b.lng, stripDangerousTags(b.description), b.mapType, b.tags, stripDangerousTags(b.title), b.tribeId || null, stripDangerousTags(b.markerLabel), imageId);
  3102. const redir = b.tribeId ? `/tribe/${encodeURIComponent(b.tribeId)}?section=maps` : safeReturnTo(ctx, '/maps?filter=all', ['/maps']);
  3103. ctx.redirect(redir);
  3104. })
  3105. .post("/maps/update/:id", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3106. if (!checkMod(ctx, 'mapsMod')) { ctx.redirect('/modules'); return; }
  3107. const target = await mapsModel.getMapById(ctx.params.id, getViewerId()).catch(() => null);
  3108. if (target && target.tribeId) {
  3109. const t = await tribesModel.getTribeById(target.tribeId).catch(() => null);
  3110. if (!t || !t.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3111. }
  3112. const b = ctx.request.body;
  3113. const imageId = ctx.request.files?.image ? extractBlobId(await handleBlobUpload(ctx, 'image')) || "" : "";
  3114. await mapsModel.updateMapById(ctx.params.id, b.lat, b.lng, stripDangerousTags(b.description), b.mapType, b.tags, stripDangerousTags(b.title), imageId || undefined);
  3115. ctx.redirect(safeReturnTo(ctx, '/maps?filter=mine', ['/maps']));
  3116. })
  3117. .post("/maps/delete/:id", koaBody(), async (ctx) => {
  3118. if (!checkMod(ctx, 'mapsMod')) { ctx.redirect('/modules'); return; }
  3119. const target = await mapsModel.getMapById(ctx.params.id, getViewerId()).catch(() => null);
  3120. if (target && target.tribeId) {
  3121. const t = await tribesModel.getTribeById(target.tribeId).catch(() => null);
  3122. if (!t || !t.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3123. }
  3124. await mapsModel.deleteMapById(ctx.params.id);
  3125. ctx.redirect(safeReturnTo(ctx, '/maps?filter=mine', ['/maps']));
  3126. })
  3127. .post("/maps/favorites/add/:id", koaBody(), async ctx => favAction(ctx, 'maps', 'add'))
  3128. .post("/maps/favorites/remove/:id", koaBody(), async ctx => favAction(ctx, 'maps', 'remove'))
  3129. .post("/maps/:mapId/marker", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3130. if (!checkMod(ctx, 'mapsMod')) { ctx.redirect('/modules'); return; }
  3131. const uid = getViewerId();
  3132. const mapItem = await mapsModel.getMapById(ctx.params.mapId, uid);
  3133. if (mapItem.tribeId) {
  3134. try {
  3135. const t = await tribesModel.getTribeById(mapItem.tribeId);
  3136. if (!t.members.includes(uid)) { ctx.status = 403; ctx.body = "Forbidden"; return; }
  3137. } catch { ctx.status = 403; ctx.body = "Forbidden"; return; }
  3138. }
  3139. const b = ctx.request.body;
  3140. const imageBlobId = extractBlobId(await handleBlobUpload(ctx, 'image')) || "";
  3141. await mapsModel.addMarker(ctx.params.mapId, b.mkLat, b.mkLng, stripDangerousTags(b.label), imageBlobId);
  3142. ctx.redirect(safeReturnTo(ctx, `/maps/${encodeURIComponent(ctx.params.mapId)}`, ['/maps']));
  3143. })
  3144. .post("/audios/create", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async ctx => mediaCreateAction(ctx, 'audios'))
  3145. .post("/audios/update/:id", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async ctx => mediaUpdateAction(ctx, 'audios'))
  3146. .post("/audios/delete/:id", koaBody(), async ctx => deleteAction(ctx, 'audios'))
  3147. .post("/audios/opinions/:audioId/:category", koaBody(), async ctx => opinionAction(ctx, 'audios', 'audioId'))
  3148. .post("/audios/favorites/add/:id", koaBody(), async ctx => favAction(ctx, 'audios', 'add'))
  3149. .post("/audios/favorites/remove/:id", koaBody(), async ctx => favAction(ctx, 'audios', 'remove'))
  3150. .post("/audios/:audioId/comments", koaBodyMiddleware, async ctx => commentAction(ctx, 'audios', 'audioId'))
  3151. .post("/torrents/create", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3152. if (!checkMod(ctx, 'torrentsMod')) { ctx.redirect('/modules'); return; }
  3153. const { tags, title, description, tribeId } = ctx.request.body;
  3154. const cleanTribeId = tribeId ? String(tribeId).trim() : null;
  3155. if (cleanTribeId) {
  3156. const t = await tribesModel.getTribeById(cleanTribeId).catch(() => null);
  3157. if (!t || !t.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3158. }
  3159. const blob = await handleBlobUpload(ctx, 'torrent');
  3160. const fileSize = ctx.request.files?.torrent?.size || 0;
  3161. await torrentsModel.createTorrent(blob, stripDangerousTags(tags), stripDangerousTags(title), stripDangerousTags(description), fileSize, cleanTribeId);
  3162. ctx.redirect(cleanTribeId ? `/tribe/${encodeURIComponent(cleanTribeId)}?section=torrents` : safeReturnTo(ctx, '/torrents?filter=all', ['/torrents']));
  3163. })
  3164. .post("/torrents/update/:id", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3165. if (!checkMod(ctx, 'torrentsMod')) { ctx.redirect('/modules'); return; }
  3166. const target = await torrentsModel.getTorrentById(ctx.params.id, getViewerId()).catch(() => null);
  3167. if (target && target.tribeId) {
  3168. const t = await tribesModel.getTribeById(target.tribeId).catch(() => null);
  3169. if (!t || !t.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3170. }
  3171. const { tags, title, description } = ctx.request.body;
  3172. const blob = ctx.request.files?.torrent ? await handleBlobUpload(ctx, 'torrent') : null;
  3173. await torrentsModel.updateTorrentById(ctx.params.id, blob, stripDangerousTags(tags), stripDangerousTags(title), stripDangerousTags(description));
  3174. ctx.redirect(safeReturnTo(ctx, '/torrents?filter=mine', ['/torrents']));
  3175. })
  3176. .post("/torrents/delete/:id", koaBody(), async ctx => {
  3177. const target = await torrentsModel.getTorrentById(ctx.params.id, getViewerId()).catch(() => null);
  3178. if (target && target.tribeId) {
  3179. const t = await tribesModel.getTribeById(target.tribeId).catch(() => null);
  3180. if (!t || !t.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3181. }
  3182. return deleteAction(ctx, 'torrents');
  3183. })
  3184. .post("/torrents/opinions/:torrentId/:category", koaBody(), async ctx => {
  3185. const target = await torrentsModel.getTorrentById(ctx.params.torrentId, getViewerId()).catch(() => null);
  3186. if (target && target.tribeId) {
  3187. const t = await tribesModel.getTribeById(target.tribeId).catch(() => null);
  3188. if (!t || !t.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3189. }
  3190. return opinionAction(ctx, 'torrents', 'torrentId');
  3191. })
  3192. .post("/torrents/favorites/add/:id", koaBody(), async ctx => favAction(ctx, 'torrents', 'add'))
  3193. .post("/torrents/favorites/remove/:id", koaBody(), async ctx => favAction(ctx, 'torrents', 'remove'))
  3194. .post("/torrents/:torrentId/comments", koaBodyMiddleware, async ctx => commentAction(ctx, 'torrents', 'torrentId'))
  3195. .post("/videos/create", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async ctx => mediaCreateAction(ctx, 'videos'))
  3196. .post("/videos/update/:id", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async ctx => mediaUpdateAction(ctx, 'videos'))
  3197. .post("/videos/delete/:id", koaBody(), async ctx => deleteAction(ctx, 'videos'))
  3198. .post("/videos/opinions/:videoId/:category", koaBody(), async ctx => opinionAction(ctx, 'videos', 'videoId'))
  3199. .post("/videos/favorites/add/:id", koaBody(), async ctx => favAction(ctx, 'videos', 'add'))
  3200. .post("/videos/favorites/remove/:id", koaBody(), async ctx => favAction(ctx, 'videos', 'remove'))
  3201. .post("/videos/:videoId/comments", koaBodyMiddleware, async ctx => commentAction(ctx, 'videos', 'videoId'))
  3202. .post("/documents/create", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3203. const docBlob = await handleBlobUpload(ctx, "document"), b = ctx.request.body;
  3204. await documentsModel.createDocument(docBlob, b.tags, stripDangerousTags(b.title), stripDangerousTags(b.description));
  3205. ctx.redirect(safeReturnTo(ctx, "/documents?filter=all", ["/documents"]));
  3206. })
  3207. .post("/documents/update/:id", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3208. const b = ctx.request.body, blob = ctx.request.files?.document ? await handleBlobUpload(ctx, "document") : null;
  3209. await documentsModel.updateDocumentById(ctx.params.id, blob, b.tags, stripDangerousTags(b.title), stripDangerousTags(b.description));
  3210. ctx.redirect(safeReturnTo(ctx, "/documents?filter=mine", ["/documents"]));
  3211. })
  3212. .post("/documents/delete/:id", koaBody(), async ctx => deleteAction(ctx, 'documents'))
  3213. .post("/documents/opinions/:documentId/:category", koaBody(), async ctx => opinionAction(ctx, 'documents', 'documentId'))
  3214. .post("/documents/favorites/add/:id", koaBody(), async ctx => favAction(ctx, 'documents', 'add'))
  3215. .post("/documents/favorites/remove/:id", koaBody(), async ctx => favAction(ctx, 'documents', 'remove'))
  3216. .post("/documents/:documentId/comments", koaBodyMiddleware, async ctx => commentAction(ctx, 'documents', 'documentId'))
  3217. .post('/cv/upload', koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async ctx => {
  3218. const photoUrl = await handleBlobUpload(ctx, 'image')
  3219. await cvModel.createCV(ctx.request.body, photoUrl)
  3220. ctx.redirect('/cv')
  3221. })
  3222. .post('/cv/update/:id', koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async ctx => {
  3223. const photoUrl = await handleBlobUpload(ctx, 'image')
  3224. await cvModel.updateCV(ctx.params.id, ctx.request.body, photoUrl)
  3225. ctx.redirect('/cv')
  3226. })
  3227. .post('/cv/delete/:id', async ctx => {
  3228. await cvModel.deleteCVById(ctx.params.id)
  3229. ctx.redirect('/cv')
  3230. })
  3231. .post('/cipher/encrypt', koaBody(), async (ctx) => {
  3232. const { text, password } = ctx.request.body;
  3233. if (password.length < 32) { ctx.body = { error: 'Password is too short or missing.' }; return ctx.redirect('/cipher'); }
  3234. const { encryptedText, iv } = cipherModel.encryptData(text, password);
  3235. ctx.body = await cipherView(encryptedText, "", iv, password);
  3236. })
  3237. .post('/cipher/decrypt', koaBody(), async (ctx) => {
  3238. const { encryptedText, password } = ctx.request.body;
  3239. if (password.length < 32) { ctx.body = { error: 'Password is too short or missing.' }; return ctx.redirect('/cipher'); }
  3240. ctx.body = await cipherView("", cipherModel.decryptData(encryptedText, password), "", password);
  3241. })
  3242. .post('/tribes/create', koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async ctx => {
  3243. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3244. const b = ctx.request.body;
  3245. if (tooLong(ctx, b.title, MAX_TITLE_LENGTH, 'Title') || tooLong(ctx, b.description, MAX_TEXT_LENGTH, 'Description')) return;
  3246. if (!['strict', 'open'].includes(b.inviteMode)) { ctx.redirect('/tribes'); return; }
  3247. const image = await handleBlobUpload(ctx, 'image');
  3248. const tribeRes = await tribesModel.createTribe(stripDangerousTags(b.title), stripDangerousTags(b.description), image, stripDangerousTags(b.location), b.tags, b.isLARP === 'true', b.isAnonymous === 'true', b.inviteMode, null, 'OPEN', stripDangerousTags(b.mapUrl));
  3249. try { if (tribeRes?.key) await parliamentModel.tribe.publishInitialTerm(tribeRes.key); } catch (e) { console.error('publishInitialTerm failed:', e); }
  3250. ctx.redirect('/tribes');
  3251. })
  3252. .post('/tribe/:id/subtribes/create', koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async ctx => {
  3253. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3254. const parentTribe = await tribesModel.getTribeById(ctx.params.id);
  3255. const viewerId = getViewerId();
  3256. const canCreate = parentTribe.inviteMode === 'open'
  3257. ? parentTribe.members.includes(viewerId)
  3258. : parentTribe.author === viewerId;
  3259. if (!canCreate) { ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=subtribes`); return; }
  3260. const b = ctx.request.body;
  3261. if (tooLong(ctx, b.title, MAX_TITLE_LENGTH, 'Title') || tooLong(ctx, b.description, MAX_TEXT_LENGTH, 'Description')) return;
  3262. const image = await handleBlobUpload(ctx, 'image');
  3263. const parentEffective = await tribesModel.getEffectiveStatus(ctx.params.id).catch(() => ({ isPrivate: false }));
  3264. const effectiveAnonymous = !!(parentEffective.isPrivate || parentTribe.isAnonymous);
  3265. await tribesModel.createTribe(stripDangerousTags(b.title), stripDangerousTags(b.description), image, stripDangerousTags(b.location), b.tags, false, effectiveAnonymous, b.inviteMode || 'open', ctx.params.id, 'OPEN', stripDangerousTags(b.mapUrl));
  3266. ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=subtribes`);
  3267. })
  3268. .post('/tribes/update/:id', koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async ctx => {
  3269. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3270. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3271. if (tribe.author !== getViewerId()) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3272. const b = ctx.request.body;
  3273. if (tooLong(ctx, b.title, MAX_TITLE_LENGTH, 'Title') || tooLong(ctx, b.description, MAX_TEXT_LENGTH, 'Description')) return;
  3274. if (b.inviteMode && !['strict', 'open'].includes(b.inviteMode)) { ctx.redirect('/tribes'); return; }
  3275. const tags = b.tags ? b.tags.split(',').map(t => t.trim()).filter(Boolean) : [];
  3276. const isSub = !!tribe.parentTribeId;
  3277. const updateFields = { title: stripDangerousTags(b.title), description: stripDangerousTags(b.description), image: await handleBlobUpload(ctx, 'image'), location: stripDangerousTags(b.location), tags, inviteMode: b.inviteMode || tribe.inviteMode, status: b.status || tribe.status || 'OPEN' };
  3278. if (isSub) {
  3279. updateFields.isLARP = false;
  3280. updateFields.isAnonymous = !!tribe.isAnonymous;
  3281. } else {
  3282. updateFields.isLARP = b.isLARP === 'true';
  3283. updateFields.isAnonymous = b.isAnonymous === 'true';
  3284. }
  3285. await tribesModel.updateTribeById(ctx.params.id, updateFields);
  3286. ctx.redirect('/tribes?filter=mine');
  3287. })
  3288. .post('/tribes/delete/:id', async ctx => {
  3289. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3290. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3291. if (tribe.author !== getViewerId()) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3292. await tribesModel.deleteTribeById(ctx.params.id)
  3293. ctx.redirect('/tribes?filter=mine')
  3294. })
  3295. .post('/tribes/generate-invite', koaBody(), async ctx => {
  3296. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3297. ctx.body = await renderInvitePage(await tribesModel.generateInvite(ctx.request.body.tribeId));
  3298. })
  3299. .post('/tribes/join-code', koaBody(), async ctx => {
  3300. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3301. await tribesModel.joinByInvite(ctx.request.body.inviteCode)
  3302. ctx.redirect('/tribes?filter=membership')
  3303. })
  3304. .post('/tribes/leave/:id', koaBody(), async ctx => {
  3305. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3306. await tribesModel.leaveTribe(ctx.params.id)
  3307. ctx.redirect('/tribes?filter=membership')
  3308. })
  3309. .post('/tribe/:id/message', koaBody(), async ctx => {
  3310. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3311. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3312. const uid = getViewerId();
  3313. if (!tribe.members.includes(uid)) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3314. if (tooLong(ctx, ctx.request.body.message, MAX_TEXT_LENGTH, 'Text')) return;
  3315. const message = stripDangerousTags((ctx.request.body.message || '').trim());
  3316. if (!message || message.length === 0 || message.length > 280) { ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=feed`); return; }
  3317. await tribesContentModel.create(tribe.id, 'feed', { description: await resolveMentionText(message) });
  3318. ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=feed&sent=1`);
  3319. })
  3320. .post('/tribe/:id/refeed/:msgId', koaBody(), async ctx => {
  3321. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3322. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3323. const uid = getViewerId();
  3324. if (!tribe.members.includes(uid)) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3325. await tribesContentModel.toggleRefeed(ctx.params.msgId);
  3326. ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=feed`);
  3327. })
  3328. .post('/tribe/:id/events/create', koaBody(), async ctx => {
  3329. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3330. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3331. if (!tribe.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3332. const b = ctx.request.body;
  3333. if (tooLong(ctx, b.title, MAX_TITLE_LENGTH, 'Title') || tooLong(ctx, b.description, MAX_TEXT_LENGTH, 'Description')) return;
  3334. if (b.date && b.date < new Date().toISOString().split('T')[0]) { ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=events&action=create`); return; }
  3335. await tribesContentModel.create(tribe.id, 'event', { title: stripDangerousTags(b.title), description: await resolveMentionText(stripDangerousTags(b.description)), date: b.date, location: stripDangerousTags(b.location), attendees: [getViewerId()] });
  3336. ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=events`);
  3337. })
  3338. .post('/tribe/:id/events/attend/:eventId', koaBody(), async ctx => {
  3339. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3340. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3341. if (!tribe.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3342. await tribesContentModel.toggleAttendee(ctx.params.eventId);
  3343. ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=events`);
  3344. })
  3345. .post('/tribe/:id/tasks/create', koaBody(), async ctx => {
  3346. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3347. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3348. if (!tribe.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3349. const b = ctx.request.body;
  3350. if (tooLong(ctx, b.title, MAX_TITLE_LENGTH, 'Title') || tooLong(ctx, b.description, MAX_TEXT_LENGTH, 'Description')) return;
  3351. if (b.deadline && b.deadline < new Date().toISOString().split('T')[0]) { ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=tasks&action=create`); return; }
  3352. await tribesContentModel.create(tribe.id, 'task', { title: stripDangerousTags(b.title), description: await resolveMentionText(stripDangerousTags(b.description)), priority: b.priority, deadline: b.deadline, assignees: [] });
  3353. ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=tasks`);
  3354. })
  3355. .post('/tribe/:id/tasks/assign/:taskId', koaBody(), async ctx => {
  3356. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3357. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3358. if (!tribe.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3359. await tribesContentModel.toggleAssignee(ctx.params.taskId);
  3360. ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=tasks`);
  3361. })
  3362. .post('/tribe/:id/tasks/status/:taskId', koaBody(), async ctx => {
  3363. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3364. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3365. if (!tribe.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3366. const item = await tribesContentModel.getById(ctx.params.taskId);
  3367. if (!item || item.author !== getViewerId()) { ctx.status = 403; ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=tasks`); return; }
  3368. await tribesContentModel.updateStatus(ctx.params.taskId, ctx.request.body.status);
  3369. ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=tasks`);
  3370. })
  3371. .post('/tribe/:id/votations/create', koaBody(), async ctx => {
  3372. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3373. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3374. if (!tribe.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3375. const b = ctx.request.body;
  3376. if (tooLong(ctx, b.title, MAX_TITLE_LENGTH, 'Title') || tooLong(ctx, b.description, MAX_TEXT_LENGTH, 'Description')) return;
  3377. if (b.deadline && b.deadline < new Date().toISOString().split('T')[0]) { ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=votations&action=create`); return; }
  3378. const options = [b.option1, b.option2, b.option3, b.option4].filter(Boolean).map(o => stripDangerousTags(o));
  3379. await tribesContentModel.create(tribe.id, 'votation', { title: stripDangerousTags(b.title), description: await resolveMentionText(stripDangerousTags(b.description)), deadline: b.deadline, options, votes: {} });
  3380. ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=votations`);
  3381. })
  3382. .post('/tribe/:id/votations/:voteId/vote', koaBody(), async ctx => {
  3383. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3384. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3385. if (!tribe.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3386. await tribesContentModel.castVote(ctx.params.voteId, parseInt(ctx.request.body.optionIndex, 10));
  3387. ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=votations`);
  3388. })
  3389. .post('/tribe/:id/votations/close/:voteId', koaBody(), async ctx => {
  3390. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3391. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3392. if (!tribe.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3393. const votation = await tribesContentModel.getById(ctx.params.voteId);
  3394. if (!votation || votation.author !== getViewerId()) { ctx.status = 403; ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=votations`); return; }
  3395. await tribesContentModel.updateStatus(ctx.params.voteId, 'CLOSED');
  3396. ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=votations`);
  3397. })
  3398. .post('/tribe/:id/forum/create', koaBody(), async ctx => {
  3399. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3400. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3401. if (!tribe.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3402. const b = ctx.request.body;
  3403. if (tooLong(ctx, b.title, MAX_TITLE_LENGTH, 'Title') || tooLong(ctx, b.description, MAX_TEXT_LENGTH, 'Description')) return;
  3404. await tribesContentModel.create(tribe.id, 'forum', { title: stripDangerousTags(b.title), description: await resolveMentionText(stripDangerousTags(b.description)), category: b.category });
  3405. ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=forum`);
  3406. })
  3407. .post('/tribe/:id/forum/:forumId/reply', koaBody(), async ctx => {
  3408. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3409. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3410. if (!tribe.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3411. const b = ctx.request.body;
  3412. if (tooLong(ctx, b.description, MAX_TEXT_LENGTH, 'Description')) return;
  3413. await tribesContentModel.create(tribe.id, 'forum-reply', { description: await resolveMentionText(stripDangerousTags(b.description)), parentId: ctx.params.forumId });
  3414. ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=forum&thread=${encodeURIComponent(ctx.params.forumId)}`);
  3415. })
  3416. .post('/tribe/:id/forum/:forumId/refeed', koaBody(), async ctx => {
  3417. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3418. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3419. const uid = getViewerId();
  3420. if (!tribe.members.includes(uid)) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3421. await tribesContentModel.toggleRefeed(ctx.params.forumId);
  3422. const thread = ctx.query.thread || '';
  3423. ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=forum${thread ? '&thread=' + encodeURIComponent(thread) : ''}`);
  3424. })
  3425. .post('/tribe/:id/media/upload', koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async ctx => {
  3426. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3427. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3428. if (!tribe.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3429. const b = ctx.request.body;
  3430. if (tooLong(ctx, b.title, MAX_TITLE_LENGTH, 'Title') || tooLong(ctx, b.description, MAX_TEXT_LENGTH, 'Description')) return;
  3431. const returnSection = b.returnSection || 'media';
  3432. const mediaType = b.mediaType || 'image';
  3433. let blobRef = null;
  3434. if (mediaType === 'bookmark') {
  3435. const url = stripDangerousTags(b.url || '');
  3436. await tribesContentModel.create(tribe.id, 'media', { title: stripDangerousTags(b.title), description: stripDangerousTags(b.description), mediaType: 'bookmark', url });
  3437. } else {
  3438. const blobMarkdownMedia = await handleBlobUpload(ctx, 'media');
  3439. blobRef = blobMarkdownMedia ? ((blobMarkdownMedia.match(/\((&[^)]+)\)/) || [])[1] || blobMarkdownMedia) : null;
  3440. await tribesContentModel.create(tribe.id, 'media', { title: stripDangerousTags(b.title), description: stripDangerousTags(b.description), mediaType, image: blobRef });
  3441. }
  3442. ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=${returnSection}`);
  3443. })
  3444. .post('/tribe/:id/content/delete/:contentId', koaBody(), async ctx => {
  3445. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3446. const tribeRedirect = `/tribe/${encodeURIComponent(ctx.params.id)}`;
  3447. const item = await tribesContentModel.getById(ctx.params.contentId);
  3448. if (!item || item.author !== getViewerId() || item.tribeId !== ctx.params.id) { ctx.status = 403; ctx.redirect(tribeRedirect); return; }
  3449. await tribesContentModel.deleteById(ctx.params.contentId);
  3450. ctx.redirect(tribeRedirect);
  3451. })
  3452. .post('/tribe/:id/content/:contentId/opinion/:category', koaBody(), async ctx => {
  3453. if (!checkMod(ctx, 'tribesMod')) { ctx.redirect('/modules'); return; }
  3454. const tribe = await tribesModel.getTribeById(ctx.params.id);
  3455. if (!tribe.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3456. const item = await tribesContentModel.getById(ctx.params.contentId);
  3457. if (!item || item.tribeId !== ctx.params.id) { ctx.status = 404; ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=opinions`); return; }
  3458. try {
  3459. await tribesContentModel.castOpinion(ctx.params.contentId, ctx.params.category);
  3460. } catch (_) {}
  3461. ctx.redirect(`/tribe/${encodeURIComponent(ctx.params.id)}?section=opinions`);
  3462. })
  3463. .post('/panic/remove', koaBody(), async (ctx) => {
  3464. const { exec } = require('child_process');
  3465. try {
  3466. await panicmodeModel.removeSSB();
  3467. ctx.body = { message: 'Your blockchain has been succesfully deleted!' };
  3468. exec('pkill -f "node SSB_server.js start"');
  3469. setTimeout(() => process.exit(0), 1000);
  3470. } catch (error) { ctx.body = { error: 'Error deleting your blockchain: ' + error.message }; }
  3471. })
  3472. .post('/export/create', async (ctx) => {
  3473. try {
  3474. const outputPath = path.join(os.homedir(), 'ssb_exported.zip');
  3475. await exportmodeModel.exportSSB(outputPath);
  3476. ctx.set('Content-Type', 'application/zip');
  3477. ctx.set('Content-Disposition', `attachment; filename=ssb_exported.zip`);
  3478. ctx.body = fs.createReadStream(outputPath);
  3479. ctx.res.on('finish', () => fs.unlinkSync(outputPath));
  3480. } catch (error) { ctx.body = { error: 'Error exporting your blockchain: ' + error.message }; }
  3481. })
  3482. .post('/tasks/create', koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async ctx => {
  3483. const b = ctx.request.body;
  3484. const imageMarkdown = ctx.request.files?.image ? await handleBlobUpload(ctx, 'image') : null;
  3485. let desc = stripDangerousTags(b.description);
  3486. if (imageMarkdown) desc = (desc ? desc + '\n' : '') + imageMarkdown;
  3487. await tasksModel.createTask(stripDangerousTags(b.title), desc, b.startTime, b.endTime, b.priority, stripDangerousTags(b.location), b.tags, b.isPublic);
  3488. ctx.redirect(safeReturnTo(ctx, '/tasks?filter=mine', ['/tasks']));
  3489. })
  3490. .post('/tasks/update/:id', koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async ctx => {
  3491. const b = ctx.request.body, tags = Array.isArray(b.tags) ? b.tags.filter(Boolean) : (typeof b.tags === 'string' ? b.tags.split(',').map(t => t.trim()).filter(Boolean) : []);
  3492. const imageMarkdown = ctx.request.files?.image ? await handleBlobUpload(ctx, 'image') : null;
  3493. let desc = stripDangerousTags(b.description);
  3494. if (imageMarkdown) desc = (desc ? desc + '\n' : '') + imageMarkdown;
  3495. await tasksModel.updateTaskById(ctx.params.id, { title: stripDangerousTags(b.title), description: desc, startTime: b.startTime, endTime: b.endTime, priority: b.priority, location: stripDangerousTags(b.location), tags, isPublic: b.isPublic });
  3496. ctx.redirect(safeReturnTo(ctx, '/tasks?filter=mine', ['/tasks']));
  3497. })
  3498. .post('/tasks/assign/:id', koaBody(), async ctx => {
  3499. await tasksModel.toggleAssignee(ctx.params.id);
  3500. ctx.redirect(safeReturnTo(ctx, '/tasks', ['/tasks']));
  3501. })
  3502. .post('/tasks/delete/:id', koaBody(), async ctx => {
  3503. await tasksModel.deleteTaskById(ctx.params.id);
  3504. ctx.redirect(safeReturnTo(ctx, '/tasks?filter=mine', ['/tasks']));
  3505. })
  3506. .post('/tasks/status/:id', koaBody(), async ctx => {
  3507. await tasksModel.updateTaskStatus(ctx.params.id, ctx.request.body.status);
  3508. ctx.redirect(safeReturnTo(ctx, '/tasks?filter=mine', ['/tasks']));
  3509. })
  3510. .post('/tasks/:taskId/comments', koaBodyMiddleware, async ctx => commentAction(ctx, 'tasks', 'taskId'))
  3511. .post('/reports/create', koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async ctx => {
  3512. const b = ctx.request.body, image = await handleBlobUpload(ctx, 'image');
  3513. await reportsModel.createReport(stripDangerousTags(b.title), stripDangerousTags(b.description), b.category, image, b.tags, b.severity, {
  3514. stepsToReproduce: stripDangerousTags(b.stepsToReproduce), expectedBehavior: stripDangerousTags(b.expectedBehavior), actualBehavior: stripDangerousTags(b.actualBehavior), environment: stripDangerousTags(b.environment), reproduceRate: b.reproduceRate,
  3515. problemStatement: stripDangerousTags(b.problemStatement), userStory: stripDangerousTags(b.userStory), acceptanceCriteria: stripDangerousTags(b.acceptanceCriteria),
  3516. whatHappened: stripDangerousTags(b.whatHappened), reportedUser: b.reportedUser, evidenceLinks: stripDangerousTags(b.evidenceLinks),
  3517. contentLocation: stripDangerousTags(b.contentLocation), whyInappropriate: stripDangerousTags(b.whyInappropriate), requestedAction: stripDangerousTags(b.requestedAction)
  3518. });
  3519. ctx.redirect('/reports');
  3520. })
  3521. .post('/reports/update/:id', koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async ctx => {
  3522. const b = ctx.request.body, image = await handleBlobUpload(ctx, 'image');
  3523. await reportsModel.updateReportById(ctx.params.id, {
  3524. title: stripDangerousTags(b.title), description: stripDangerousTags(b.description), category: b.category, image, tags: b.tags, severity: b.severity,
  3525. template: {
  3526. stepsToReproduce: stripDangerousTags(b.stepsToReproduce), expectedBehavior: stripDangerousTags(b.expectedBehavior), actualBehavior: stripDangerousTags(b.actualBehavior), environment: stripDangerousTags(b.environment), reproduceRate: b.reproduceRate,
  3527. problemStatement: stripDangerousTags(b.problemStatement), userStory: stripDangerousTags(b.userStory), acceptanceCriteria: stripDangerousTags(b.acceptanceCriteria),
  3528. whatHappened: stripDangerousTags(b.whatHappened), reportedUser: stripDangerousTags(b.reportedUser), evidenceLinks: stripDangerousTags(b.evidenceLinks),
  3529. contentLocation: stripDangerousTags(b.contentLocation), whyInappropriate: stripDangerousTags(b.whyInappropriate), requestedAction: stripDangerousTags(b.requestedAction)
  3530. }
  3531. });
  3532. ctx.redirect('/reports?filter=mine');
  3533. })
  3534. .post('/reports/delete/:id', async ctx => {
  3535. await reportsModel.deleteReportById(ctx.params.id);
  3536. ctx.redirect('/reports?filter=mine');
  3537. })
  3538. .post('/reports/confirm/:id', async ctx => {
  3539. await reportsModel.confirmReportById(ctx.params.id);
  3540. ctx.redirect('/reports');
  3541. })
  3542. .post('/reports/status/:id', koaBody(), async ctx => {
  3543. await reportsModel.updateReportById(ctx.params.id, { status: ctx.request.body.status });
  3544. ctx.redirect('/reports?filter=mine');
  3545. })
  3546. .post('/reports/:reportId/comments', koaBodyMiddleware, async ctx => commentAction(ctx, 'reports', 'reportId'))
  3547. .post('/events/create', koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3548. const b = ctx.request.body;
  3549. const imageMarkdown = ctx.request.files?.image ? await handleBlobUpload(ctx, 'image') : null;
  3550. let desc = stripDangerousTags(b.description);
  3551. if (imageMarkdown) desc = (desc ? desc + '\n' : '') + imageMarkdown;
  3552. await eventsModel.createEvent(stripDangerousTags(b.title), desc, b.date, stripDangerousTags(b.location), b.price, b.url, b.attendees || [], b.tags, b.isPublic, stripDangerousTags(b.mapUrl));
  3553. ctx.redirect(safeReturnTo(ctx, '/events?filter=mine', ['/events']));
  3554. })
  3555. .post('/events/update/:id', koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3556. const b = ctx.request.body, existing = await eventsModel.getEventById(ctx.params.id);
  3557. const imageMarkdown = ctx.request.files?.image ? await handleBlobUpload(ctx, 'image') : null;
  3558. let desc = stripDangerousTags(b.description);
  3559. if (imageMarkdown) desc = (desc ? desc + '\n' : '') + imageMarkdown;
  3560. await eventsModel.updateEventById(ctx.params.id, { title: stripDangerousTags(b.title), description: desc, date: b.date, location: stripDangerousTags(b.location), price: b.price, url: b.url, attendees: b.attendees, tags: b.tags, isPublic: b.isPublic, createdAt: existing.createdAt, organizer: existing.organizer, mapUrl: stripDangerousTags(b.mapUrl) });
  3561. ctx.redirect(safeReturnTo(ctx, '/events?filter=mine', ['/events']));
  3562. })
  3563. .post('/events/attend/:id', koaBody(), async ctx => {
  3564. await eventsModel.toggleAttendee(ctx.params.id);
  3565. ctx.redirect(safeReturnTo(ctx, '/events', ['/events']));
  3566. })
  3567. .post('/events/delete/:id', koaBody(), async ctx => {
  3568. await eventsModel.deleteEventById(ctx.params.id);
  3569. ctx.redirect(safeReturnTo(ctx, '/events?filter=mine', ['/events']));
  3570. })
  3571. .post('/events/:eventId/comments', koaBodyMiddleware, async ctx => commentAction(ctx, 'events', 'eventId'))
  3572. .post('/votes/create', koaBody(), async ctx => {
  3573. const b = ctx.request.body, defaultOptions = ['YES', 'NO', 'ABSTENTION', 'CONFUSED', 'FOLLOW_MAJORITY', 'NOT_INTERESTED'];
  3574. const parsedOptions = b.options ? b.options.split(',').map(o => o.trim()).filter(Boolean) : defaultOptions;
  3575. await votesModel.createVote(stripDangerousTags(b.question), b.deadline, parsedOptions, String(b.tags || '').split(',').map(t => t.trim()).filter(Boolean));
  3576. ctx.redirect(safeReturnTo(ctx, '/votes?filter=mine', ['/votes']));
  3577. })
  3578. .post('/votes/update/:id', koaBody(), async ctx => {
  3579. const b = ctx.request.body, parsedOptions = b.options ? b.options.split(',').map(o => o.trim()).filter(Boolean) : undefined;
  3580. await votesModel.updateVoteById(ctx.params.id, { question: stripDangerousTags(b.question), deadline: b.deadline, options: parsedOptions, tags: b.tags ? b.tags.split(',').map(t => t.trim()).filter(Boolean) : [] });
  3581. ctx.redirect(safeReturnTo(ctx, '/votes?filter=mine', ['/votes']));
  3582. })
  3583. .post('/votes/delete/:id', koaBody(), async ctx => {
  3584. await votesModel.deleteVoteById(ctx.params.id);
  3585. ctx.redirect(safeReturnTo(ctx, '/votes?filter=mine', ['/votes']));
  3586. })
  3587. .post('/votes/vote/:id', koaBody(), async ctx => {
  3588. await votesModel.voteOnVote(ctx.params.id, ctx.request.body.choice);
  3589. ctx.redirect(safeReturnTo(ctx, '/votes?filter=open', ['/votes']));
  3590. })
  3591. .post('/votes/opinions/:voteId/:category', koaBody(), async ctx => {
  3592. try { await votesModel.createOpinion(ctx.params.voteId, ctx.params.category); }
  3593. catch (e) { if (!/already/i.test(String(e?.message || ''))) throw e; ctx.flash = { message: "You have already opined." }; }
  3594. ctx.redirect(safeReturnTo(ctx, '/votes', ['/votes']));
  3595. })
  3596. .post('/votes/:voteId/comments', koaBodyMiddleware, async ctx => commentAction(ctx, 'votes', 'voteId'))
  3597. .post('/parliament/candidatures/propose', koaBody(), async (ctx) => {
  3598. const b = ctx.request.body || {}, id = String(b.candidateId || '').trim(), m = String(b.method || '').trim().toUpperCase();
  3599. if (!id) ctx.throw(400, 'Candidate is required.');
  3600. if (!new Set(['DEMOCRACY','MAJORITY','MINORITY','DICTATORSHIP','KARMATOCRACY']).has(m)) ctx.throw(400, 'Invalid method.');
  3601. await parliamentModel.proposeCandidature({ candidateId: id, method: m }).catch(e => ctx.throw(400, String(e?.message || e)));
  3602. ctx.redirect('/parliament?filter=candidatures');
  3603. })
  3604. .post('/tribe/:id/governance/publish-candidature', koaBody(), async (ctx) => {
  3605. const tribeId = ctx.params.id;
  3606. const uid = getViewerId();
  3607. const tribe = await tribesModel.getTribeById(tribeId).catch(() => null);
  3608. if (!tribe) ctx.throw(404, 'Tribe not found');
  3609. if (tribe.parentTribeId) ctx.throw(400, 'Sub-tribes have no governance');
  3610. const isCreator = tribe.author === uid;
  3611. const isMember = Array.isArray(tribe.members) && tribe.members.includes(uid);
  3612. if (!isCreator && !isMember) ctx.throw(403, 'Not a tribe member');
  3613. const globalTerm = await parliamentModel.getCurrentTerm().catch(() => null);
  3614. const already = await parliamentModel.tribe.hasCandidatureInGlobalCycle(tribeId, globalTerm?.startAt).catch(() => false);
  3615. if (already) ctx.throw(400, 'This tribe already has an open candidature in the current global parliament cycle.');
  3616. const term = await parliamentModel.tribe.getCurrentTerm(tribeId).catch(() => null);
  3617. const rawMethod = (term?.method && String(term.method).toUpperCase()) || 'DEMOCRACY';
  3618. const method = rawMethod === 'ANARCHY' ? 'DEMOCRACY' : rawMethod;
  3619. await parliamentModel.proposeCandidature({ candidateId: tribeId, method }).catch(e => ctx.throw(400, String(e?.message || e)));
  3620. ctx.redirect('/parliament?filter=candidatures');
  3621. })
  3622. .post('/tribe/:id/governance/candidature/propose', koaBody(), async (ctx) => {
  3623. const tribeId = ctx.params.id;
  3624. const uid = getViewerId();
  3625. const tribe = await tribesModel.getTribeById(tribeId).catch(() => null);
  3626. if (!tribe) ctx.throw(404, 'Tribe not found');
  3627. if (tribe.parentTribeId) ctx.throw(400, 'Sub-tribes have no governance');
  3628. const isCreator = tribe.author === uid;
  3629. const isMember = Array.isArray(tribe.members) && tribe.members.includes(uid);
  3630. if (!isCreator && !isMember) ctx.throw(403, 'Not a tribe member');
  3631. const b = ctx.request.body || {};
  3632. const candidateId = String(b.candidateId || '').trim();
  3633. const method = String(b.method || '').trim().toUpperCase();
  3634. if (!candidateId) ctx.throw(400, 'Candidate required');
  3635. await parliamentModel.tribe.publishTribeCandidature({ tribeId, candidateId, method }).catch(e => ctx.throw(400, String(e?.message || e)));
  3636. ctx.redirect(`/tribe/${encodeURIComponent(tribeId)}?section=governance&filter=candidatures`);
  3637. })
  3638. .post('/tribe/:id/governance/candidature/vote', koaBody(), async (ctx) => {
  3639. const tribeId = ctx.params.id;
  3640. const uid = getViewerId();
  3641. const tribe = await tribesModel.getTribeById(tribeId).catch(() => null);
  3642. if (!tribe) ctx.throw(404, 'Tribe not found');
  3643. if (tribe.parentTribeId) ctx.throw(400, 'Sub-tribes have no governance');
  3644. const isCreator = tribe.author === uid;
  3645. const isMember = Array.isArray(tribe.members) && tribe.members.includes(uid);
  3646. if (!isCreator && !isMember) ctx.throw(403, 'Not a tribe member');
  3647. const candidatureId = String(ctx.request.body?.candidatureId || '').trim();
  3648. if (!candidatureId) ctx.throw(400, 'Missing candidatureId');
  3649. await parliamentModel.tribe.voteTribeCandidature({ tribeId, candidatureId }).catch(e => ctx.throw(400, String(e?.message || e)));
  3650. ctx.redirect(`/tribe/${encodeURIComponent(tribeId)}?section=governance&filter=candidatures`);
  3651. })
  3652. .post('/tribe/:id/governance/rule/add', koaBody(), async (ctx) => {
  3653. const tribeId = ctx.params.id;
  3654. const uid = getViewerId();
  3655. const tribe = await tribesModel.getTribeById(tribeId).catch(() => null);
  3656. if (!tribe) ctx.throw(404, 'Tribe not found');
  3657. if (tribe.parentTribeId) ctx.throw(400, 'Sub-tribes have no governance');
  3658. if (tribe.author !== uid) ctx.throw(403, 'Only tribe creator can add rules');
  3659. const b = ctx.request.body || {};
  3660. await parliamentModel.tribe.publishTribeRule({ tribeId, title: stripDangerousTags(String(b.title || '')), body: stripDangerousTags(String(b.body || '')) }).catch(e => ctx.throw(400, String(e?.message || e)));
  3661. ctx.redirect(`/tribe/${encodeURIComponent(tribeId)}?section=governance&filter=rules`);
  3662. })
  3663. .post('/tribe/:id/governance/rule/delete', koaBody(), async (ctx) => {
  3664. const tribeId = ctx.params.id;
  3665. const uid = getViewerId();
  3666. const tribe = await tribesModel.getTribeById(tribeId).catch(() => null);
  3667. if (!tribe) ctx.throw(404, 'Tribe not found');
  3668. if (tribe.parentTribeId) ctx.throw(400, 'Sub-tribes have no governance');
  3669. if (tribe.author !== uid) ctx.throw(403, 'Only tribe creator can delete rules');
  3670. const ruleId = String(ctx.request.body?.ruleId || '').trim();
  3671. if (!ruleId) ctx.throw(400, 'Missing ruleId');
  3672. await parliamentModel.tribe.deleteTribeRule(ruleId).catch(e => ctx.throw(400, String(e?.message || e)));
  3673. ctx.redirect(`/tribe/${encodeURIComponent(tribeId)}?section=governance&filter=rules`);
  3674. })
  3675. .post('/parliament/candidatures/:id/vote', koaBody(), async (ctx) => {
  3676. await parliamentModel.voteCandidature(ctx.params.id).catch(e => ctx.throw(400, String(e?.message || e)));
  3677. ctx.redirect('/parliament?filter=candidatures');
  3678. })
  3679. .post('/parliament/proposals/create', koaBody(), async (ctx) => {
  3680. const b = ctx.request.body || {}, t = String(b.title || '').trim(), d = String(b.description || '').trim();
  3681. if (!t) ctx.throw(400, 'Title is required.');
  3682. if (d.length > 1000) ctx.throw(400, 'Description must be ≤ 1000 chars.');
  3683. await parliamentModel.createProposal({ title: stripDangerousTags(t), description: stripDangerousTags(d) }).catch(e => ctx.throw(400, String(e?.message || e)));
  3684. ctx.redirect('/parliament?filter=proposals');
  3685. })
  3686. .post('/parliament/proposals/close/:id', koaBody(), async (ctx) => {
  3687. const canClose = await parliamentModel.canPropose();
  3688. if (!canClose) { ctx.status = 403; ctx.body = 'Forbidden'; return; }
  3689. await parliamentModel.closeProposal(ctx.params.id).catch(e => ctx.throw(400, String(e?.message || e)));
  3690. ctx.redirect('/parliament?filter=proposals');
  3691. })
  3692. .post('/parliament/resolve', koaBody(), async (ctx) => {
  3693. await ensureTerm();
  3694. ctx.redirect('/parliament?filter=government');
  3695. })
  3696. .post('/parliament/revocations/create', koaBody(), async (ctx) => {
  3697. const b = ctx.request.body || {}, rawLawId = Array.isArray(b.lawId) ? b.lawId[0] : (b.lawId ?? b['lawId[]'] ?? b.law_id ?? '');
  3698. const lawId = String(rawLawId || '').trim();
  3699. if (!lawId) ctx.throw(400, 'Law required');
  3700. await parliamentModel.createRevocation({ lawId, title: b.title, reasons: b.reasons });
  3701. ctx.redirect('/parliament?filter=revocations');
  3702. })
  3703. .post('/courts/cases/create', koaBody(), async (ctx) => {
  3704. const b = ctx.request.body || {}, titleSuffix = String(b.titleSuffix || '').trim(), titlePreset = String(b.titlePreset || '').trim();
  3705. const respondent = String(b.respondentId || '').trim(), method = String(b.method || '').trim().toUpperCase();
  3706. if (!titleSuffix && !titlePreset) { ctx.flash = { message: 'Title is required.' }; return ctx.redirect('/courts?filter=cases'); }
  3707. if (!respondent) { ctx.flash = { message: 'Accused / Respondent is required.' }; return ctx.redirect('/courts?filter=cases'); }
  3708. if (!/^@[A-Za-z0-9+/]+=*\.ed25519$/.test(respondent)) { ctx.flash = { message: 'Invalid respondent ID. Must be a valid SSB ID (@...ed25519).' }; return ctx.redirect('/courts?filter=cases'); }
  3709. if (!new Set(['JUDGE','DICTATOR','POPULAR','MEDIATION','KARMATOCRACY']).has(method)) { ctx.flash = { message: 'Invalid resolution method.' }; return ctx.redirect('/courts?filter=cases'); }
  3710. try { await courtsModel.openCase({ titleBase: [titlePreset, titleSuffix].filter(Boolean).join(' - '), respondentInput: respondent, method }); }
  3711. catch (e) { ctx.flash = { message: String(e?.message || e) }; }
  3712. ctx.redirect('/courts?filter=mycases');
  3713. })
  3714. .post('/courts/cases/:id/evidence/add', koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3715. const caseId = ctx.params.id, b = ctx.request.body || {};
  3716. if (!caseId) { ctx.flash = { message: 'Case not found.' }; return ctx.redirect('/courts?filter=cases'); }
  3717. try { await courtsModel.addEvidence({ caseId, text: stripDangerousTags(String(b.text || '')), link: String(b.link || ''), imageMarkdown: ctx.request.files?.image ? await handleBlobUpload(ctx, 'image') : null }); }
  3718. catch (e) { ctx.flash = { message: String(e?.message || e) }; }
  3719. ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`);
  3720. })
  3721. .post('/courts/cases/:id/answer', koaBody(), async (ctx) => {
  3722. const caseId = ctx.params.id, b = ctx.request.body || {}, answer = String(b.answer || ''), stance = String(b.stance || '').toUpperCase();
  3723. if (!caseId) { ctx.flash = { message: 'Case not found.' }; return ctx.redirect('/courts?filter=cases'); }
  3724. if (!answer) { ctx.flash = { message: 'Response brief is required.' }; return ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`); }
  3725. if (!new Set(['DENY','ADMIT','PARTIAL']).has(stance)) { ctx.flash = { message: 'Invalid stance.' }; return ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`); }
  3726. try { await courtsModel.answerCase({ caseId, stance, text: stripDangerousTags(answer) }); } catch (e) { ctx.flash = { message: String(e?.message || e) }; }
  3727. ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`);
  3728. })
  3729. .post('/courts/cases/:id/decide', koaBody(), async (ctx) => {
  3730. const caseId = ctx.params.id, b = ctx.request.body || {}, result = String(b.outcome || '').trim(), orders = String(b.orders || '');
  3731. if (!caseId) { ctx.flash = { message: 'Case not found.' }; return ctx.redirect('/courts?filter=cases'); }
  3732. if (!result) { ctx.flash = { message: 'Result is required.' }; return ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`); }
  3733. try { await courtsModel.issueVerdict({ caseId, result, orders }); } catch (e) { ctx.flash = { message: String(e?.message || e) }; }
  3734. ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`);
  3735. })
  3736. .post('/courts/cases/:id/settlements/propose', koaBody(), async (ctx) => {
  3737. const caseId = ctx.params.id, terms = String(ctx.request.body?.terms || '');
  3738. if (!caseId) { ctx.flash = { message: 'Case not found.' }; return ctx.redirect('/courts?filter=cases'); }
  3739. if (!terms) { ctx.flash = { message: 'Terms are required.' }; return ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`); }
  3740. try { await courtsModel.proposeSettlement({ caseId, terms }); } catch (e) { ctx.flash = { message: String(e?.message || e) }; }
  3741. ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`);
  3742. })
  3743. .post('/courts/cases/:id/settlements/accept', koaBody(), async (ctx) => {
  3744. const caseId = ctx.params.id;
  3745. if (!caseId) { ctx.flash = { message: 'Case not found.' }; return ctx.redirect('/courts?filter=cases'); }
  3746. try { await courtsModel.acceptSettlement({ caseId }); } catch (e) { ctx.flash = { message: String(e?.message || e) }; }
  3747. ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`);
  3748. })
  3749. .post('/courts/cases/:id/mediators/accuser', koaBody(), async (ctx) => {
  3750. const caseId = ctx.params.id, mediators = String(ctx.request.body?.mediators || '').split(',').map(s => s.trim()).filter(Boolean);
  3751. const uid = ctx.state?.user?.id;
  3752. if (!caseId) { ctx.flash = { message: 'Case not found.' }; return ctx.redirect('/courts?filter=cases'); }
  3753. if (!mediators.length) { ctx.flash = { message: 'At least one mediator is required.' }; return ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`); }
  3754. if (uid && mediators.includes(uid)) { ctx.flash = { message: 'You cannot appoint yourself as mediator.' }; return ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`); }
  3755. try { await courtsModel.setMediators({ caseId, side: 'accuser', mediators }); } catch (e) { ctx.flash = { message: String(e?.message || e) }; }
  3756. ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`);
  3757. })
  3758. .post('/courts/cases/:id/mediators/respondent', koaBody(), async (ctx) => {
  3759. const caseId = ctx.params.id, mediators = String(ctx.request.body?.mediators || '').split(',').map(s => s.trim()).filter(Boolean);
  3760. const uid = ctx.state?.user?.id;
  3761. if (!caseId) { ctx.flash = { message: 'Case not found.' }; return ctx.redirect('/courts?filter=cases'); }
  3762. if (!mediators.length) { ctx.flash = { message: 'At least one mediator is required.' }; return ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`); }
  3763. if (uid && mediators.includes(uid)) { ctx.flash = { message: 'You cannot appoint yourself as mediator.' }; return ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`); }
  3764. try { await courtsModel.setMediators({ caseId, side: 'respondent', mediators }); } catch (e) { ctx.flash = { message: String(e?.message || e) }; }
  3765. ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`);
  3766. })
  3767. .post('/courts/cases/:id/judge', koaBody(), async (ctx) => {
  3768. const caseId = ctx.params.id, judgeId = String(ctx.request.body?.judgeId || '').trim(), uid = ctx.state?.user?.id;
  3769. if (!caseId) { ctx.flash = { message: 'Case not found.' }; return ctx.redirect('/courts?filter=cases'); }
  3770. if (!judgeId) { ctx.flash = { message: 'Judge is required.' }; return ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`); }
  3771. if (uid && judgeId === uid) { ctx.flash = { message: 'You cannot assign yourself as judge.' }; return ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`); }
  3772. try { await courtsModel.assignJudge({ caseId, judgeId }); } catch (e) { ctx.flash = { message: String(e?.message || e) }; }
  3773. ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`);
  3774. })
  3775. .post('/courts/cases/:id/public', koaBody(), async (ctx) => {
  3776. const caseId = ctx.params.id, pref = String(ctx.request.body?.preference || '').toUpperCase();
  3777. if (!caseId) { ctx.flash = { message: 'Case not found.' }; return ctx.redirect('/courts?filter=cases'); }
  3778. if (pref !== 'YES' && pref !== 'NO') { ctx.flash = { message: 'Invalid visibility preference.' }; return ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`); }
  3779. try { await courtsModel.setPublicPreference({ caseId, preference: pref === 'YES' }); } catch (e) { ctx.flash = { message: String(e?.message || e) }; }
  3780. ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`);
  3781. })
  3782. .post('/courts/cases/:id/openVote', koaBody(), async (ctx) => {
  3783. const caseId = ctx.params.id;
  3784. if (!caseId) { ctx.flash = { message: 'Case not found.' }; return ctx.redirect('/courts?filter=cases'); }
  3785. try { await courtsModel.openPopularVote({ caseId }); } catch (e) { ctx.flash = { message: String(e?.message || e) }; }
  3786. ctx.redirect(`/courts/cases/${encodeURIComponent(caseId)}`);
  3787. })
  3788. .post('/courts/judges/nominate', koaBody(), async (ctx) => {
  3789. const judgeId = String(ctx.request.body?.judgeId || '').trim();
  3790. if (!judgeId) { ctx.flash = { message: 'Judge is required.' }; return ctx.redirect('/courts?filter=judges'); }
  3791. try { await courtsModel.nominateJudge({ judgeId }); } catch (e) { ctx.flash = { message: String(e?.message || e) }; }
  3792. ctx.redirect('/courts?filter=judges');
  3793. })
  3794. .post('/courts/judges/:id/vote', koaBody(), async (ctx) => {
  3795. if (!ctx.params.id) { ctx.flash = { message: 'Nomination not found.' }; return ctx.redirect('/courts?filter=judges'); }
  3796. try { await courtsModel.voteNomination(ctx.params.id); } catch (e) { ctx.flash = { message: String(e?.message || e) }; }
  3797. ctx.redirect('/courts?filter=judges');
  3798. })
  3799. .post("/market/create", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3800. if (!checkMod(ctx, 'marketMod')) { ctx.redirect('/modules'); return; }
  3801. const b = ctx.request.body, image = await handleBlobUpload(ctx, "image"), parsedStock = parseInt(String(b.stock || "0"), 10);
  3802. if (!parsedStock || parsedStock <= 0) ctx.throw(400, "Stock must be a positive number.");
  3803. const pickLast = v => Array.isArray(v) ? v[v.length - 1] : v, shpVal = pickLast(b.includesShipping);
  3804. await marketModel.createItem(b.item_type, stripDangerousTags(b.title), stripDangerousTags(b.description), image, b.price, b.tags, b.item_status, b.deadline, shpVal === "1" || shpVal === "on" || shpVal === true || shpVal === "true", parsedStock, stripDangerousTags(b.mapUrl));
  3805. ctx.redirect(safeReturnTo(ctx, "/market", ["/market"]));
  3806. })
  3807. .post("/market/update/:id", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3808. if (!checkMod(ctx, 'marketMod')) { ctx.redirect('/modules'); return; }
  3809. const b = ctx.request.body, parsedStock = parseInt(String(b.stock || "0"), 10);
  3810. if (parsedStock < 0) ctx.throw(400, "Stock cannot be negative.");
  3811. const pickLast = v => Array.isArray(v) ? v[v.length - 1] : v, shpVal = pickLast(b.includesShipping);
  3812. const updatedData = { item_type: b.item_type, title: stripDangerousTags(b.title), description: stripDangerousTags(b.description), price: b.price, item_status: b.item_status, deadline: b.deadline, includesShipping: shpVal === "1" || shpVal === "on" || shpVal === true || shpVal === "true", tags: String(b.tags || "").split(",").map(t => t.trim()).filter(Boolean), stock: parsedStock, mapUrl: stripDangerousTags(b.mapUrl) };
  3813. const image = await handleBlobUpload(ctx, "image");
  3814. if (image) updatedData.image = image;
  3815. await marketModel.updateItemById(ctx.params.id, updatedData);
  3816. ctx.redirect(safeReturnTo(ctx, "/market?filter=mine", ["/market"]));
  3817. })
  3818. .post("/market/delete/:id", koaBody(), async ctx => {
  3819. if (!checkMod(ctx, 'marketMod')) { ctx.redirect('/modules'); return; }
  3820. await marketModel.deleteItemById(ctx.params.id)
  3821. ctx.redirect(safeReturnTo(ctx, "/market?filter=mine", ["/market"]))
  3822. })
  3823. .post("/market/sold/:id", koaBody(), async (ctx) => {
  3824. if (!checkMod(ctx, 'marketMod')) { ctx.redirect('/modules'); return; }
  3825. const item = await marketModel.getItemById(ctx.params.id);
  3826. if (!item) ctx.throw(404, "Item not found");
  3827. if (Number(item.stock || 0) <= 0) ctx.throw(400, "No stock left to mark as sold.");
  3828. if (item.status !== "SOLD") { await marketModel.setItemAsSold(ctx.params.id); await marketModel.decrementStock(ctx.params.id); }
  3829. ctx.redirect(safeReturnTo(ctx, "/market?filter=mine", ["/market"]));
  3830. })
  3831. .post("/market/buy/:id", koaBody(), async (ctx) => {
  3832. if (!checkMod(ctx, 'marketMod')) { ctx.redirect('/modules'); return; }
  3833. const item = await marketModel.getItemById(ctx.params.id);
  3834. if (!item) ctx.throw(404, "Item not found");
  3835. if (item.item_type === "exchange" && item.status !== "SOLD") {
  3836. await pmModel.sendMessage([item.seller], "MARKET_SOLD", `item "${item.title}" has been sold -> /market/${ctx.params.id} OASIS ID: ${getViewerId()} for: ${item.price} ECO`);
  3837. await marketModel.setItemAsSold(ctx.params.id);
  3838. } else await marketModel.decrementStock(ctx.params.id);
  3839. if (item.shopProductId && checkMod(ctx, 'shopsMod')) {
  3840. try { await shopsModel.buyProduct(item.shopProductId); } catch (_) {}
  3841. }
  3842. ctx.redirect(safeReturnTo(ctx, "/inbox?filter=sent", ["/inbox", "/market"]));
  3843. })
  3844. .post("/market/status/:id", koaBody(), async (ctx) => {
  3845. if (!checkMod(ctx, 'marketMod')) { ctx.redirect('/modules'); return; }
  3846. const desired = String(ctx.request.body.status || "").toUpperCase().replace(/_/g, " ").replace(/\s+/g, " ").trim();
  3847. if (!["FOR SALE", "SOLD", "DISCARDED"].includes(desired)) ctx.throw(400, "Invalid status.");
  3848. const item = await marketModel.getItemById(ctx.params.id);
  3849. if (!item) ctx.throw(404, "Item not found");
  3850. const cur = String(item.status || "").toUpperCase().replace(/\s+/g, " ").trim();
  3851. if (cur !== "SOLD" && cur !== "DISCARDED" && desired !== cur && desired !== "FOR SALE") {
  3852. if (desired === "SOLD") {
  3853. if (Number(item.stock || 0) <= 0) ctx.throw(400, "No stock left to mark as sold.");
  3854. await marketModel.setItemAsSold(ctx.params.id); await marketModel.decrementStock(ctx.params.id);
  3855. } else if (desired === "DISCARDED") await marketModel.updateItemById(ctx.params.id, { status: "DISCARDED", stock: 0 });
  3856. }
  3857. ctx.redirect(safeReturnTo(ctx, "/market?filter=mine", ["/market"]));
  3858. })
  3859. .post("/market/bid/:id", koaBody(), async ctx => {
  3860. if (!checkMod(ctx, 'marketMod')) { ctx.redirect('/modules'); return; }
  3861. await marketModel.addBidToAuction(ctx.params.id, getViewerId(), ctx.request.body.bidAmount)
  3862. ctx.redirect(safeReturnTo(ctx, "/market?filter=auctions", ["/market"]))
  3863. })
  3864. .post("/market/:itemId/comments", koaBodyMiddleware, async ctx => commentAction(ctx, 'market', 'itemId'))
  3865. .post('/jobs/create', koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3866. if (!checkMod(ctx, 'jobsMod')) { ctx.redirect('/modules'); return; }
  3867. const b = ctx.request.body, imageBlob = ctx.request.files?.image ? await handleBlobUpload(ctx, 'image') : null;
  3868. await jobsModel.createJob({ job_type: stripDangerousTags(b.job_type), title: stripDangerousTags(b.title), description: stripDangerousTags(b.description), requirements: stripDangerousTags(b.requirements), languages: stripDangerousTags(b.languages), job_time: b.job_time, tasks: stripDangerousTags(b.tasks), location: stripDangerousTags(b.location), vacants: b.vacants ? parseInt(b.vacants, 10) : 1, salary: b.salary != null && b.salary !== '' ? parseFloat(String(b.salary).replace(',', '.')) : 0, tags: b.tags, image: imageBlob, mapUrl: stripDangerousTags(b.mapUrl) });
  3869. ctx.redirect(safeReturnTo(ctx, '/jobs?filter=MINE', ['/jobs']));
  3870. })
  3871. .post('/jobs/update/:id', koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3872. if (!checkMod(ctx, 'jobsMod')) { ctx.redirect('/modules'); return; }
  3873. const b = ctx.request.body, imageBlob = ctx.request.files?.image ? await handleBlobUpload(ctx, 'image') : undefined;
  3874. const patch = { job_type: stripDangerousTags(b.job_type), title: stripDangerousTags(b.title), description: stripDangerousTags(b.description), requirements: stripDangerousTags(b.requirements), languages: stripDangerousTags(b.languages), job_time: b.job_time, tasks: stripDangerousTags(b.tasks), location: stripDangerousTags(b.location), tags: b.tags, mapUrl: stripDangerousTags(b.mapUrl) };
  3875. if (b.vacants !== undefined && b.vacants !== '') patch.vacants = parseInt(b.vacants, 10);
  3876. if (b.salary !== undefined && b.salary !== '') patch.salary = parseFloat(String(b.salary).replace(',', '.'));
  3877. if (imageBlob !== undefined) patch.image = imageBlob;
  3878. await jobsModel.updateJob(ctx.params.id, patch);
  3879. ctx.redirect(safeReturnTo(ctx, '/jobs?filter=MINE', ['/jobs']));
  3880. })
  3881. .post('/jobs/delete/:id', koaBody(), async ctx => {
  3882. if (!checkMod(ctx, 'jobsMod')) { ctx.redirect('/modules'); return; }
  3883. await jobsModel.deleteJob(ctx.params.id)
  3884. ctx.redirect(safeReturnTo(ctx, '/jobs?filter=MINE', ['/jobs']))
  3885. })
  3886. .post('/jobs/status/:id', koaBody(), async ctx => {
  3887. if (!checkMod(ctx, 'jobsMod')) { ctx.redirect('/modules'); return; }
  3888. await jobsModel.updateJobStatus(ctx.params.id, String(ctx.request.body.status).toUpperCase())
  3889. ctx.redirect(safeReturnTo(ctx, '/jobs?filter=MINE', ['/jobs']))
  3890. })
  3891. .post('/jobs/subscribe/:id', koaBody(), async (ctx) => {
  3892. if (!checkMod(ctx, 'jobsMod')) { ctx.redirect('/modules'); return; }
  3893. const userId = getViewerId(), job = await jobsModel.getJobById(ctx.params.id, userId);
  3894. await jobsModel.subscribeToJob(ctx.params.id, userId);
  3895. await pmModel.sendMessage([job.author], 'JOB_SUBSCRIBED', `has subscribed to your job offer "${job.title || ''}" -> /jobs/${encodeURIComponent(job.id)}`);
  3896. ctx.redirect(safeReturnTo(ctx, '/jobs', ['/jobs']));
  3897. })
  3898. .post('/jobs/unsubscribe/:id', koaBody(), async (ctx) => {
  3899. if (!checkMod(ctx, 'jobsMod')) { ctx.redirect('/modules'); return; }
  3900. const userId = getViewerId(), job = await jobsModel.getJobById(ctx.params.id, userId);
  3901. await jobsModel.unsubscribeFromJob(ctx.params.id, userId);
  3902. await pmModel.sendMessage([job.author], 'JOB_UNSUBSCRIBED', `has unsubscribed from your job offer "${job.title || ''}" -> /jobs/${encodeURIComponent(job.id)}`);
  3903. ctx.redirect(safeReturnTo(ctx, '/jobs', ['/jobs']));
  3904. })
  3905. .post('/jobs/:jobId/comments', koaBodyMiddleware, async ctx => commentAction(ctx, 'jobs', 'jobId'))
  3906. .post("/shops/create", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3907. if (!checkMod(ctx, 'shopsMod')) { ctx.redirect('/modules'); return; }
  3908. const b = ctx.request.body, imageBlob = ctx.request.files?.image ? await handleBlobUpload(ctx, 'image') : null;
  3909. await shopsModel.createShop(stripDangerousTags(b.title), stripDangerousTags(b.shortDescription), stripDangerousTags(b.description), imageBlob, stripDangerousTags(b.url), stripDangerousTags(b.location), b.tags, b.visibility, stripDangerousTags(b.mapUrl));
  3910. ctx.redirect(safeReturnTo(ctx, '/shops?filter=mine', ['/shops']));
  3911. })
  3912. .post("/shops/update/:id", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3913. if (!checkMod(ctx, 'shopsMod')) { ctx.redirect('/modules'); return; }
  3914. const b = ctx.request.body, imageBlob = ctx.request.files?.image ? await handleBlobUpload(ctx, 'image') : undefined;
  3915. const patch = { title: stripDangerousTags(b.title), shortDescription: stripDangerousTags(b.shortDescription), description: stripDangerousTags(b.description), url: stripDangerousTags(b.url), location: stripDangerousTags(b.location), tags: b.tags, visibility: b.visibility, mapUrl: stripDangerousTags(b.mapUrl) };
  3916. if (imageBlob !== undefined) patch.image = imageBlob;
  3917. await shopsModel.updateShopById(ctx.params.id, patch);
  3918. ctx.redirect(safeReturnTo(ctx, '/shops?filter=mine', ['/shops']));
  3919. })
  3920. .post("/shops/delete/:id", koaBody(), async (ctx) => {
  3921. if (!checkMod(ctx, 'shopsMod')) { ctx.redirect('/modules'); return; }
  3922. await shopsModel.deleteShopById(ctx.params.id);
  3923. ctx.redirect(safeReturnTo(ctx, '/shops?filter=mine', ['/shops']));
  3924. })
  3925. .post("/shops/visibility/:id", koaBody(), async (ctx) => {
  3926. if (!checkMod(ctx, 'shopsMod')) { ctx.redirect('/modules'); return; }
  3927. await shopsModel.updateShopById(ctx.params.id, { visibility: ctx.request.body.visibility });
  3928. ctx.redirect(safeReturnTo(ctx, `/shops/${encodeURIComponent(ctx.params.id)}`, ['/shops']));
  3929. })
  3930. .post("/shops/favorites/add/:id", koaBody(), async ctx => favAction(ctx, 'shops', 'add'))
  3931. .post("/shops/favorites/remove/:id", koaBody(), async ctx => favAction(ctx, 'shops', 'remove'))
  3932. .post("/shops/opinions/:shopId/:category", koaBody(), async (ctx) => {
  3933. if (!checkMod(ctx, 'shopsMod')) { ctx.redirect('/modules'); return; }
  3934. await shopsModel.createOpinion(ctx.params.shopId, ctx.params.category);
  3935. ctx.redirect(safeReturnTo(ctx, `/shops/${encodeURIComponent(ctx.params.shopId)}`, ['/shops']));
  3936. })
  3937. .post("/shops/product/create", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3938. if (!checkMod(ctx, 'shopsMod')) { ctx.redirect('/modules'); return; }
  3939. const b = ctx.request.body, imageBlob = ctx.request.files?.image ? await handleBlobUpload(ctx, 'image') : null;
  3940. const productMsg = await shopsModel.createProduct(b.shopId, stripDangerousTags(b.title), stripDangerousTags(b.description), imageBlob, b.price, b.stock, [].concat(b.featured).includes("1"));
  3941. if ([].concat(b.sendToMarket).includes("1") && checkMod(ctx, 'marketMod')) {
  3942. const shop = await shopsModel.getShopById(b.shopId);
  3943. const deadline = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString();
  3944. const stock = parseInt(String(b.stock || '0'), 10) || 1;
  3945. try {
  3946. await marketModel.createItem('exchange', stripDangerousTags(b.title), stripDangerousTags(b.description), imageBlob, b.price, [], 'NEW', deadline, false, stock, '', { shopProductId: productMsg.key, shopId: b.shopId, shopTitle: shop ? shop.title : '' });
  3947. } catch (e) { console.error("market-from-shop:", e.message) }
  3948. }
  3949. ctx.redirect(safeReturnTo(ctx, `/shops/${encodeURIComponent(b.shopId)}`, ['/shops']));
  3950. })
  3951. .post("/shops/product/update/:id", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3952. if (!checkMod(ctx, 'shopsMod')) { ctx.redirect('/modules'); return; }
  3953. const b = ctx.request.body, imageBlob = ctx.request.files?.image ? await handleBlobUpload(ctx, 'image') : undefined;
  3954. const patch = { title: stripDangerousTags(b.title), description: stripDangerousTags(b.description), price: b.price, stock: b.stock, featured: [].concat(b.featured).includes("1") };
  3955. if (imageBlob !== undefined) patch.image = imageBlob;
  3956. await shopsModel.updateProductById(ctx.params.id, patch);
  3957. ctx.redirect(safeReturnTo(ctx, `/shops/${encodeURIComponent(b.shopId || '')}`, ['/shops']));
  3958. })
  3959. .post("/shops/product/delete/:id", koaBody(), async (ctx) => {
  3960. if (!checkMod(ctx, 'shopsMod')) { ctx.redirect('/modules'); return; }
  3961. const product = await shopsModel.getProductById(ctx.params.id);
  3962. await shopsModel.deleteProductById(ctx.params.id);
  3963. ctx.redirect(safeReturnTo(ctx, `/shops/${encodeURIComponent(product?.shopId || '')}`, ['/shops']));
  3964. })
  3965. .post("/shops/product/buy/:id", koaBody(), async (ctx) => {
  3966. if (!checkMod(ctx, 'shopsMod')) { ctx.redirect('/modules'); return; }
  3967. await shopsModel.buyProduct(ctx.params.id);
  3968. if (checkMod(ctx, 'marketMod')) {
  3969. try { const mi = await marketModel.getItemByShopProductId(ctx.params.id); if (mi) await marketModel.decrementStock(mi.id); } catch (_) {}
  3970. }
  3971. ctx.redirect(safeReturnTo(ctx, `/shops/product/${encodeURIComponent(ctx.params.id)}`, ['/shops']));
  3972. })
  3973. .post("/shops/product/opinions/:productId/:category", koaBody(), async (ctx) => {
  3974. if (!checkMod(ctx, 'shopsMod')) { ctx.redirect('/modules'); return; }
  3975. await shopsModel.createOpinion(ctx.params.productId, ctx.params.category);
  3976. ctx.redirect(safeReturnTo(ctx, `/shops/product/${encodeURIComponent(ctx.params.productId)}`, ['/shops']));
  3977. })
  3978. .post("/shops/:shopId/comments", koaBodyMiddleware, async ctx => commentAction(ctx, 'shops', 'shopId'))
  3979. .post("/chats/create", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3980. if (!checkMod(ctx, 'chatsMod')) { ctx.redirect('/modules'); return; }
  3981. const b = ctx.request.body;
  3982. const tribeId = b.tribeId || null;
  3983. if (tribeId) {
  3984. const t = await tribesModel.getTribeById(tribeId).catch(() => null);
  3985. if (!t || !t.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  3986. await tribesModel.ensureTribeKeyDistribution(tribeId).catch(() => {});
  3987. }
  3988. const imageBlob = ctx.request.files?.image ? extractBlobId(await handleBlobUpload(ctx, 'image')) : null;
  3989. await chatsModel.createChat(stripDangerousTags(b.title), stripDangerousTags(b.description), imageBlob, b.category, b.status, b.tags, tribeId);
  3990. ctx.redirect(tribeId ? `/tribe/${encodeURIComponent(tribeId)}?section=chats` : safeReturnTo(ctx, '/chats?filter=mine', ['/chats']));
  3991. })
  3992. .post("/chats/update/:id", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  3993. if (!checkMod(ctx, 'chatsMod')) { ctx.redirect('/modules'); return; }
  3994. const b = ctx.request.body;
  3995. const imageBlob = ctx.request.files?.image ? extractBlobId(await handleBlobUpload(ctx, 'image')) : undefined;
  3996. const patch = { title: stripDangerousTags(b.title), description: stripDangerousTags(b.description), category: b.category, status: b.status, tags: b.tags };
  3997. if (imageBlob !== undefined) patch.image = imageBlob;
  3998. await chatsModel.updateChatById(ctx.params.id, patch);
  3999. ctx.redirect(safeReturnTo(ctx, '/chats?filter=mine', ['/chats']));
  4000. })
  4001. .post("/chats/delete/:id", koaBody(), async (ctx) => {
  4002. if (!checkMod(ctx, 'chatsMod')) { ctx.redirect('/modules'); return; }
  4003. await chatsModel.deleteChatById(ctx.params.id);
  4004. ctx.redirect(safeReturnTo(ctx, '/chats?filter=mine', ['/chats']));
  4005. })
  4006. .post("/chats/close/:id", koaBody(), async (ctx) => {
  4007. if (!checkMod(ctx, 'chatsMod')) { ctx.redirect('/modules'); return; }
  4008. await chatsModel.closeChatById(ctx.params.id);
  4009. ctx.redirect(safeReturnTo(ctx, `/chats/${encodeURIComponent(ctx.params.id)}`, ['/chats']));
  4010. })
  4011. .post("/chats/generate-invite", koaBody(), async (ctx) => {
  4012. if (!checkMod(ctx, 'chatsMod')) { ctx.redirect('/modules'); return; }
  4013. const chatId = ctx.request.body.chatId;
  4014. const code = await chatsModel.generateInvite(chatId);
  4015. ctx.body = renderChatInvitePage(code);
  4016. })
  4017. .post("/chats/join-code", koaBody(), async (ctx) => {
  4018. if (!checkMod(ctx, 'chatsMod')) { ctx.redirect('/modules'); return; }
  4019. const code = String(ctx.request.body.code || '').trim();
  4020. try {
  4021. const chatKey = await chatsModel.joinByInvite(code);
  4022. ctx.redirect(safeReturnTo(ctx, `/chats/${encodeURIComponent(chatKey)}`, ['/chats']));
  4023. } catch (_) {
  4024. ctx.redirect(safeReturnTo(ctx, '/chats', ['/chats']));
  4025. }
  4026. })
  4027. .post("/chats/join/:id", koaBody(), async (ctx) => {
  4028. if (!checkMod(ctx, 'chatsMod')) { ctx.redirect('/modules'); return; }
  4029. const uid = getViewerId();
  4030. const chat = await chatsModel.getChatById(ctx.params.id);
  4031. if (!chat) { ctx.status = 404; ctx.body = "Chat not found"; return; }
  4032. if (chat.status === "CLOSED") { ctx.status = 403; ctx.body = "Chat is closed"; return; }
  4033. if (chat.status === "INVITE-ONLY" && !chat.members.includes(uid) && chat.author !== uid) { ctx.status = 403; ctx.body = "Invite-only chat"; return; }
  4034. if (chat.tribeId) {
  4035. try {
  4036. const t = await tribesModel.getTribeById(chat.tribeId);
  4037. if (!t.members.includes(uid)) { ctx.status = 403; ctx.body = "Forbidden"; return; }
  4038. } catch { ctx.status = 403; ctx.body = "Forbidden"; return; }
  4039. ctx.redirect(safeReturnTo(ctx, `/chats/${encodeURIComponent(ctx.params.id)}`, ['/chats']));
  4040. return;
  4041. }
  4042. try {
  4043. await chatsModel.joinChat(ctx.params.id);
  4044. } catch (_) {}
  4045. ctx.redirect(safeReturnTo(ctx, `/chats/${encodeURIComponent(ctx.params.id)}`, ['/chats']));
  4046. })
  4047. .post("/chats/leave/:id", koaBody(), async (ctx) => {
  4048. if (!checkMod(ctx, 'chatsMod')) { ctx.redirect('/modules'); return; }
  4049. try {
  4050. await chatsModel.leaveChat(ctx.params.id);
  4051. } catch (_) {}
  4052. ctx.redirect(safeReturnTo(ctx, '/chats?filter=all', ['/chats']));
  4053. })
  4054. .post("/chats/favorites/add/:id", koaBody(), async ctx => favAction(ctx, 'chats', 'add'))
  4055. .post("/chats/favorites/remove/:id", koaBody(), async ctx => favAction(ctx, 'chats', 'remove'))
  4056. .post("/chats/:chatId/message", koaBody({ multipart: true }), async (ctx) => {
  4057. if (!checkMod(ctx, 'chatsMod')) { ctx.redirect('/modules'); return; }
  4058. const uid = getViewerId();
  4059. const chat = await chatsModel.getChatById(ctx.params.chatId);
  4060. if (chat && chat.tribeId) {
  4061. try {
  4062. const t = await tribesModel.getTribeById(chat.tribeId);
  4063. if (!t.members.includes(uid)) { ctx.status = 403; ctx.body = "Forbidden"; return; }
  4064. } catch { ctx.status = 403; ctx.body = "Forbidden"; return; }
  4065. }
  4066. const text = stripDangerousTags(String(ctx.request.body.text || '').trim());
  4067. const imageBlob = ctx.request.files?.image ? extractBlobId(await handleBlobUpload(ctx, 'image')) : null;
  4068. if (!text && !imageBlob) { ctx.redirect(`/chats/${encodeURIComponent(ctx.params.chatId)}`); return; }
  4069. await chatsModel.sendMessage(ctx.params.chatId, text, imageBlob);
  4070. ctx.redirect(safeReturnTo(ctx, `/chats/${encodeURIComponent(ctx.params.chatId)}`, ['/chats']));
  4071. })
  4072. .post("/pads/create", koaBody(), async (ctx) => {
  4073. if (!checkMod(ctx, 'padsMod')) { ctx.redirect('/modules'); return; }
  4074. const b = ctx.request.body || {};
  4075. const tribeId = b.tribeId || null;
  4076. if (tribeId) {
  4077. const t = await tribesModel.getTribeById(tribeId).catch(() => null);
  4078. if (!t || !t.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  4079. await tribesModel.ensureTribeKeyDistribution(tribeId).catch(() => {});
  4080. }
  4081. const msg = await padsModel.createPad(
  4082. stripDangerousTags(b.title || ""),
  4083. b.status || "OPEN",
  4084. b.deadline || "",
  4085. b.tags || "",
  4086. tribeId
  4087. );
  4088. ctx.redirect(tribeId ? `/tribe/${encodeURIComponent(tribeId)}?section=pads` : `/pads/${encodeURIComponent(msg.key)}`);
  4089. })
  4090. .post("/pads/update/:id", koaBody(), async (ctx) => {
  4091. if (!checkMod(ctx, 'padsMod')) { ctx.redirect('/modules'); return; }
  4092. const b = ctx.request.body || {};
  4093. await padsModel.updatePadById(ctx.params.id, {
  4094. title: stripDangerousTags(b.title || ""),
  4095. status: b.status || "OPEN",
  4096. deadline: b.deadline || "",
  4097. tags: b.tags || ""
  4098. });
  4099. ctx.redirect(`/pads/${encodeURIComponent(ctx.params.id)}`);
  4100. })
  4101. .post("/pads/close/:id", koaBody(), async (ctx) => {
  4102. if (!checkMod(ctx, 'padsMod')) { ctx.redirect('/modules'); return; }
  4103. try { await padsModel.closePadById(ctx.params.id); } catch (_) {}
  4104. ctx.redirect(`/pads/${encodeURIComponent(ctx.params.id)}`);
  4105. })
  4106. .post("/pads/delete/:id", koaBody(), async (ctx) => {
  4107. if (!checkMod(ctx, 'padsMod')) { ctx.redirect('/modules'); return; }
  4108. await padsModel.deletePadById(ctx.params.id);
  4109. ctx.redirect('/pads');
  4110. })
  4111. .post("/pads/generate-invite/:id", koaBody(), async (ctx) => {
  4112. if (!checkMod(ctx, 'padsMod')) { ctx.redirect('/modules'); return; }
  4113. const code = await padsModel.generateInvite(ctx.params.id);
  4114. ctx.body = renderPadInvitePage(code);
  4115. })
  4116. .post("/pads/join-code", koaBody(), async (ctx) => {
  4117. if (!checkMod(ctx, 'padsMod')) { ctx.redirect('/modules'); return; }
  4118. const code = String((ctx.request.body || {}).code || "").trim();
  4119. try {
  4120. const padId = await padsModel.joinByInvite(code);
  4121. ctx.redirect(`/pads/${encodeURIComponent(padId)}`);
  4122. } catch (_) {
  4123. ctx.redirect('/pads');
  4124. }
  4125. })
  4126. .post("/pads/join/:id", koaBody(), async (ctx) => {
  4127. if (!checkMod(ctx, 'padsMod')) { ctx.redirect('/modules'); return; }
  4128. const uid = getViewerId();
  4129. const pad = await padsModel.getPadById(ctx.params.id);
  4130. if (!pad) { ctx.status = 404; ctx.body = "Pad not found"; return; }
  4131. if (pad.isClosed || pad.status === "CLOSED") { ctx.status = 403; ctx.body = "Pad is closed"; return; }
  4132. if (pad.status === "INVITE-ONLY" && !pad.members.includes(uid) && pad.author !== uid) { ctx.status = 403; ctx.body = "Invite-only pad"; return; }
  4133. if (pad.tribeId) {
  4134. try {
  4135. const t = await tribesModel.getTribeById(pad.tribeId);
  4136. if (!t.members.includes(uid)) { ctx.status = 403; ctx.body = "Forbidden"; return; }
  4137. } catch { ctx.status = 403; ctx.body = "Forbidden"; return; }
  4138. ctx.redirect(`/pads/${encodeURIComponent(ctx.params.id)}`);
  4139. return;
  4140. }
  4141. await padsModel.addMemberToPad(ctx.params.id, uid);
  4142. ctx.redirect(`/pads/${encodeURIComponent(ctx.params.id)}`);
  4143. })
  4144. .post("/pads/entry/:id", koaBody(), async (ctx) => {
  4145. if (!checkMod(ctx, 'padsMod')) { ctx.redirect('/modules'); return; }
  4146. const uid = getViewerId();
  4147. const pad = await padsModel.getPadById(ctx.params.id);
  4148. if (pad && pad.tribeId) {
  4149. try {
  4150. const t = await tribesModel.getTribeById(pad.tribeId);
  4151. if (!t.members.includes(uid)) { ctx.status = 403; ctx.body = "Forbidden"; return; }
  4152. } catch { ctx.status = 403; ctx.body = "Forbidden"; return; }
  4153. }
  4154. const b = ctx.request.body || {};
  4155. const text = stripDangerousTags(String(b.text || "").trim());
  4156. if (text) await padsModel.addEntry(ctx.params.id, text);
  4157. ctx.redirect(`/pads/${encodeURIComponent(ctx.params.id)}`);
  4158. })
  4159. .post("/pads/favorites/add/:id", koaBody(), async ctx => favAction(ctx, 'pads', 'add'))
  4160. .post("/pads/favorites/remove/:id", koaBody(), async ctx => favAction(ctx, 'pads', 'remove'))
  4161. .post("/calendars/create", koaBody(), async (ctx) => {
  4162. if (!checkMod(ctx, 'calendarsMod')) { ctx.redirect('/modules'); return; }
  4163. const b = ctx.request.body || {};
  4164. const tribeId = b.tribeId || null;
  4165. if (tribeId) {
  4166. const t = await tribesModel.getTribeById(tribeId).catch(() => null);
  4167. if (!t || !t.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  4168. }
  4169. const intervalWeekly = [].concat(b.intervalWeekly).includes("1");
  4170. const intervalMonthly = [].concat(b.intervalMonthly).includes("1");
  4171. const intervalYearly = [].concat(b.intervalYearly).includes("1");
  4172. try {
  4173. const msg = await calendarsModel.createCalendar({
  4174. title: stripDangerousTags(b.title || ""),
  4175. status: b.status || "OPEN",
  4176. deadline: b.deadline || "",
  4177. tags: b.tags || "",
  4178. firstDate: b.firstDate || "",
  4179. firstDateLabel: stripDangerousTags(b.firstDateLabel || ""),
  4180. firstNote: stripDangerousTags(b.firstNote || ""),
  4181. intervalWeekly, intervalMonthly, intervalYearly,
  4182. tribeId
  4183. });
  4184. ctx.redirect(tribeId ? `/tribe/${encodeURIComponent(tribeId)}?section=calendars` : `/calendars/${encodeURIComponent(msg.key)}`);
  4185. } catch (e) {
  4186. console.error("[calendars/create]", e && e.message ? e.message : e)
  4187. ctx.redirect(tribeId ? `/tribe/${encodeURIComponent(tribeId)}?section=calendars` : '/calendars');
  4188. }
  4189. })
  4190. .post("/calendars/update/:id", koaBody(), async (ctx) => {
  4191. if (!checkMod(ctx, 'calendarsMod')) { ctx.redirect('/modules'); return; }
  4192. const target = await calendarsModel.getCalendarById(ctx.params.id).catch(() => null);
  4193. if (target && target.tribeId) {
  4194. const t = await tribesModel.getTribeById(target.tribeId).catch(() => null);
  4195. if (!t || !t.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  4196. }
  4197. const b = ctx.request.body || {};
  4198. try {
  4199. await calendarsModel.updateCalendarById(ctx.params.id, {
  4200. title: stripDangerousTags(b.title || ""),
  4201. status: b.status || "OPEN",
  4202. deadline: b.deadline || "",
  4203. tags: b.tags || ""
  4204. });
  4205. } catch (_) {}
  4206. ctx.redirect(`/calendars/${encodeURIComponent(ctx.params.id)}`);
  4207. })
  4208. .post("/calendars/delete/:id", koaBody(), async (ctx) => {
  4209. if (!checkMod(ctx, 'calendarsMod')) { ctx.redirect('/modules'); return; }
  4210. const target = await calendarsModel.getCalendarById(ctx.params.id).catch(() => null);
  4211. if (target && target.tribeId) {
  4212. const t = await tribesModel.getTribeById(target.tribeId).catch(() => null);
  4213. if (!t || !t.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  4214. }
  4215. try { await calendarsModel.deleteCalendarById(ctx.params.id); } catch (_) {}
  4216. ctx.redirect('/calendars');
  4217. })
  4218. .post("/calendars/join/:id", koaBody(), async (ctx) => {
  4219. if (!checkMod(ctx, 'calendarsMod')) { ctx.redirect('/modules'); return; }
  4220. const target = await calendarsModel.getCalendarById(ctx.params.id).catch(() => null);
  4221. if (target && target.tribeId) {
  4222. const t = await tribesModel.getTribeById(target.tribeId).catch(() => null);
  4223. if (!t || !t.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  4224. }
  4225. try { await calendarsModel.joinCalendar(ctx.params.id); } catch (_) {}
  4226. ctx.redirect(`/calendars/${encodeURIComponent(ctx.params.id)}`);
  4227. })
  4228. .post("/calendars/leave/:id", koaBody(), async (ctx) => {
  4229. if (!checkMod(ctx, 'calendarsMod')) { ctx.redirect('/modules'); return; }
  4230. const target = await calendarsModel.getCalendarById(ctx.params.id).catch(() => null);
  4231. if (target && target.tribeId) {
  4232. const t = await tribesModel.getTribeById(target.tribeId).catch(() => null);
  4233. if (!t || !t.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  4234. }
  4235. try { await calendarsModel.leaveCalendar(ctx.params.id); } catch (_) {}
  4236. ctx.redirect(`/calendars/${encodeURIComponent(ctx.params.id)}`);
  4237. })
  4238. .post("/calendars/add-date/:id", koaBody(), async (ctx) => {
  4239. if (!checkMod(ctx, 'calendarsMod')) { ctx.redirect('/modules'); return; }
  4240. const uid = getViewerId();
  4241. const calForGate = await calendarsModel.getCalendarById(ctx.params.id).catch(() => null);
  4242. if (calForGate && calForGate.tribeId) {
  4243. try {
  4244. const t = await tribesModel.getTribeById(calForGate.tribeId);
  4245. if (!t.members.includes(uid)) { ctx.status = 403; ctx.body = "Forbidden"; return; }
  4246. } catch { ctx.status = 403; ctx.body = "Forbidden"; return; }
  4247. }
  4248. const b = ctx.request.body || {};
  4249. const intervalWeekly = [].concat(b.intervalWeekly).includes("1");
  4250. const intervalMonthly = [].concat(b.intervalMonthly).includes("1");
  4251. const intervalYearly = [].concat(b.intervalYearly).includes("1");
  4252. try {
  4253. const dateMsgs = await calendarsModel.addDate(ctx.params.id, b.date || "", stripDangerousTags(b.label || ""), intervalWeekly, intervalMonthly, intervalYearly, b.intervalDeadline || "");
  4254. const noteText = stripDangerousTags(String(b.text || "").trim());
  4255. if (noteText && Array.isArray(dateMsgs)) {
  4256. for (const msg of dateMsgs) {
  4257. if (msg && msg.key) {
  4258. try { await calendarsModel.addNote(ctx.params.id, msg.key, noteText); } catch (_) {}
  4259. }
  4260. }
  4261. }
  4262. } catch (e) {
  4263. console.error("[calendars/add-date]", e && e.message ? e.message : e)
  4264. }
  4265. ctx.redirect(`/calendars/${encodeURIComponent(ctx.params.id)}`);
  4266. })
  4267. .post("/calendars/add-note/:id", koaBody(), async (ctx) => {
  4268. if (!checkMod(ctx, 'calendarsMod')) { ctx.redirect('/modules'); return; }
  4269. const uid = getViewerId();
  4270. const calForGate = await calendarsModel.getCalendarById(ctx.params.id).catch(() => null);
  4271. if (calForGate && calForGate.tribeId) {
  4272. try {
  4273. const t = await tribesModel.getTribeById(calForGate.tribeId);
  4274. if (!t.members.includes(uid)) { ctx.status = 403; ctx.body = "Forbidden"; return; }
  4275. } catch { ctx.status = 403; ctx.body = "Forbidden"; return; }
  4276. }
  4277. const b = ctx.request.body || {};
  4278. const text = stripDangerousTags(String(b.text || "").trim());
  4279. if (text) {
  4280. try { await calendarsModel.addNote(ctx.params.id, b.dateId || "", text); } catch (_) {}
  4281. }
  4282. ctx.redirect(`/calendars/${encodeURIComponent(ctx.params.id)}`);
  4283. })
  4284. .post("/calendars/delete-note/:noteId", koaBody(), async (ctx) => {
  4285. if (!checkMod(ctx, 'calendarsMod')) { ctx.redirect('/modules'); return; }
  4286. const calendarId = (ctx.request.body || {}).calendarId || "";
  4287. if (calendarId) {
  4288. const target = await calendarsModel.getCalendarById(calendarId).catch(() => null);
  4289. if (target && target.tribeId) {
  4290. const t = await tribesModel.getTribeById(target.tribeId).catch(() => null);
  4291. if (!t || !t.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  4292. }
  4293. }
  4294. try { await calendarsModel.deleteNote(ctx.params.noteId); } catch (_) {}
  4295. ctx.redirect(calendarId ? `/calendars/${encodeURIComponent(calendarId)}` : '/calendars');
  4296. })
  4297. .post("/calendars/delete-date/:id", koaBody(), async (ctx) => {
  4298. if (!checkMod(ctx, 'calendarsMod')) { ctx.redirect('/modules'); return; }
  4299. const calendarId = (ctx.request.body || {}).calendarId || "";
  4300. if (calendarId) {
  4301. const target = await calendarsModel.getCalendarById(calendarId).catch(() => null);
  4302. if (target && target.tribeId) {
  4303. const t = await tribesModel.getTribeById(target.tribeId).catch(() => null);
  4304. if (!t || !t.members.includes(getViewerId())) { ctx.status = 403; ctx.redirect('/tribes'); return; }
  4305. }
  4306. }
  4307. try { await calendarsModel.deleteDate(ctx.params.id, calendarId); } catch (_) {}
  4308. ctx.redirect(calendarId ? `/calendars/${encodeURIComponent(calendarId)}` : '/calendars');
  4309. })
  4310. .post("/calendars/favorites/add/:id", koaBody(), async ctx => favAction(ctx, 'calendars', 'add'))
  4311. .post("/calendars/favorites/remove/:id", koaBody(), async ctx => favAction(ctx, 'calendars', 'remove'))
  4312. .post("/projects/create", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  4313. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  4314. const b = ctx.request.body || {}, image = ctx.request.files?.image ? await handleBlobUpload(ctx, "image") : null;
  4315. const bounties = b.bountiesInput ? String(b.bountiesInput).split("\n").filter(Boolean).map(l => { const [t,a,d] = String(l).split("|"); return { title: String(t||"").trim(), amount: parseFloat(a||0)||0, description: String(d||"").trim(), milestoneIndex: null }; }) : [];
  4316. await projectsModel.createProject({ title: b.title, description: b.description, goal: b.goal != null && b.goal !== "" ? parseFloat(b.goal) : 0, deadline: b.deadline ? new Date(b.deadline).toISOString() : null, progress: b.progress != null && b.progress !== "" ? parseInt(b.progress,10) : 0, bounties, image, milestoneTitle: b.milestoneTitle, milestoneDescription: b.milestoneDescription, milestoneTargetPercent: b.milestoneTargetPercent, milestoneDueDate: b.milestoneDueDate, mapUrl: stripDangerousTags(b.mapUrl) });
  4317. ctx.redirect(safeReturnTo(ctx, "/projects?filter=MINE", ["/projects"]));
  4318. })
  4319. .post("/projects/update/:id", koaBody({ multipart: true, formidable: { maxFileSize: maxSize } }), async (ctx) => {
  4320. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  4321. const id = await projectsModel.getProjectTipId(ctx.params.id), b = ctx.request.body || {};
  4322. const image = ctx.request.files?.image ? await handleBlobUpload(ctx, "image") : undefined;
  4323. const bounties = b.bountiesInput !== undefined ? String(b.bountiesInput).split("\n").filter(Boolean).map(l => { const [t,a,d] = String(l).split("|"); return { title: String(t||"").trim(), amount: parseFloat(a||0)||0, description: String(d||"").trim(), milestoneIndex: null }; }) : undefined;
  4324. await projectsModel.updateProject(id, { title: b.title, description: b.description, goal: b.goal !== "" && b.goal != null ? parseFloat(b.goal) : undefined, deadline: b.deadline ? new Date(b.deadline).toISOString() : undefined, progress: b.progress !== "" && b.progress != null ? parseInt(b.progress,10) : undefined, bounties, image, mapUrl: stripDangerousTags(b.mapUrl) });
  4325. ctx.redirect(safeReturnTo(ctx, "/projects?filter=MINE", ["/projects"]));
  4326. })
  4327. .post("/projects/delete/:id", koaBody(), async (ctx) => {
  4328. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  4329. await projectsModel.deleteProject(await projectsModel.getProjectTipId(ctx.params.id));
  4330. ctx.redirect(safeReturnTo(ctx, "/projects?filter=MINE", ["/projects"]));
  4331. })
  4332. .post("/projects/status/:id", koaBody(), async (ctx) => {
  4333. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  4334. const id = await projectsModel.getProjectTipId(ctx.params.id);
  4335. await projectsModel.updateProjectStatus(id, String(ctx.request.body?.status || "").toUpperCase());
  4336. ctx.redirect(safeReturnTo(ctx, `/projects/${encodeURIComponent(id)}`, ["/projects"]));
  4337. })
  4338. .post("/projects/progress/:id", koaBody(), async (ctx) => {
  4339. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  4340. const id = await projectsModel.getProjectTipId(ctx.params.id);
  4341. await projectsModel.updateProjectProgress(id, ctx.request.body?.progress);
  4342. ctx.redirect(safeReturnTo(ctx, `/projects/${encodeURIComponent(id)}`, ["/projects"]));
  4343. })
  4344. .post("/projects/pledge/:id", koaBody(), async (ctx) => {
  4345. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  4346. const latestId = await projectsModel.getProjectTipId(ctx.params.id), b = ctx.request.body || {};
  4347. const pledgeAmount = parseFloat(b.amount), uid = getViewerId();
  4348. if (isNaN(pledgeAmount) || pledgeAmount <= 0) ctx.throw(400, "Invalid amount");
  4349. const project = await projectsModel.getProjectById(latestId);
  4350. if (String(project.status || "ACTIVE").toUpperCase() !== "ACTIVE") ctx.throw(400, "Project is not active");
  4351. if (project.deadline && moment(project.deadline).isValid() && moment(project.deadline).isBefore(moment())) ctx.throw(400, "Project deadline passed");
  4352. if (project.author === uid) ctx.throw(403, "Authors cannot pledge to their own project");
  4353. let milestoneIndex = null, bountyIndex = null, mob = b.milestoneOrBounty || "";
  4354. if (String(mob).startsWith("milestone:")) milestoneIndex = parseInt(String(mob).split(":")[1], 10);
  4355. else if (String(mob).startsWith("bounty:")) bountyIndex = parseInt(String(mob).split(":")[1], 10);
  4356. const transfer = await transfersModel.createTransfer(project.author, "Project Pledge", pledgeAmount, moment().add(14, "days").toISOString(), ["backer-pledge", `project:${latestId}`]);
  4357. const backers = [...(project.backers || []), { userId: uid, amount: pledgeAmount, at: new Date().toISOString(), transferId: transfer.key || transfer.id, confirmed: false, milestoneIndex, bountyIndex }];
  4358. const pledged = (parseFloat(project.pledged || 0) || 0) + pledgeAmount;
  4359. await projectsModel.updateProject(latestId, { backers, pledged, progress: project.goal ? (pledged / parseFloat(project.goal)) * 100 : 0 });
  4360. await pmModel.sendMessage([project.author], "PROJECT_PLEDGE", `has pledged ${pledgeAmount} ECO to your project "${project.title || ''}" -> /projects/${latestId}`);
  4361. ctx.redirect(safeReturnTo(ctx, `/projects/${encodeURIComponent(latestId)}`, ["/projects"]));
  4362. })
  4363. .post("/projects/confirm-transfer/:id", koaBody(), async (ctx) => {
  4364. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  4365. const uid = getViewerId(), transfer = await transfersModel.getTransferById(ctx.params.id);
  4366. if (transfer.to !== uid) ctx.throw(403, "Unauthorized action");
  4367. const tagProject = (Array.isArray(transfer.tags) ? transfer.tags : []).find(t => String(t).startsWith("project:"));
  4368. if (!tagProject) ctx.throw(400, "Missing project tag on transfer");
  4369. const projectId = String(tagProject).split(":")[1];
  4370. await transfersModel.confirmTransferById(ctx.params.id);
  4371. const project = await projectsModel.getProjectById(projectId), backers = [...(project.backers || [])];
  4372. const idx = backers.findIndex(b => b?.transferId === ctx.params.id);
  4373. if (idx !== -1) backers[idx].confirmed = true;
  4374. await projectsModel.updateProject(projectId, { backers, progress: project.goal ? (parseFloat(project.pledged || 0) / parseFloat(project.goal)) * 100 : 0 });
  4375. ctx.redirect(safeReturnTo(ctx, `/projects/${encodeURIComponent(projectId)}`, ["/projects", "/transfers"]));
  4376. })
  4377. .post("/projects/follow/:id", koaBody(), async (ctx) => {
  4378. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  4379. const latestId = await projectsModel.getProjectTipId(ctx.params.id), project = await projectsModel.getProjectById(latestId);
  4380. await projectsModel.followProject(ctx.params.id, getViewerId());
  4381. await pmModel.sendMessage([project.author], "PROJECT_FOLLOWED", `has followed your project "${project.title || ''}" -> /projects/${latestId}`);
  4382. ctx.redirect(safeReturnTo(ctx, "/projects", ["/projects"]));
  4383. })
  4384. .post("/projects/unfollow/:id", koaBody(), async (ctx) => {
  4385. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  4386. const latestId = await projectsModel.getProjectTipId(ctx.params.id), project = await projectsModel.getProjectById(latestId);
  4387. await projectsModel.unfollowProject(ctx.params.id, getViewerId());
  4388. await pmModel.sendMessage([project.author], "PROJECT_UNFOLLOWED", `has unfollowed your project "${project.title || ''}" -> /projects/${latestId}`);
  4389. ctx.redirect(safeReturnTo(ctx, "/projects", ["/projects"]));
  4390. })
  4391. .post("/projects/milestones/add/:id", koaBody(), async (ctx) => {
  4392. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  4393. const id = await projectsModel.getProjectTipId(ctx.params.id), b = ctx.request.body || {};
  4394. await projectsModel.addMilestone(id, { title: b.title, description: b.description || "", targetPercent: b.targetPercent != null && b.targetPercent !== "" ? parseInt(b.targetPercent, 10) : 0, dueDate: b.dueDate ? new Date(b.dueDate).toISOString() : null });
  4395. ctx.redirect(safeReturnTo(ctx, `/projects/${encodeURIComponent(id)}`, ["/projects"]));
  4396. })
  4397. .post("/projects/milestones/update/:id/:index", koaBody(), async (ctx) => {
  4398. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  4399. const id = await projectsModel.getProjectTipId(ctx.params.id), idx = parseInt(ctx.params.index, 10), b = ctx.request.body || {};
  4400. const patch = { title: b.title, ...(b.description !== undefined ? { description: b.description } : {}), ...(b.targetPercent !== undefined && b.targetPercent !== "" ? { targetPercent: parseInt(b.targetPercent, 10) } : {}), ...(b.dueDate !== undefined ? { dueDate: b.dueDate ? new Date(b.dueDate).toISOString() : null } : {}), ...(b.done !== undefined ? { done: !!b.done } : {}) };
  4401. await projectsModel.updateMilestone(id, idx, patch);
  4402. ctx.redirect(safeReturnTo(ctx, `/projects/${encodeURIComponent(id)}`, ["/projects"]));
  4403. })
  4404. .post("/projects/milestones/complete/:id/:index", koaBody(), async (ctx) => {
  4405. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  4406. const id = await projectsModel.getProjectTipId(ctx.params.id);
  4407. await projectsModel.completeMilestone(id, parseInt(ctx.params.index, 10), getViewerId());
  4408. ctx.redirect(safeReturnTo(ctx, `/projects/${encodeURIComponent(id)}`, ["/projects"]));
  4409. })
  4410. .post("/projects/bounties/add/:id", koaBody(), async (ctx) => {
  4411. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  4412. const id = await projectsModel.getProjectTipId(ctx.params.id), b = ctx.request.body || {};
  4413. await projectsModel.addBounty(id, { title: b.title, amount: b.amount, description: b.description, milestoneIndex: b.milestoneIndex === "" || b.milestoneIndex === undefined ? null : parseInt(b.milestoneIndex, 10) });
  4414. ctx.redirect(safeReturnTo(ctx, `/projects/${encodeURIComponent(id)}`, ["/projects"]));
  4415. })
  4416. .post("/projects/bounties/update/:id/:index", koaBody(), async (ctx) => {
  4417. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  4418. const id = await projectsModel.getProjectTipId(ctx.params.id), idx = parseInt(ctx.params.index, 10), b = ctx.request.body || {};
  4419. const patch = { ...(b.title !== undefined ? { title: b.title } : {}), ...(b.amount !== undefined && b.amount !== "" ? { amount: parseFloat(b.amount) } : {}), ...(b.description !== undefined ? { description: b.description } : {}), ...(b.milestoneIndex !== undefined ? { milestoneIndex: b.milestoneIndex === "" ? null : parseInt(b.milestoneIndex, 10) } : {}), ...(b.done !== undefined ? { done: !!b.done } : {}) };
  4420. await projectsModel.updateBounty(id, idx, patch);
  4421. ctx.redirect(safeReturnTo(ctx, `/projects/${encodeURIComponent(id)}`, ["/projects"]));
  4422. })
  4423. .post("/projects/bounties/claim/:id/:index", koaBody(), async (ctx) => {
  4424. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  4425. const id = await projectsModel.getProjectTipId(ctx.params.id);
  4426. await projectsModel.claimBounty(id, parseInt(ctx.params.index, 10), getViewerId());
  4427. ctx.redirect(safeReturnTo(ctx, `/projects/${encodeURIComponent(id)}`, ["/projects"]));
  4428. })
  4429. .post("/projects/bounties/complete/:id/:index", koaBody(), async (ctx) => {
  4430. if (!checkMod(ctx, 'projectsMod')) { ctx.redirect('/modules'); return; }
  4431. const id = await projectsModel.getProjectTipId(ctx.params.id);
  4432. await projectsModel.completeBounty(id, parseInt(ctx.params.index, 10), getViewerId());
  4433. ctx.redirect(safeReturnTo(ctx, `/projects/${encodeURIComponent(id)}`, ["/projects"]));
  4434. })
  4435. .post("/projects/:projectId/comments", koaBodyMiddleware, async ctx => commentAction(ctx, 'projects', 'projectId'))
  4436. .post("/banking/claim-ubi", koaBody(), async (ctx) => {
  4437. const userId = getViewerId();
  4438. try {
  4439. await bankingModel.claimUBI(userId);
  4440. ctx.redirect("/banking?filter=overview&msg=claimed_pending");
  4441. } catch (e) {
  4442. ctx.redirect(`/banking?filter=overview&msg=${encodeURIComponent(e.message || "error")}`);
  4443. }
  4444. })
  4445. .post("/banking/claim/:id", koaBody(), async (ctx) => {
  4446. const { i18n: _i18n } = require("../views/main_views");
  4447. const userId = getViewerId(), allocation = await bankingModel.getAllocationById(ctx.params.id);
  4448. if (!allocation) { ctx.body = { error: _i18n.errorNoAllocation }; return; }
  4449. if (allocation.to !== userId || (allocation.status !== "UNCLAIMED" && allocation.status !== "UNCONFIRMED")) { ctx.body = { error: _i18n.errorInvalidClaim }; return; }
  4450. if (!bankingModel.isPubNode()) {
  4451. ctx.redirect("/banking?filter=overview&msg=claimed_pending");
  4452. return;
  4453. }
  4454. const { txid } = await bankingModel.claimAllocation({ transferId: ctx.params.id, claimerId: userId });
  4455. await bankingModel.publishBankClaim({ amount: allocation.amount, epochId: allocation.concept, allocationId: allocation.id, txid });
  4456. ctx.redirect(`/banking?claimed=${encodeURIComponent(txid)}`);
  4457. })
  4458. .post("/banking/simulate", koaBody(), async (ctx) => {
  4459. if (!bankingModel.isPubNode()) { ctx.status = 403; ctx.body = { error: require("../views/main_views").i18n.bankPubOnly }; return; }
  4460. const { epochId, rules } = ctx.request.body || {};
  4461. ctx.body = await bankingModel.computeEpoch({ epochId, rules });
  4462. })
  4463. .post("/banking/run", koaBody(), async (ctx) => {
  4464. if (!bankingModel.isPubNode()) { ctx.status = 403; ctx.body = { error: require("../views/main_views").i18n.bankPubOnly }; return; }
  4465. const { epochId, rules } = ctx.request.body || {};
  4466. ctx.body = await bankingModel.executeEpoch({ epochId, rules });
  4467. })
  4468. .post("/banking/addresses", koaBody(), async (ctx) => {
  4469. const b = ctx.request.body || {}, res = await bankingModel.addAddress({ userId: (b.userId || "").trim(), address: (b.address || "").trim() });
  4470. ctx.redirect(`/banking?filter=addresses&msg=${encodeURIComponent(res.status)}`);
  4471. })
  4472. .post("/banking/addresses/delete", koaBody(), async (ctx) => {
  4473. const res = await bankingModel.removeAddress({ userId: getViewerId() });
  4474. ctx.redirect(`/banking?filter=addresses&msg=${encodeURIComponent(res.status)}`);
  4475. })
  4476. .post("/favorites/remove/:kind/:id", koaBody(), async (ctx) => {
  4477. await favoritesModel.removeFavorite(ctx.params.kind, ctx.params.id);
  4478. const fallback = `/favorites?filter=${encodeURIComponent(ctx.query.filter || "all")}`;
  4479. ctx.redirect(safeReturnTo(ctx, fallback, ["/favorites"]));
  4480. })
  4481. .post("/update", koaBody(), async (ctx) => {
  4482. const exec = require("node:util").promisify(require("node:child_process").exec);
  4483. const { stdout, stderr } = await exec("git reset --hard && git pull");
  4484. console.log("oasis@version: updating Oasis...", stdout, stderr);
  4485. const { stdout: shOut, stderr: shErr } = await exec("sh install.sh");
  4486. console.log("oasis@version: running install.sh...", shOut, shErr);
  4487. ctx.redirect(new URL(ctx.request.header.referer).href);
  4488. })
  4489. .post("/settings/theme", koaBody(), async (ctx) => {
  4490. const theme = String(ctx.request.body.theme || "").trim(), cfg = getConfig();
  4491. cfg.themes.current = theme || "Dark-SNH";
  4492. fs.writeFileSync(configPath, JSON.stringify(cfg, null, 2));
  4493. ctx.cookies.set("theme", cfg.themes.current, { httpOnly: true, sameSite: 'strict', secure: ctx.secure });
  4494. ctx.redirect("/settings");
  4495. })
  4496. .post("/language", koaBody(), async (ctx) => {
  4497. const lang = String(ctx.request.body.language || "en");
  4498. const cfg = getConfig();
  4499. cfg.language = lang;
  4500. fs.writeFileSync(configPath, JSON.stringify(cfg, null, 2));
  4501. ctx.cookies.set("language", lang, { maxAge: 365 * 24 * 60 * 60 * 1000, httpOnly: true, sameSite: 'strict', secure: ctx.secure });
  4502. ctx.redirect(new URL(ctx.request.header.referer).href);
  4503. })
  4504. .post("/settings/conn/start", koaBody(), async ctx => { await meta.connStart(); ctx.redirect("/peers"); })
  4505. .post("/settings/conn/stop", koaBody(), async ctx => { await meta.connStop(); ctx.redirect("/peers"); })
  4506. .post("/settings/conn/sync", koaBody(), async ctx => { await meta.sync(); ctx.redirect("/peers"); })
  4507. .post("/settings/conn/restart", koaBody(), async ctx => { await meta.connRestart(); ctx.redirect("/peers"); })
  4508. .post("/settings/invite/accept", koaBody(), async ctx => { await meta.acceptInvite(String(ctx.request.body.invite)); ctx.redirect("/invites"); })
  4509. .post("/settings/invite/unfollow", koaBody(), async (ctx) => {
  4510. const { key } = ctx.request.body || {};
  4511. if (!key) return ctx.redirect("/invites");
  4512. const pubs = readJSON(gossipPath), kcanon = canonicalKey(key);
  4513. const idx = pubs.findIndex(x => x && canonicalKey(x.key) === kcanon);
  4514. const removed = idx >= 0 ? (pubs.splice(idx, 1)[0], writeJSON(gossipPath, pubs), pubs[idx-1] !== undefined ? pubs.splice(idx,1)[0] : null) : null;
  4515. const ssb = await cooler.open(), addr = removed?.host ? msAddrFrom(removed.host, removed.port, removed.key) : null;
  4516. if (addr) { try { await new Promise(res => ssb.conn.disconnect(addr, res)); } catch {} try { ssb.conn.forget(addr); } catch {} }
  4517. try { await new Promise((res, rej) => ssb.publish({ type: "contact", contact: kcanon, following: false, blocking: true }, e => e ? rej(e) : res())); } catch {}
  4518. const unf = readJSON(unfollowedPath);
  4519. if (!unf.find(x => x && canonicalKey(x.key) === kcanon)) { unf.push(removed || { key: kcanon }); writeJSON(unfollowedPath, unf); }
  4520. ctx.redirect("/invites");
  4521. })
  4522. .post("/settings/invite/follow", koaBody(), async (ctx) => {
  4523. const { key, host, port } = ctx.request.body || {};
  4524. if (!key || !host) return ctx.redirect("/invites");
  4525. const pubs = readJSON(gossipPath), kcanon = canonicalKey(key);
  4526. if (pubs.find(p => p.host === host)?.error) return ctx.redirect("/invites");
  4527. const ssb = await cooler.open(), unf = readJSON(unfollowedPath);
  4528. const rec = unf.find(x => x && canonicalKey(x.key) === kcanon) || { host, port: Number(port) || 8008, key: kcanon };
  4529. if (!pubs.find(x => x && canonicalKey(x.key) === kcanon)) { pubs.push({ host: rec.host, port: Number(rec.port) || 8008, key: kcanon }); writeJSON(gossipPath, pubs); }
  4530. const addr = msAddrFrom(rec.host, rec.port, kcanon);
  4531. try { ssb.conn.remember(addr, { type: "pub", autoconnect: true, key: kcanon }); } catch {}
  4532. try { await new Promise(res => ssb.conn.connect(addr, { type: "pub" }, res)); } catch {}
  4533. try { await new Promise((res, rej) => ssb.publish({ type: "contact", contact: kcanon, blocking: false }, e => e ? rej(e) : res())); } catch {}
  4534. writeJSON(unfollowedPath, unf.filter(x => !(x && canonicalKey(x.key) === kcanon)));
  4535. ctx.redirect("/invites");
  4536. })
  4537. .post("/peers/connect", koaBody(), async (ctx) => {
  4538. const { key, host, port } = ctx.request.body || {};
  4539. if (!key || !host) return ctx.redirect("/peers?err=missing");
  4540. const hostStr = String(host).trim().toLowerCase();
  4541. const isIPv4 = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostStr);
  4542. const isHostname = /^[a-z0-9]([a-z0-9\-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9\-]*[a-z0-9])?)*$/.test(hostStr);
  4543. if ((!isIPv4 && !isHostname) || hostStr.length > 253) return ctx.redirect("/peers?err=invalidHost");
  4544. if (isIPv4 && hostStr.split('.').some(o => Number(o) > 255)) return ctx.redirect("/peers?err=invalidHost");
  4545. const prt = Number(port) || 8008;
  4546. if (!Number.isInteger(prt) || prt < 1 || prt > 65535) return ctx.redirect("/peers?err=invalidPort");
  4547. const keyStr = String(key).trim();
  4548. if (!/^@[A-Za-z0-9+/_\-]{43}=\.ed25519$/.test(keyStr)) return ctx.redirect("/peers?err=invalidKey");
  4549. const kcanon = canonicalKey(keyStr);
  4550. const pubs = readJSON(gossipPath);
  4551. if (!pubs.find(x => x && canonicalKey(x.key) === kcanon)) {
  4552. pubs.push({ host: hostStr, port: prt, key: kcanon });
  4553. writeJSON(gossipPath, pubs);
  4554. }
  4555. const ssb = await cooler.open();
  4556. const addr = msAddrFrom(hostStr, prt, kcanon);
  4557. try { ssb.conn.remember(addr, { type: "peer", autoconnect: true, key: kcanon }); } catch {}
  4558. try { await new Promise(res => ssb.conn.connect(addr, { type: "peer" }, res)); } catch {}
  4559. try { await new Promise((res, rej) => ssb.publish({ type: "contact", contact: kcanon, following: true }, e => e ? rej(e) : res())); } catch {}
  4560. const unf = readJSON(unfollowedPath);
  4561. writeJSON(unfollowedPath, unf.filter(x => !(x && canonicalKey(x.key) === kcanon)));
  4562. ctx.redirect("/peers");
  4563. })
  4564. .post("/settings/ssb-logstream", koaBody(), async (ctx) => {
  4565. const logLimit = parseInt(ctx.request.body.ssb_log_limit, 10);
  4566. if (!isNaN(logLimit) && logLimit > 0 && logLimit <= 100000) {
  4567. const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
  4568. config.ssbLogStream = { ...(config.ssbLogStream || {}), limit: logLimit };
  4569. fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
  4570. }
  4571. ctx.redirect("/settings");
  4572. })
  4573. .post("/settings/home-page", koaBody(), async (ctx) => {
  4574. const cfg = getConfig();
  4575. cfg.homePage = String(ctx.request.body.homePage || "").trim() || "activity";
  4576. saveConfig(cfg);
  4577. ctx.redirect("/settings");
  4578. })
  4579. .post("/inhabitants/follow/accept", koaBody(), async (ctx) => {
  4580. const b = ctx.request.body || {};
  4581. const followerId = String(b.followerId || '').trim();
  4582. if (!followerId) { ctx.redirect('/inhabitants?filter=pending'); return; }
  4583. if (viewerFilters.canAutoAcceptNow()) viewerFilters.markAutoAccept();
  4584. viewerFilters.addAccepted(followerId);
  4585. viewerFilters.removePending(followerId);
  4586. ctx.redirect('/inhabitants?filter=pending');
  4587. })
  4588. .post("/inhabitants/follow/reject", koaBody(), async (ctx) => {
  4589. const b = ctx.request.body || {};
  4590. const followerId = String(b.followerId || '').trim();
  4591. if (!followerId) { ctx.redirect('/inhabitants?filter=pending'); return; }
  4592. viewerFilters.removeAccepted(followerId);
  4593. viewerFilters.removePending(followerId);
  4594. ctx.redirect('/inhabitants?filter=pending');
  4595. })
  4596. .post("/settings/wish", koaBody(), async (ctx) => {
  4597. const cfg = getConfig();
  4598. const v = String(ctx.request.body.wish || '').trim();
  4599. cfg.wish = v === 'mutuals' ? 'mutuals' : 'whole';
  4600. saveConfig(cfg);
  4601. ctx.redirect("/settings");
  4602. })
  4603. .post("/settings/pm-visibility", koaBody(), async (ctx) => {
  4604. const cfg = getConfig();
  4605. const v = String(ctx.request.body.pmVisibility || '').trim();
  4606. cfg.pmVisibility = v === 'mutuals' ? 'mutuals' : 'whole';
  4607. saveConfig(cfg);
  4608. ctx.redirect("/settings");
  4609. })
  4610. .post("/settings/rebuild", async ctx => { meta.rebuild(); ctx.redirect("/settings"); })
  4611. .post("/modules/preset", koaBody(), async (ctx) => {
  4612. const ALL_MODULES = ['popular', 'topics', 'summaries', 'latest', 'threads', 'multiverse', 'invites', 'wallet', 'legacy', 'cipher', 'bookmarks', 'calendars', 'chats', 'videos', 'docs', 'audios', 'tags', 'images', 'maps', 'trending', 'events', 'tasks', 'market', 'tribes', 'votes', 'reports', 'opinions', 'pads', 'transfers', 'feed', 'pixelia', 'agenda', 'favorites', 'ai', 'forum', 'games', 'jobs', 'projects', 'shops', 'banking', 'parliament', 'courts', 'logs', 'torrents'];
  4613. const PRESETS = {
  4614. minimal: ['feed', 'forum', 'games', 'images', 'videos', 'audios', 'bookmarks', 'tags', 'trending', 'popular', 'latest', 'threads', 'opinions', 'cipher', 'legacy'],
  4615. social: ['agenda', 'audios', 'bookmarks', 'calendars', 'chats', 'cipher', 'courts', 'docs', 'events', 'favorites', 'feed', 'forum', 'games', 'images', 'invites', 'legacy', 'logs', 'maps', 'multiverse', 'opinions', 'pads', 'parliament', 'pixelia', 'projects', 'reports', 'tags', 'tasks', 'threads', 'trending', 'tribes', 'videos', 'votes'],
  4616. economy: ['agenda', 'audios', 'bookmarks', 'calendars', 'chats', 'cipher', 'courts', 'docs', 'events', 'favorites', 'feed', 'forum', 'games', 'images', 'invites', 'legacy', 'logs', 'maps', 'multiverse', 'opinions', 'pads', 'parliament', 'pixelia', 'projects', 'reports', 'tags', 'tasks', 'threads', 'trending', 'tribes', 'videos', 'votes', 'banking', 'wallet', 'transfers', 'market', 'jobs', 'shops'],
  4617. full: ALL_MODULES
  4618. };
  4619. const preset = String(ctx.request.body.preset || '');
  4620. const enabledMods = PRESETS[preset];
  4621. if (!enabledMods) { ctx.redirect('/modules'); return; }
  4622. const cfg = getConfig();
  4623. ALL_MODULES.forEach(mod => cfg.modules[`${mod}Mod`] = enabledMods.includes(mod) ? 'on' : 'off');
  4624. saveConfig(cfg);
  4625. ctx.redirect('/modules');
  4626. })
  4627. .post("/save-modules", koaBody(), async (ctx) => {
  4628. const modules = ['popular', 'topics', 'summaries', 'latest', 'threads', 'multiverse', 'invites', 'wallet', 'legacy', 'cipher', 'bookmarks', 'calendars', 'chats', 'videos', 'docs', 'audios', 'tags', 'images', 'maps', 'trending', 'events', 'tasks', 'market', 'tribes', 'votes', 'reports', 'opinions', 'pads', 'transfers', 'feed', 'pixelia', 'agenda', 'favorites', 'ai', 'forum', 'games', 'jobs', 'projects', 'shops', 'banking', 'parliament', 'courts', 'logs', 'torrents'];
  4629. const cfg = getConfig();
  4630. modules.forEach(mod => cfg.modules[`${mod}Mod`] = ctx.request.body[`${mod}Form`] === 'on' ? 'on' : 'off');
  4631. saveConfig(cfg);
  4632. ctx.redirect(`/modules`);
  4633. })
  4634. .post("/settings/ai", koaBody(), async (ctx) => {
  4635. const aiPrompt = String(ctx.request.body.ai_prompt || "").trim();
  4636. if (aiPrompt.length > 128) { ctx.status = 400; ctx.body = "Prompt too long. Must be 128 characters or fewer."; return; }
  4637. const cfg = getConfig();
  4638. cfg.ai = { ...(cfg.ai || {}), prompt: aiPrompt };
  4639. saveConfig(cfg);
  4640. ctx.redirect("/settings");
  4641. })
  4642. .post("/settings/pub-id", koaBody(), async (ctx) => {
  4643. const b = ctx.request.body, cfg = getConfig();
  4644. cfg.walletPub = { pubId: String(b.pub_id || "").trim() };
  4645. saveConfig(cfg);
  4646. ctx.redirect("/settings");
  4647. })
  4648. .post('/transfers/create', koaBody(), async ctx => {
  4649. if (!checkMod(ctx, 'transfersMod')) { ctx.redirect('/modules'); return; }
  4650. const b = ctx.request.body;
  4651. await transfersModel.createTransfer(b.to, b.concept, b.amount, b.deadline, b.tags);
  4652. ctx.redirect(safeReturnTo(ctx, '/transfers?filter=all', ['/transfers']));
  4653. })
  4654. .post('/transfers/update/:id', koaBody(), async ctx => {
  4655. if (!checkMod(ctx, 'transfersMod')) { ctx.redirect('/modules'); return; }
  4656. const b = ctx.request.body;
  4657. await transfersModel.updateTransferById(ctx.params.id, b.to, b.concept, b.amount, b.deadline, b.tags);
  4658. ctx.redirect(safeReturnTo(ctx, '/transfers?filter=mine', ['/transfers']));
  4659. })
  4660. .post('/transfers/confirm/:id', koaBody(), async ctx => {
  4661. if (!checkMod(ctx, 'transfersMod')) { ctx.redirect('/modules'); return; }
  4662. await transfersModel.confirmTransferById(ctx.params.id);
  4663. ctx.redirect(safeReturnTo(ctx, '/transfers', ['/transfers']));
  4664. })
  4665. .post('/transfers/delete/:id', koaBody(), async ctx => {
  4666. if (!checkMod(ctx, 'transfersMod')) { ctx.redirect('/modules'); return; }
  4667. await transfersModel.deleteTransferById(ctx.params.id);
  4668. ctx.redirect(safeReturnTo(ctx, '/transfers?filter=mine', ['/transfers']));
  4669. })
  4670. .post('/transfers/opinions/:transferId/:category', koaBody(), async ctx => {
  4671. if (!checkMod(ctx, 'transfersMod')) { ctx.redirect('/modules'); return; }
  4672. await transfersModel.createOpinion(ctx.params.transferId, ctx.params.category);
  4673. ctx.redirect(safeReturnTo(ctx, '/transfers', ['/transfers']));
  4674. })
  4675. .post("/settings/wallet", koaBody(), async (ctx) => {
  4676. const b = ctx.request.body, cfg = getConfig();
  4677. if (b.wallet_url) cfg.wallet.url = String(b.wallet_url);
  4678. if (b.wallet_user) cfg.wallet.user = String(b.wallet_user);
  4679. if (b.wallet_pass) cfg.wallet.pass = String(b.wallet_pass);
  4680. if (b.wallet_fee) cfg.wallet.fee = String(b.wallet_fee);
  4681. saveConfig(cfg);
  4682. const res = await bankingModel.ensureSelfAddressPublished();
  4683. ctx.redirect(`/banking?filter=addresses&msg=${encodeURIComponent(res.status)}`);
  4684. })
  4685. .post("/wallet/send", koaBody(), async (ctx) => {
  4686. const b = ctx.request.body, action = String(b.action), dest = String(b.destination), amt = Number(b.amount), fee = Number(b.fee);
  4687. const { url, user, pass } = getConfig().wallet;
  4688. let balance = null;
  4689. try { balance = await walletModel.getBalance(url, user, pass); } catch (error) { ctx.body = await walletErrorView(error); return; }
  4690. if (action === 'confirm') {
  4691. const v = await walletModel.validateSend(url, user, pass, dest, amt, fee);
  4692. try { ctx.body = v.isValid ? await walletSendConfirmView(balance, dest, amt, fee) : await walletSendFormView(balance, dest, amt, fee, { type: 'error', title: 'validation_errors', messages: v.errors }); }
  4693. catch (error) { ctx.body = await walletErrorView(error); }
  4694. } else if (action === 'send') {
  4695. try { ctx.body = await walletSendResultView(balance, dest, amt, await walletModel.sendToAddress(url, user, pass, dest, amt)); }
  4696. catch (error) { ctx.body = await walletErrorView(error); }
  4697. }
  4698. });
  4699. const routes = router.routes();
  4700. const middleware = [
  4701. async (ctx, next) => {
  4702. if (config.public && ctx.method !== "GET") throw new Error("Sorry, many actions are unavailable when Oasis is running in public mode. Please run Oasis in the default mode and try again.");
  4703. await next();
  4704. },
  4705. async (ctx, next) => { setLanguage(ctx.cookies.get("language") || getConfig().language || "en"); await next(); },
  4706. async (ctx, next) => {
  4707. const ssb = await cooler.open(), status = await ssb.status(), values = Object.values(status.sync.plugins);
  4708. const totalCurrent = values.reduce((acc, cur) => acc + cur, 0), totalTarget = status.sync.since * values.length;
  4709. if (totalTarget - totalCurrent > 1024 * 1024) ctx.response.body = indexingView({ percent: Math.floor((totalCurrent / totalTarget) * 1000) / 10 });
  4710. else { try { await next(); } catch (err) {
  4711. if (err.name === 'FileTooLargeError' || (err.message && err.message.includes('maxFileSize'))) {
  4712. const { template, i18n } = require('../views/main_views');
  4713. const referer = ctx.get('referer') || '/';
  4714. ctx.status = 413;
  4715. ctx.body = template(
  4716. i18n.fileTooLargeTitle,
  4717. section(
  4718. div({ class: 'tags-header' },
  4719. h2(i18n.fileTooLargeTitle),
  4720. p(i18n.fileTooLargeMessage),
  4721. p(a({ href: referer, class: 'filter-btn', style: 'display:inline-block;text-decoration:none;margin-top:16px;' }, i18n.goBack))
  4722. )
  4723. )
  4724. );
  4725. } else {
  4726. ctx.status = err.status || 500; ctx.body = { message: err.message || 'Internal Server Error' };
  4727. }
  4728. } }
  4729. },
  4730. async (ctx, next) => {
  4731. if (!ctx.path.startsWith('/assets/') && !ctx.path.startsWith('/image/') && !ctx.path.startsWith('/blob/')) {
  4732. const now = Date.now();
  4733. if (now - sharedState.getLastRefresh() > 60000) {
  4734. sharedState.setLastRefresh(now);
  4735. try {
  4736. const stats = await statsModel.getStats('ALL');
  4737. const totalMB = parseSizeMB(stats.statsBlobsSize) + parseSizeMB(stats.statsBlockchainSize);
  4738. const hcT = parseFloat((totalMB * 0.0002 * 475).toFixed(2));
  4739. const inhabitants = stats.usersKPIs?.totalInhabitants || stats.inhabitants || 1;
  4740. const hcH = inhabitants > 0 ? parseFloat((hcT / inhabitants).toFixed(2)) : 0;
  4741. sharedState.setCarbonHcT(hcT);
  4742. sharedState.setCarbonHcH(hcH);
  4743. } catch (_) {}
  4744. try { await refreshInboxCount(); } catch (_) {}
  4745. try { await calendarsModel.checkDueReminders(); } catch (_) {}
  4746. }
  4747. }
  4748. await next();
  4749. },
  4750. routes,
  4751. ];
  4752. const app = http({ host, port, middleware, allowHost: config.allowHost });
  4753. let pubEngineTimer = null;
  4754. async function runPubEngineTick() {
  4755. if (!bankingModel.isPubNode()) return;
  4756. try { await bankingModel.executeEpoch({}); } catch (_) {}
  4757. try { await bankingModel.processPendingClaims(); } catch (_) {}
  4758. try { await bankingModel.publishPubAvailability(); } catch (_) {}
  4759. }
  4760. if (bankingModel.isPubNode()) {
  4761. setTimeout(() => { runPubEngineTick(); }, 15000);
  4762. pubEngineTimer = setInterval(runPubEngineTick, 30 * 60 * 1000);
  4763. }
  4764. app._close = () => {
  4765. if (pubEngineTimer) clearInterval(pubEngineTimer);
  4766. nameWarmup.close();
  4767. cooler.close();
  4768. };
  4769. module.exports = app;
  4770. if (config.open === true) open(url);