ita_plugin.py 256 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286
  1. """Prenot@Mi plugin: one uploadable runtime file.
  2. Sections below were mechanically relocated from commit 62c2388.
  3. Maintain this file directly; tools/consolidate_ita_plugin.py is an audit
  4. of the initial move, not a build step. Shared host APIs remain shared.
  5. """
  6. from __future__ import annotations
  7. # ============================================================================
  8. # PROTOCOL (from plugins/ita_protocol.py)
  9. # ============================================================================
  10. """Pure Prenot@Mi protocol parsing and precommit validation.
  11. This module is the functional core of the Italy plugin. It deliberately owns
  12. no browser, network, session, OTP, or form-submission behavior. Callers pass
  13. already-captured, sanitized data in and receive immutable value objects back.
  14. """
  15. import json
  16. import html
  17. import re
  18. from dataclasses import dataclass, field
  19. from datetime import date, datetime, time as datetime_time
  20. from enum import Enum
  21. from typing import Any, Mapping, Sequence
  22. MAX_PROTOCOL_ITEMS = 512
  23. MAX_PROTOCOL_PAYLOAD_CHARS = 1_000_000
  24. MAX_LOOKAHEAD_MONTHS = 120
  25. _SITE_DATE_PATTERN = re.compile(r"^\d{2}/\d{2}/\d{4} 00:00:00$")
  26. PRENOTAMI_OTP_SENDER = "noreply-prenotami@esteri.it"
  27. _EMAIL_PATTERN = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
  28. _OTP_CONTEXT_PATTERN = re.compile(
  29. r"(?<!\w)OTP\s+Code\s*:\s*([0-9]{6})(?!\w)",
  30. re.IGNORECASE,
  31. )
  32. class ItaProtocolError(ValueError):
  33. """Fail-closed protocol error with a stable, non-sensitive category."""
  34. def __init__(self, code: str, message: str, *, path: str = "") -> None:
  35. self.code = code
  36. self.path = path
  37. location = f" at {path}" if path else ""
  38. super().__init__(f"Italy protocol error [{code}]{location}: {message}")
  39. class ItaCapability(str, Enum):
  40. SERVICES_PROBE_ONLY = "services_probe_only"
  41. SINGLE_SCHENGEN_TOURISM = "single_schengen_tourism"
  42. class InventoryState(str, Enum):
  43. AVAILABLE = "available"
  44. UNAVAILABLE = "unavailable"
  45. @dataclass(frozen=True, slots=True)
  46. class CalendarScanConfig:
  47. lookahead_months: int
  48. @dataclass(frozen=True, slots=True)
  49. class FormControlConfig:
  50. control_id: str
  51. value: str
  52. labels: tuple[str, ...]
  53. @dataclass(frozen=True, slots=True)
  54. class OtpMailConfig:
  55. """Allowlisted cloud-mail query settings for one Italy route.
  56. The authorization mailbox is configured explicitly or derived per call
  57. from the current account, never cached on a shared route or included in
  58. diagnostic objects or log messages. The sender is
  59. fixed to Prenot@Mi's observed official address; a route may not widen the
  60. allowlist through configuration.
  61. """
  62. authorization_email: str | None = field(default=None, repr=False)
  63. subject_keywords: str = "OTP Code"
  64. body_keywords: str = "OTP Code:"
  65. expiry_seconds: int = 300
  66. authorization_source: str = "configured"
  67. def __post_init__(self) -> None:
  68. if self.authorization_source not in ("configured", "account"):
  69. raise ItaProtocolError(
  70. "otp_authorization_source_invalid",
  71. "authorization source must be configured or account",
  72. path="mail.authorization_source",
  73. )
  74. if self.authorization_source == "account":
  75. if self.authorization_email is not None:
  76. raise ItaProtocolError(
  77. "otp_authorization_source_conflict",
  78. "account source cannot also specify a fixed authorization mailbox",
  79. path="mail.authorization_email",
  80. )
  81. else:
  82. object.__setattr__(self, "authorization_email", self._require_mailbox(self.authorization_email))
  83. for field_name, expected in (("subject_keywords", "OTP Code"), ("body_keywords", "OTP Code:")):
  84. value = getattr(self, field_name)
  85. if not isinstance(value, str) or value.strip() != expected:
  86. raise ItaProtocolError(
  87. "otp_filter_invalid",
  88. "mail filters must match the observed Prenot@Mi OTP template",
  89. path=f"mail.{field_name}",
  90. )
  91. object.__setattr__(self, field_name, value.strip())
  92. if (
  93. not isinstance(self.expiry_seconds, int)
  94. or isinstance(self.expiry_seconds, bool)
  95. or not 1 <= self.expiry_seconds <= 300
  96. ):
  97. raise ItaProtocolError(
  98. "otp_expiry_invalid",
  99. "mail expiry must be an integer between 1 and 300 seconds",
  100. path="mail.expiry_seconds",
  101. )
  102. @staticmethod
  103. def _require_mailbox(value: Any) -> str:
  104. if not isinstance(value, str) or not _EMAIL_PATTERN.fullmatch(value.strip()):
  105. raise ItaProtocolError(
  106. "otp_authorization_email_invalid",
  107. "authorization mailbox must be a valid email address",
  108. path="mail.authorization_email",
  109. )
  110. return value.strip()
  111. def mailbox_for(self, account_email: str) -> str:
  112. """Bind per call; never mutate the route shared by pool instances.
  113. Account mode requires that each account's own inbox has an existing
  114. backend authorization. Configured mode preserves shared/forwarded
  115. inbox support; recipient filtering remains bound to the site account.
  116. """
  117. return self._require_mailbox(
  118. account_email if self.authorization_source == "account" else self.authorization_email
  119. )
  120. @dataclass(frozen=True, slots=True)
  121. class ItaRouteConfig:
  122. routing_key: str
  123. service_id: int
  124. capability: ItaCapability
  125. calendar_scan: CalendarScanConfig | None = None
  126. booking_type: FormControlConfig | None = None
  127. purpose: FormControlConfig | None = None
  128. mail: OtpMailConfig | None = None
  129. @dataclass(frozen=True, slots=True)
  130. class CalendarDay:
  131. day: date
  132. slots_free: int
  133. slots_remaining: int
  134. state: InventoryState
  135. def __post_init__(self) -> None:
  136. _require_date(self.day, "CalendarDay.day")
  137. slots_free = _require_int(self.slots_free, "CalendarDay.slots_free")
  138. slots_remaining = _require_int(
  139. self.slots_remaining,
  140. "CalendarDay.slots_remaining",
  141. )
  142. expected_state = _classify_inventory(
  143. slots_free,
  144. slots_remaining,
  145. path="CalendarDay",
  146. )
  147. if self.state is not expected_state:
  148. raise ItaProtocolError(
  149. "inventory_state_mismatch",
  150. "declared state differs from the slot counters",
  151. path="CalendarDay.state",
  152. )
  153. @property
  154. def is_available(self) -> bool:
  155. return self.state is InventoryState.AVAILABLE
  156. @dataclass(frozen=True, slots=True)
  157. class SlotCandidate:
  158. day: date
  159. start_time: datetime_time
  160. end_time: datetime_time
  161. slots_free: int
  162. slots_remaining: int
  163. state: InventoryState
  164. daily_calendar_id: str = field(repr=False)
  165. def __post_init__(self) -> None:
  166. _require_date(self.day, "SlotCandidate.day")
  167. start = _require_time(self.start_time, "SlotCandidate.start_time")
  168. end = _require_time(self.end_time, "SlotCandidate.end_time")
  169. if start >= end:
  170. raise ItaProtocolError(
  171. "time_range_invalid",
  172. "slot start time must be earlier than end time",
  173. path="SlotCandidate",
  174. )
  175. slots_free = _require_int(
  176. self.slots_free,
  177. "SlotCandidate.slots_free",
  178. )
  179. slots_remaining = _require_int(
  180. self.slots_remaining,
  181. "SlotCandidate.slots_remaining",
  182. )
  183. expected_state = _classify_inventory(
  184. slots_free,
  185. slots_remaining,
  186. path="SlotCandidate",
  187. )
  188. if self.state is not expected_state:
  189. raise ItaProtocolError(
  190. "inventory_state_mismatch",
  191. "declared state differs from the slot counters",
  192. path="SlotCandidate.state",
  193. )
  194. if (
  195. not isinstance(self.daily_calendar_id, str)
  196. or not self.daily_calendar_id.isdigit()
  197. or int(self.daily_calendar_id) <= 0
  198. ):
  199. raise ItaProtocolError(
  200. "daily_id_invalid",
  201. "runtime daily identifier must be a positive integer string",
  202. path="SlotCandidate.daily_calendar_id",
  203. )
  204. @property
  205. def is_available(self) -> bool:
  206. return self.state is InventoryState.AVAILABLE
  207. @property
  208. def time_label(self) -> str:
  209. return (
  210. f"{self.start_time.strftime('%H:%M')} - "
  211. f"{self.end_time.strftime('%H:%M')}"
  212. )
  213. @dataclass(frozen=True, slots=True)
  214. class DateSelectionState:
  215. planned_day: date
  216. matching_availability_count: int
  217. timeline_selected_days: tuple[date, ...]
  218. content_selected_days: tuple[date, ...]
  219. day_disabled: bool
  220. day_not_available: bool
  221. day_has_positive_state: bool
  222. def __post_init__(self) -> None:
  223. _require_date(self.planned_day, "DateSelectionState.planned_day")
  224. _require_nonnegative_int(
  225. self.matching_availability_count,
  226. "DateSelectionState.matching_availability_count",
  227. )
  228. _require_date_tuple(
  229. self.timeline_selected_days,
  230. "DateSelectionState.timeline_selected_days",
  231. )
  232. _require_date_tuple(
  233. self.content_selected_days,
  234. "DateSelectionState.content_selected_days",
  235. )
  236. for field_name in (
  237. "day_disabled",
  238. "day_not_available",
  239. "day_has_positive_state",
  240. ):
  241. _require_bool(
  242. getattr(self, field_name),
  243. f"DateSelectionState.{field_name}",
  244. )
  245. @dataclass(frozen=True, slots=True)
  246. class SlotSelectionState:
  247. active_slot_count: int
  248. active_is_candidate: bool
  249. active_has_unavailable_class: bool
  250. active_has_red_dot: bool
  251. active_hidden_input_count: int
  252. active_daily_id_matches_candidate: bool
  253. active_day_matches_candidate: bool
  254. active_time_matches_candidate: bool
  255. active_capacity_matches_candidate: bool
  256. def __post_init__(self) -> None:
  257. for field_name in (
  258. "active_slot_count",
  259. "active_hidden_input_count",
  260. ):
  261. _require_nonnegative_int(
  262. getattr(self, field_name),
  263. f"SlotSelectionState.{field_name}",
  264. )
  265. for field_name in (
  266. "active_is_candidate",
  267. "active_has_unavailable_class",
  268. "active_has_red_dot",
  269. "active_daily_id_matches_candidate",
  270. "active_day_matches_candidate",
  271. "active_time_matches_candidate",
  272. "active_capacity_matches_candidate",
  273. ):
  274. _require_bool(
  275. getattr(self, field_name),
  276. f"SlotSelectionState.{field_name}",
  277. )
  278. @dataclass(frozen=True, slots=True)
  279. class PrecommitApproval:
  280. """Immutable value returned by :func:`approve_precommit`."""
  281. calendar_day: CalendarDay
  282. candidate: SlotCandidate
  283. def resolve_route_config(
  284. apt_configs: Mapping[str, Any],
  285. routing_key: str,
  286. ) -> ItaRouteConfig:
  287. """Resolve one VFS/BLS-style ``apt_configs[routing_key]`` entry."""
  288. configs = _require_mapping(apt_configs, "apt_configs")
  289. key = _require_nonempty_string(routing_key, "routing_key")
  290. if key not in configs:
  291. raise ItaProtocolError(
  292. "route_missing",
  293. "no route is configured for the requested routing key",
  294. path="apt_configs",
  295. )
  296. raw_route = _require_mapping(configs[key], f"apt_configs.{key}")
  297. service_id = _require_positive_int(
  298. raw_route.get("service_id"),
  299. f"apt_configs.{key}.service_id",
  300. )
  301. raw_capability = _require_nonempty_string(
  302. raw_route.get("capability"),
  303. f"apt_configs.{key}.capability",
  304. )
  305. try:
  306. capability = ItaCapability(raw_capability)
  307. except ValueError as exc:
  308. raise ItaProtocolError(
  309. "capability_unsupported",
  310. "route capability is not supported",
  311. path=f"apt_configs.{key}.capability",
  312. ) from exc
  313. if capability is ItaCapability.SERVICES_PROBE_ONLY:
  314. return ItaRouteConfig(
  315. routing_key=key,
  316. service_id=service_id,
  317. capability=capability,
  318. )
  319. calendar_scan_raw = _require_mapping(
  320. raw_route.get("calendar_scan"),
  321. f"apt_configs.{key}.calendar_scan",
  322. )
  323. calendar_scan = CalendarScanConfig(
  324. lookahead_months=_require_lookahead_months(
  325. calendar_scan_raw.get("lookahead_months"),
  326. f"apt_configs.{key}.calendar_scan.lookahead_months",
  327. )
  328. )
  329. form_raw = _require_mapping(
  330. raw_route.get("form"),
  331. f"apt_configs.{key}.form",
  332. )
  333. booking_type = _parse_form_control(
  334. form_raw,
  335. prefix="booking_type",
  336. path=f"apt_configs.{key}.form",
  337. )
  338. purpose = _parse_form_control(
  339. form_raw,
  340. prefix="purpose",
  341. path=f"apt_configs.{key}.form",
  342. )
  343. mail = _parse_mail_config(
  344. raw_route.get("mail"),
  345. path=f"apt_configs.{key}.mail",
  346. )
  347. return ItaRouteConfig(
  348. routing_key=key,
  349. service_id=service_id,
  350. capability=capability,
  351. calendar_scan=calendar_scan,
  352. booking_type=booking_type,
  353. purpose=purpose,
  354. mail=mail,
  355. )
  356. def decode_double_json_array(
  357. payload: str,
  358. *,
  359. max_items: int = MAX_PROTOCOL_ITEMS,
  360. ) -> tuple[Mapping[str, Any], ...]:
  361. """Strictly decode the JSON-string-containing-a-JSON-array wire shape."""
  362. if not isinstance(payload, str) or not payload:
  363. raise ItaProtocolError(
  364. "payload_type",
  365. "payload must be a non-empty JSON string",
  366. )
  367. if len(payload) > MAX_PROTOCOL_PAYLOAD_CHARS:
  368. raise ItaProtocolError(
  369. "payload_too_large",
  370. "payload exceeds the local parsing limit",
  371. )
  372. if not _is_positive_int(max_items):
  373. raise ItaProtocolError(
  374. "max_items_invalid",
  375. "max_items must be a positive integer",
  376. )
  377. try:
  378. outer = json.loads(payload)
  379. except (TypeError, json.JSONDecodeError) as exc:
  380. raise ItaProtocolError(
  381. "outer_json_invalid",
  382. "outer JSON cannot be decoded",
  383. ) from exc
  384. if not isinstance(outer, str):
  385. raise ItaProtocolError(
  386. "payload_layer_count",
  387. "payload must contain exactly two JSON layers",
  388. )
  389. if len(outer) > MAX_PROTOCOL_PAYLOAD_CHARS:
  390. raise ItaProtocolError(
  391. "payload_too_large",
  392. "inner payload exceeds the local parsing limit",
  393. )
  394. try:
  395. items = json.loads(outer)
  396. except (TypeError, json.JSONDecodeError) as exc:
  397. raise ItaProtocolError(
  398. "inner_json_invalid",
  399. "inner JSON cannot be decoded",
  400. ) from exc
  401. if not isinstance(items, list):
  402. raise ItaProtocolError(
  403. "payload_layer_count",
  404. "inner JSON must be an array",
  405. )
  406. if len(items) > max_items:
  407. raise ItaProtocolError(
  408. "item_limit_exceeded",
  409. "response contains more items than the configured parsing limit",
  410. )
  411. result: list[Mapping[str, Any]] = []
  412. for index, item in enumerate(items):
  413. if not isinstance(item, Mapping):
  414. raise ItaProtocolError(
  415. "item_type",
  416. "every response item must be an object",
  417. path=f"items[{index}]",
  418. )
  419. result.append(item)
  420. return tuple(result)
  421. def parse_calendar_availability(
  422. payload: str,
  423. *,
  424. max_items: int = MAX_PROTOCOL_ITEMS,
  425. ) -> tuple[CalendarDay, ...]:
  426. """Parse and classify calendar-day capacity without guessing conflicts."""
  427. items = decode_double_json_array(payload, max_items=max_items)
  428. days: list[CalendarDay] = []
  429. seen_days: set[date] = set()
  430. for index, item in enumerate(items):
  431. path = f"availability[{index}]"
  432. parsed_day = _parse_site_date(
  433. _require_key(item, "DateLibere", path),
  434. f"{path}.DateLibere",
  435. )
  436. if parsed_day in seen_days:
  437. raise ItaProtocolError(
  438. "duplicate_calendar_day",
  439. "calendar response contains a duplicate date",
  440. path=path,
  441. )
  442. seen_days.add(parsed_day)
  443. slots_free = _require_int(
  444. _require_key(item, "SlotLiberi", path),
  445. f"{path}.SlotLiberi",
  446. )
  447. slots_remaining = _require_int(
  448. _require_key(item, "SlotRimanenti", path),
  449. f"{path}.SlotRimanenti",
  450. )
  451. state = _classify_inventory(
  452. slots_free,
  453. slots_remaining,
  454. path=path,
  455. )
  456. days.append(
  457. CalendarDay(
  458. day=parsed_day,
  459. slots_free=slots_free,
  460. slots_remaining=slots_remaining,
  461. state=state,
  462. )
  463. )
  464. return tuple(sorted(days, key=lambda item: item.day))
  465. def parse_time_slots(
  466. payload: str,
  467. *,
  468. max_items: int = MAX_PROTOCOL_ITEMS,
  469. ) -> tuple[SlotCandidate, ...]:
  470. """Parse TimeSlots items while keeping the runtime ID memory-only."""
  471. items = decode_double_json_array(payload, max_items=max_items)
  472. candidates: list[SlotCandidate] = []
  473. seen_ranges: set[tuple[date, datetime_time, datetime_time]] = set()
  474. seen_daily_ids: set[str] = set()
  475. for index, item in enumerate(items):
  476. path = f"time_slots[{index}]"
  477. parsed_day = _parse_site_date(
  478. _require_key(item, "Data", path),
  479. f"{path}.Data",
  480. )
  481. start_time = _parse_site_time(
  482. _require_key(item, "OrarioInizioFascia", path),
  483. f"{path}.OrarioInizioFascia",
  484. )
  485. end_time = _parse_site_time(
  486. _require_key(item, "OrarioFineFascia", path),
  487. f"{path}.OrarioFineFascia",
  488. )
  489. if start_time >= end_time:
  490. raise ItaProtocolError(
  491. "time_range_invalid",
  492. "slot start time must be earlier than end time",
  493. path=path,
  494. )
  495. slots_free = _require_int(
  496. _require_key(item, "SlotLiberi", path),
  497. f"{path}.SlotLiberi",
  498. )
  499. slots_remaining = _require_int(
  500. _require_key(item, "SlotRimanenti", path),
  501. f"{path}.SlotRimanenti",
  502. )
  503. state = _classify_inventory(
  504. slots_free,
  505. slots_remaining,
  506. path=path,
  507. )
  508. daily_id = str(
  509. _require_positive_int(
  510. _require_key(item, "IDCalendarioServizioGiornaliero", path),
  511. f"{path}.IDCalendarioServizioGiornaliero",
  512. )
  513. )
  514. time_range = (parsed_day, start_time, end_time)
  515. if time_range in seen_ranges:
  516. raise ItaProtocolError(
  517. "duplicate_time_range",
  518. "time-slot response contains a duplicate time range",
  519. path=path,
  520. )
  521. if daily_id in seen_daily_ids:
  522. raise ItaProtocolError(
  523. "duplicate_daily_id",
  524. "time-slot response reuses a runtime daily identifier",
  525. path=path,
  526. )
  527. seen_ranges.add(time_range)
  528. seen_daily_ids.add(daily_id)
  529. candidates.append(
  530. SlotCandidate(
  531. day=parsed_day,
  532. start_time=start_time,
  533. end_time=end_time,
  534. slots_free=slots_free,
  535. slots_remaining=slots_remaining,
  536. state=state,
  537. daily_calendar_id=daily_id,
  538. )
  539. )
  540. return tuple(
  541. sorted(
  542. candidates,
  543. key=lambda item: (item.day, item.start_time, item.end_time),
  544. )
  545. )
  546. def available_calendar_days(
  547. days: Sequence[CalendarDay],
  548. *,
  549. start_day: date | None = None,
  550. end_day: date | None = None,
  551. ) -> tuple[CalendarDay, ...]:
  552. """Return positive days in an inclusive date range, sorted ascending."""
  553. start, end = _validate_date_range(start_day, end_day)
  554. seen: set[date] = set()
  555. selected: list[CalendarDay] = []
  556. for index, item in enumerate(days):
  557. if not isinstance(item, CalendarDay):
  558. raise ItaProtocolError(
  559. "calendar_day_type",
  560. "days must contain CalendarDay values",
  561. path=f"days[{index}]",
  562. )
  563. if item.day in seen:
  564. raise ItaProtocolError(
  565. "duplicate_calendar_day",
  566. "days contain a duplicate date",
  567. path=f"days[{index}]",
  568. )
  569. seen.add(item.day)
  570. if item.is_available and _date_in_range(item.day, start, end):
  571. selected.append(item)
  572. return tuple(sorted(selected, key=lambda item: item.day))
  573. def available_slot_candidates(
  574. candidates: Sequence[SlotCandidate],
  575. *,
  576. start_day: date | None = None,
  577. end_day: date | None = None,
  578. ) -> tuple[SlotCandidate, ...]:
  579. """Filter and deterministically order positive Book-side candidates."""
  580. start, end = _validate_date_range(start_day, end_day)
  581. seen_ranges: set[tuple[date, datetime_time, datetime_time]] = set()
  582. selected: list[SlotCandidate] = []
  583. for index, item in enumerate(candidates):
  584. if not isinstance(item, SlotCandidate):
  585. raise ItaProtocolError(
  586. "slot_candidate_type",
  587. "candidates must contain SlotCandidate values",
  588. path=f"candidates[{index}]",
  589. )
  590. identity = (item.day, item.start_time, item.end_time)
  591. if identity in seen_ranges:
  592. raise ItaProtocolError(
  593. "duplicate_time_range",
  594. "candidates contain a duplicate time range",
  595. path=f"candidates[{index}]",
  596. )
  597. seen_ranges.add(identity)
  598. if item.is_available and _date_in_range(item.day, start, end):
  599. selected.append(item)
  600. return tuple(
  601. sorted(
  602. selected,
  603. key=lambda item: (
  604. item.day,
  605. -item.slots_free,
  606. item.start_time,
  607. item.end_time,
  608. ),
  609. )
  610. )
  611. def parse_otp_body(
  612. body: str,
  613. *,
  614. max_chars: int = MAX_PROTOCOL_PAYLOAD_CHARS,
  615. ) -> str:
  616. """Extract exactly one Prenot@Mi OTP from a cloud-mail body.
  617. The cloud endpoint returns a body-only string and may include both the
  618. plain-text and HTML MIME alternatives. HTML tags are replaced with
  619. spaces, then only the observed ``OTP Code:`` marker followed by six ASCII
  620. digits is accepted. Repeated identical matches (plain + HTML) are fine;
  621. different candidates fail closed. No caller should log ``body`` or the
  622. returned code.
  623. """
  624. if not isinstance(body, str) or not body.strip():
  625. raise ItaProtocolError(
  626. "otp_body_invalid",
  627. "OTP mail body must be a non-empty string",
  628. path="mail.body",
  629. )
  630. if not isinstance(max_chars, int) or isinstance(max_chars, bool) or max_chars <= 0:
  631. raise ItaProtocolError(
  632. "otp_body_limit_invalid",
  633. "OTP body limit must be a positive integer",
  634. path="mail.max_chars",
  635. )
  636. if len(body) > max_chars:
  637. raise ItaProtocolError(
  638. "otp_body_too_large",
  639. "OTP mail body exceeds the local parsing limit",
  640. path="mail.body",
  641. )
  642. # The existing cloud service can concatenate text/plain and text/html.
  643. # Projecting HTML to text avoids depending on a browser or executing any
  644. # markup while preserving the marker when tags surround the code.
  645. projected = html.unescape(re.sub(r"<[^>]{0,4096}>", " ", body))
  646. projected = re.sub(r"\s+", " ", projected).strip()
  647. matches = _OTP_CONTEXT_PATTERN.findall(projected)
  648. unique = tuple(dict.fromkeys(matches))
  649. if not unique:
  650. raise ItaProtocolError(
  651. "otp_not_found",
  652. "mail body did not contain the expected OTP marker",
  653. path="mail.body",
  654. )
  655. if len(unique) != 1:
  656. raise ItaProtocolError(
  657. "otp_ambiguous",
  658. "mail body contained multiple different OTP candidates",
  659. path="mail.body",
  660. )
  661. return unique[0]
  662. def month_starts(anchor_day: date, lookahead_months: int) -> tuple[date, ...]:
  663. """Return deterministic month starts for the configured scan window."""
  664. anchor = _require_date(anchor_day, "anchor_day")
  665. months = _require_lookahead_months(lookahead_months, "lookahead_months")
  666. result: list[date] = []
  667. year = anchor.year
  668. month = anchor.month
  669. for _ in range(months):
  670. result.append(date(year, month, 1))
  671. month += 1
  672. if month == 13:
  673. year += 1
  674. month = 1
  675. return tuple(result)
  676. def approve_precommit(
  677. calendar_day: CalendarDay,
  678. candidate: SlotCandidate,
  679. date_state: DateSelectionState,
  680. slot_state: SlotSelectionState,
  681. ) -> PrecommitApproval:
  682. """Approve final-button readiness only when every observed invariant holds."""
  683. if not isinstance(calendar_day, CalendarDay):
  684. raise ItaProtocolError(
  685. "precommit_type",
  686. "calendar_day must be a CalendarDay",
  687. )
  688. if not isinstance(candidate, SlotCandidate):
  689. raise ItaProtocolError(
  690. "precommit_type",
  691. "candidate must be a SlotCandidate",
  692. )
  693. if not isinstance(date_state, DateSelectionState):
  694. raise ItaProtocolError(
  695. "precommit_type",
  696. "date_state must be a DateSelectionState",
  697. )
  698. if not isinstance(slot_state, SlotSelectionState):
  699. raise ItaProtocolError(
  700. "precommit_type",
  701. "slot_state must be a SlotSelectionState",
  702. )
  703. checks = (
  704. (calendar_day.is_available, "calendar day is not positively available"),
  705. (candidate.is_available, "slot candidate is not positively available"),
  706. (calendar_day.day == candidate.day, "calendar and slot dates differ"),
  707. (
  708. date_state.planned_day == candidate.day,
  709. "selected date differs from the planned date",
  710. ),
  711. (
  712. date_state.matching_availability_count == 1,
  713. "planned date must map to exactly one availability item",
  714. ),
  715. (
  716. date_state.timeline_selected_days == (candidate.day,),
  717. "timeline must have exactly one matching selected date",
  718. ),
  719. (
  720. date_state.content_selected_days == (candidate.day,),
  721. "content must have exactly one matching selected date",
  722. ),
  723. (not date_state.day_disabled, "selected date is disabled"),
  724. (
  725. not date_state.day_not_available,
  726. "selected date has a negative availability marker",
  727. ),
  728. (
  729. date_state.day_has_positive_state,
  730. "selected date lacks the verified positive state",
  731. ),
  732. (
  733. slot_state.active_slot_count == 1,
  734. "there must be exactly one active slot",
  735. ),
  736. (
  737. slot_state.active_is_candidate,
  738. "active slot is not the approved candidate",
  739. ),
  740. (
  741. not slot_state.active_has_unavailable_class,
  742. "active slot has an unavailable class",
  743. ),
  744. (
  745. not slot_state.active_has_red_dot,
  746. "active slot has a negative red marker",
  747. ),
  748. (
  749. slot_state.active_hidden_input_count == 1,
  750. "active slot must contain exactly one runtime identifier input",
  751. ),
  752. (
  753. slot_state.active_daily_id_matches_candidate,
  754. "active slot runtime identifier differs from the candidate",
  755. ),
  756. (
  757. slot_state.active_day_matches_candidate,
  758. "active slot date differs from the candidate",
  759. ),
  760. (
  761. slot_state.active_time_matches_candidate,
  762. "active slot time differs from the candidate",
  763. ),
  764. (
  765. slot_state.active_capacity_matches_candidate,
  766. "active slot capacity differs from the candidate",
  767. ),
  768. )
  769. for passed, message in checks:
  770. if not passed:
  771. raise ItaProtocolError("precommit_rejected", message)
  772. return PrecommitApproval(calendar_day=calendar_day, candidate=candidate)
  773. def _parse_form_control(
  774. form: Mapping[str, Any],
  775. *,
  776. prefix: str,
  777. path: str,
  778. ) -> FormControlConfig:
  779. return FormControlConfig(
  780. control_id=_require_nonempty_string(
  781. form.get(f"{prefix}_control_id"),
  782. f"{path}.{prefix}_control_id",
  783. ),
  784. value=_require_nonempty_string(
  785. form.get(f"{prefix}_value"),
  786. f"{path}.{prefix}_value",
  787. ),
  788. labels=_require_string_tuple(
  789. form.get(f"{prefix}_labels"),
  790. f"{path}.{prefix}_labels",
  791. ),
  792. )
  793. def _parse_mail_config(
  794. raw_mail: Any,
  795. *,
  796. path: str,
  797. ) -> OtpMailConfig | None:
  798. if raw_mail is None:
  799. return None
  800. mail = _require_mapping(raw_mail, path)
  801. sender = mail.get("sender", PRENOTAMI_OTP_SENDER)
  802. if not isinstance(sender, str) or sender.strip().casefold() != PRENOTAMI_OTP_SENDER:
  803. raise ItaProtocolError(
  804. "otp_sender_not_allowlisted",
  805. "mail sender must match Prenot@Mi's official OTP address",
  806. path=f"{path}.sender",
  807. )
  808. return OtpMailConfig(
  809. authorization_email=mail.get("authorization_email"),
  810. subject_keywords=mail.get("subject_keywords", "OTP Code"),
  811. body_keywords=mail.get("body_keywords", "OTP Code:"),
  812. expiry_seconds=mail.get("expiry_seconds", 300),
  813. authorization_source=mail.get("authorization_source", "configured"),
  814. )
  815. def _classify_inventory(
  816. slots_free: int,
  817. slots_remaining: int,
  818. *,
  819. path: str,
  820. ) -> InventoryState:
  821. if slots_free > 0 and slots_remaining >= 0:
  822. return InventoryState.AVAILABLE
  823. if slots_free == 0 and slots_remaining < 0:
  824. return InventoryState.UNAVAILABLE
  825. raise ItaProtocolError(
  826. "inventory_conflict",
  827. "slot counters do not match an observed allowlisted state",
  828. path=path,
  829. )
  830. def _parse_site_date(value: Any, path: str) -> date:
  831. if not isinstance(value, str) or not _SITE_DATE_PATTERN.fullmatch(value):
  832. raise ItaProtocolError(
  833. "date_format",
  834. "date must match DD/MM/YYYY 00:00:00",
  835. path=path,
  836. )
  837. try:
  838. return datetime.strptime(value, "%d/%m/%Y %H:%M:%S").date()
  839. except ValueError as exc:
  840. raise ItaProtocolError(
  841. "date_invalid",
  842. "date is not a real calendar date",
  843. path=path,
  844. ) from exc
  845. def _parse_site_time(value: Any, path: str) -> datetime_time:
  846. mapping = _require_mapping(value, path)
  847. hours = _require_int(_require_key(mapping, "Hours", path), f"{path}.Hours")
  848. minutes = _require_int(
  849. _require_key(mapping, "Minutes", path),
  850. f"{path}.Minutes",
  851. )
  852. seconds = _require_int(mapping.get("Seconds", 0), f"{path}.Seconds")
  853. milliseconds = _require_int(
  854. mapping.get("Milliseconds", 0),
  855. f"{path}.Milliseconds",
  856. )
  857. if seconds != 0 or milliseconds != 0:
  858. raise ItaProtocolError(
  859. "time_precision",
  860. "sub-minute slot precision is not supported by the observed protocol",
  861. path=path,
  862. )
  863. try:
  864. return datetime_time(hour=hours, minute=minutes)
  865. except ValueError as exc:
  866. raise ItaProtocolError(
  867. "time_invalid",
  868. "slot time is outside the 24-hour clock",
  869. path=path,
  870. ) from exc
  871. def _validate_date_range(
  872. start_day: date | None,
  873. end_day: date | None,
  874. ) -> tuple[date | None, date | None]:
  875. start = _require_date(start_day, "start_day") if start_day is not None else None
  876. end = _require_date(end_day, "end_day") if end_day is not None else None
  877. if start is not None and end is not None and start > end:
  878. raise ItaProtocolError(
  879. "date_range_invalid",
  880. "start_day must not be later than end_day",
  881. )
  882. return start, end
  883. def _date_in_range(
  884. value: date,
  885. start_day: date | None,
  886. end_day: date | None,
  887. ) -> bool:
  888. return (
  889. (start_day is None or value >= start_day)
  890. and (end_day is None or value <= end_day)
  891. )
  892. def _require_mapping(value: Any, path: str) -> Mapping[str, Any]:
  893. if not isinstance(value, Mapping):
  894. raise ItaProtocolError(
  895. "mapping_required",
  896. "value must be an object",
  897. path=path,
  898. )
  899. return value
  900. def _require_key(mapping: Mapping[str, Any], key: str, path: str) -> Any:
  901. if key not in mapping:
  902. raise ItaProtocolError(
  903. "field_missing",
  904. "required field is missing",
  905. path=f"{path}.{key}",
  906. )
  907. return mapping[key]
  908. def _require_nonempty_string(value: Any, path: str) -> str:
  909. if not isinstance(value, str) or not value.strip():
  910. raise ItaProtocolError(
  911. "string_required",
  912. "value must be a non-empty string",
  913. path=path,
  914. )
  915. return value.strip()
  916. def _require_string_tuple(value: Any, path: str) -> tuple[str, ...]:
  917. if isinstance(value, (str, bytes)) or not isinstance(value, Sequence):
  918. raise ItaProtocolError(
  919. "labels_required",
  920. "labels must be a non-empty array of strings",
  921. path=path,
  922. )
  923. labels = tuple(
  924. _require_nonempty_string(item, f"{path}[{index}]")
  925. for index, item in enumerate(value)
  926. )
  927. if not labels:
  928. raise ItaProtocolError(
  929. "labels_required",
  930. "labels must be a non-empty array of strings",
  931. path=path,
  932. )
  933. if len(set(labels)) != len(labels):
  934. raise ItaProtocolError(
  935. "labels_duplicate",
  936. "labels must not contain duplicates",
  937. path=path,
  938. )
  939. return labels
  940. def _is_positive_int(value: Any) -> bool:
  941. return isinstance(value, int) and not isinstance(value, bool) and value > 0
  942. def _require_positive_int(value: Any, path: str) -> int:
  943. if not _is_positive_int(value):
  944. raise ItaProtocolError(
  945. "positive_integer_required",
  946. "value must be a positive integer",
  947. path=path,
  948. )
  949. return value
  950. def _require_int(value: Any, path: str) -> int:
  951. if not isinstance(value, int) or isinstance(value, bool):
  952. raise ItaProtocolError(
  953. "integer_required",
  954. "value must be an integer",
  955. path=path,
  956. )
  957. return value
  958. def _require_nonnegative_int(value: Any, path: str) -> int:
  959. number = _require_int(value, path)
  960. if number < 0:
  961. raise ItaProtocolError(
  962. "nonnegative_integer_required",
  963. "value must be a non-negative integer",
  964. path=path,
  965. )
  966. return number
  967. def _require_bool(value: Any, path: str) -> bool:
  968. if not isinstance(value, bool):
  969. raise ItaProtocolError(
  970. "boolean_required",
  971. "value must be a boolean",
  972. path=path,
  973. )
  974. return value
  975. def _require_lookahead_months(value: Any, path: str) -> int:
  976. months = _require_positive_int(value, path)
  977. if months > MAX_LOOKAHEAD_MONTHS:
  978. raise ItaProtocolError(
  979. "lookahead_too_large",
  980. "lookahead exceeds the local scan safety limit",
  981. path=path,
  982. )
  983. return months
  984. def _require_date(value: Any, path: str) -> date:
  985. if not isinstance(value, date) or isinstance(value, datetime):
  986. raise ItaProtocolError(
  987. "date_required",
  988. "value must be a date",
  989. path=path,
  990. )
  991. return value
  992. def _require_date_tuple(value: Any, path: str) -> tuple[date, ...]:
  993. if not isinstance(value, tuple):
  994. raise ItaProtocolError(
  995. "date_tuple_required",
  996. "value must be a tuple of dates",
  997. path=path,
  998. )
  999. for index, item in enumerate(value):
  1000. _require_date(item, f"{path}[{index}]")
  1001. return value
  1002. def _require_time(value: Any, path: str) -> datetime_time:
  1003. if not isinstance(value, datetime_time):
  1004. raise ItaProtocolError(
  1005. "time_required",
  1006. "value must be a time",
  1007. path=path,
  1008. )
  1009. if value.second != 0 or value.microsecond != 0:
  1010. raise ItaProtocolError(
  1011. "time_precision",
  1012. "slot time must use minute precision",
  1013. path=path,
  1014. )
  1015. return value
  1016. # ============================================================================
  1017. # CALENDAR_QUERY (from plugins/ita_calendar_query.py)
  1018. # ============================================================================
  1019. """Shared browser adapter for read-only Prenot@Mi Calendar queries.
  1020. The pure wire-format rules live in :mod:`plugins.ita_protocol`. This module
  1021. owns only the browser-facing mechanics that production Query and the Q-CAL
  1022. diagnostic tool must share: one-shot listeners, strict packet metadata,
  1023. native month navigation, the final-button guard, and bounded scanning.
  1024. """
  1025. import json
  1026. import time
  1027. from dataclasses import dataclass
  1028. from datetime import date, datetime
  1029. from typing import Any, Callable
  1030. from urllib.parse import urljoin, urlparse
  1031. CALENDAR_PATH = "/BookingCalendar"
  1032. AVAILABILITY_PATH = "/BookingCalendar/RetrieveCalendarAvailability"
  1033. MAX_QUERY_LOOKAHEAD_MONTHS = 120
  1034. DEFAULT_MONTH_CLICK_INTERVAL_SECONDS = 1.5
  1035. CALENDAR_GUARD_SCRIPT = r"""
  1036. /* coordinate:ita-calendar-query-final-guard */
  1037. const finalButtons = Array.from(
  1038. document.querySelectorAll('#btnPrenotaNoOtp')
  1039. );
  1040. finalButtons.forEach((button) => {
  1041. button.disabled = true;
  1042. button.setAttribute('aria-disabled', 'true');
  1043. button.dataset.coordinateFinalGuard = 'enabled';
  1044. });
  1045. const resources = performance.getEntriesByType('resource');
  1046. return {
  1047. path: window.location.pathname,
  1048. calendarFunctionPresent:
  1049. typeof window.CaricaTimelineOrizzontale === 'function',
  1050. finalButtonCount: finalButtons.length,
  1051. allFinalButtonsGuarded: finalButtons.every(
  1052. (button) => button.disabled &&
  1053. button.dataset.coordinateFinalGuard === 'enabled'
  1054. ),
  1055. finalRequestCount: resources.filter(
  1056. (entry) => entry.name.includes(
  1057. '/BookingCalendar/InsertNewBooking'
  1058. )
  1059. ).length,
  1060. timeSlotRequestCount: resources.filter(
  1061. (entry) => entry.name.includes(
  1062. '/BookingCalendar/RetrieveTimeSlots'
  1063. )
  1064. ).length,
  1065. };
  1066. """
  1067. NEXT_MONTH_CONTROL_SCRIPT = r"""
  1068. /* coordinate:ita-calendar-query-next-month */
  1069. const shouldClick = arguments[0] === true;
  1070. const selector = '#datetimepicker th.dtpicker-next';
  1071. const candidates = Array.from(document.querySelectorAll(selector));
  1072. const isActionable = (element) => {
  1073. if (
  1074. !element.isConnected ||
  1075. element.hasAttribute('disabled') ||
  1076. element.getAttribute('aria-disabled') === 'true'
  1077. ) {
  1078. return false;
  1079. }
  1080. const style = window.getComputedStyle(element);
  1081. if (
  1082. style.display === 'none' ||
  1083. style.visibility === 'hidden' ||
  1084. style.pointerEvents === 'none' ||
  1085. Number.parseFloat(style.opacity || '1') <= 0
  1086. ) {
  1087. return false;
  1088. }
  1089. const rect = element.getBoundingClientRect();
  1090. const left = Math.max(0, rect.left);
  1091. const right = Math.min(window.innerWidth, rect.right);
  1092. const top = Math.max(0, rect.top);
  1093. const bottom = Math.min(window.innerHeight, rect.bottom);
  1094. if (right <= left || bottom <= top) return false;
  1095. const topNode = document.elementFromPoint(
  1096. (left + right) / 2,
  1097. (top + bottom) / 2
  1098. );
  1099. return Boolean(topNode && (
  1100. topNode === element || element.contains(topNode)
  1101. ));
  1102. };
  1103. const actionable = candidates.filter(isActionable);
  1104. let clicked = false;
  1105. if (shouldClick && actionable.length === 1) {
  1106. clicked = true;
  1107. actionable[0].click();
  1108. }
  1109. return {
  1110. pathMatches: window.location.pathname === '/BookingCalendar',
  1111. candidateCount: candidates.length,
  1112. actionableCount: actionable.length,
  1113. clicked,
  1114. };
  1115. """
  1116. class CalendarGateError(RuntimeError):
  1117. """Fail-closed Calendar adapter error without sensitive response data."""
  1118. class CalendarAuthenticationExpiredError(CalendarGateError):
  1119. """An observed response explicitly rejected the authenticated session."""
  1120. class CalendarRateLimitedError(CalendarGateError):
  1121. """The server explicitly limited requests; callers must not rotate accounts."""
  1122. class CalendarAccessDeniedError(CalendarGateError):
  1123. """Permission or browser verification requires operator attention."""
  1124. class CalendarTransientError(CalendarGateError):
  1125. """A read failed without evidence that authentication or schema changed."""
  1126. class CalendarNextMonthUnavailableError(CalendarGateError):
  1127. """Raised when the native next-month control cannot be used safely."""
  1128. def require_plain_nonnegative_int(value: object, name: str) -> int:
  1129. if isinstance(value, bool) or not isinstance(value, int) or value < 0:
  1130. raise CalendarGateError(f"{name} must be a nonnegative integer")
  1131. return value
  1132. def same_origin_path(raw_url: object) -> tuple[str, object]:
  1133. parsed = urlparse(str(raw_url or ""))
  1134. try:
  1135. port = parsed.port
  1136. except ValueError as exc:
  1137. raise CalendarGateError(
  1138. "Observed request used an unexpected origin"
  1139. ) from exc
  1140. if (
  1141. parsed.scheme != "https"
  1142. or parsed.hostname != "prenotami.esteri.it"
  1143. or port not in (None, 443)
  1144. or parsed.username is not None
  1145. or parsed.password is not None
  1146. ):
  1147. raise CalendarGateError("Observed request used an unexpected origin")
  1148. return parsed.path, parsed
  1149. def header_value(headers: object, name: str) -> str:
  1150. if not hasattr(headers, "items"):
  1151. return ""
  1152. for key, value in headers.items():
  1153. if str(key).casefold() == name.casefold():
  1154. return str(value)
  1155. return ""
  1156. @dataclass(frozen=True, slots=True)
  1157. class CalendarProbeResult:
  1158. days: tuple[CalendarDay, ...]
  1159. selected_day: str
  1160. def __post_init__(self) -> None:
  1161. if not isinstance(self.selected_day, str) or not self.selected_day.strip():
  1162. raise CalendarGateError("selected_day must be a non-empty string")
  1163. if any(not isinstance(item, CalendarDay) for item in self.days):
  1164. raise CalendarGateError("days must contain CalendarDay values")
  1165. selected_month = self.selected_month
  1166. if any(
  1167. (item.day.year, item.day.month) != selected_month
  1168. for item in self.days
  1169. ):
  1170. raise CalendarGateError(
  1171. "Availability response escaped the requested month"
  1172. )
  1173. @property
  1174. def item_count(self) -> int:
  1175. return len(self.days)
  1176. @property
  1177. def available_days(self) -> tuple[CalendarDay, ...]:
  1178. return available_calendar_days(self.days)
  1179. @property
  1180. def available_count(self) -> int:
  1181. return len(self.available_days)
  1182. @property
  1183. def selected_month(self) -> tuple[int, int]:
  1184. value = self.selected_day.strip()[:10]
  1185. for date_format in ("%Y-%m-%d", "%d/%m/%Y"):
  1186. try:
  1187. parsed = datetime.strptime(value, date_format)
  1188. except ValueError:
  1189. continue
  1190. return parsed.year, parsed.month
  1191. raise CalendarGateError(
  1192. "Availability selectedDay used an unknown date format"
  1193. )
  1194. def next_month_value(value: tuple[int, int]) -> tuple[int, int]:
  1195. year, month = value
  1196. return (year + 1, 1) if month == 12 else (year, month + 1)
  1197. def month_text(value: tuple[int, int]) -> str:
  1198. return f"{value[0]:04d}-{value[1]:02d}"
  1199. @dataclass(frozen=True, slots=True)
  1200. class CalendarQueryScanResult:
  1201. """Result of scanning until the first positive month or the horizon end."""
  1202. probes: tuple[CalendarProbeResult, ...]
  1203. lookahead_months: int
  1204. stop_reason: str
  1205. def __post_init__(self) -> None:
  1206. _validate_lookahead_months(self.lookahead_months)
  1207. if not self.probes or any(
  1208. not isinstance(probe, CalendarProbeResult)
  1209. for probe in self.probes
  1210. ):
  1211. raise CalendarGateError(
  1212. "Calendar query scan requires parsed probe results"
  1213. )
  1214. if len(self.probes) > self.lookahead_months:
  1215. raise CalendarGateError(
  1216. "Calendar query scan exceeded the configured horizon"
  1217. )
  1218. for previous, current in zip(self.probes, self.probes[1:]):
  1219. if current.selected_month != next_month_value(
  1220. previous.selected_month
  1221. ):
  1222. raise CalendarGateError(
  1223. "Calendar request did not advance exactly one month"
  1224. )
  1225. if self.stop_reason == "first_available_month":
  1226. if self.probes[-1].available_count == 0:
  1227. raise CalendarGateError(
  1228. "first-available stop requires a positive final probe"
  1229. )
  1230. if any(probe.available_count for probe in self.probes[:-1]):
  1231. raise CalendarGateError(
  1232. "Calendar query scanned beyond the first positive month"
  1233. )
  1234. elif self.stop_reason == "horizon_exhausted":
  1235. if len(self.probes) != self.lookahead_months:
  1236. raise CalendarGateError(
  1237. "Calendar query ended before the configured horizon"
  1238. )
  1239. if any(probe.available_count for probe in self.probes):
  1240. raise CalendarGateError(
  1241. "Calendar query ignored a positive month"
  1242. )
  1243. else:
  1244. raise CalendarGateError(
  1245. "Calendar query scan used an unknown stop reason"
  1246. )
  1247. @property
  1248. def scanned_months(self) -> int:
  1249. return len(self.probes)
  1250. @property
  1251. def available_days(self) -> tuple[CalendarDay, ...]:
  1252. if self.stop_reason != "first_available_month":
  1253. return ()
  1254. return self.probes[-1].available_days
  1255. @property
  1256. def earliest_available_date(self) -> date | None:
  1257. return (
  1258. self.available_days[0].day
  1259. if self.available_days
  1260. else None
  1261. )
  1262. def _validate_lookahead_months(value: object) -> int:
  1263. if (
  1264. isinstance(value, bool)
  1265. or not isinstance(value, int)
  1266. or not 1 <= value <= MAX_QUERY_LOOKAHEAD_MONTHS
  1267. ):
  1268. raise CalendarGateError(
  1269. "lookahead_months must be between 1 and 120"
  1270. )
  1271. return value
  1272. def listen_once(
  1273. page: object,
  1274. *,
  1275. target: str,
  1276. method: str,
  1277. action: Callable[[], Any],
  1278. timeout: float,
  1279. ) -> object:
  1280. """Listen around one native action and always stop the listener."""
  1281. page.listen.start(target, method=method)
  1282. try:
  1283. action()
  1284. packet = page.listen.wait(timeout=timeout)
  1285. if not packet:
  1286. raise CalendarTransientError(
  1287. f"Expected {method} {target} was not observed"
  1288. )
  1289. return packet
  1290. finally:
  1291. page.listen.stop()
  1292. def parse_availability_packet(packet: object) -> CalendarProbeResult:
  1293. path, _ = same_origin_path(packet.url)
  1294. if str(packet.method).upper() != "POST" or path != AVAILABILITY_PATH:
  1295. raise CalendarGateError("Availability request method or path changed")
  1296. response = packet.response
  1297. status = response.status
  1298. if type(status) is not int:
  1299. raise CalendarGateError("Availability HTTP status was not an integer")
  1300. if status in {301, 302, 303, 307, 308}:
  1301. location = header_value(getattr(response, "headers", None), "Location")
  1302. destination = urlparse(urljoin(packet.url, location))
  1303. if location and destination.scheme == "https" and destination.hostname == "iam.esteri.it":
  1304. raise CalendarAuthenticationExpiredError("Calendar response redirected to IAM")
  1305. response_url = getattr(response, "url", None)
  1306. if isinstance(response_url, str) and response_url:
  1307. destination = urlparse(response_url)
  1308. if destination.scheme == "https" and destination.hostname == "iam.esteri.it":
  1309. raise CalendarAuthenticationExpiredError("Calendar response returned to IAM")
  1310. response_path, _ = same_origin_path(response_url)
  1311. if response_path != AVAILABILITY_PATH:
  1312. raise CalendarGateError("Availability response reached an unexpected path")
  1313. if status == 401:
  1314. raise CalendarAuthenticationExpiredError("Calendar authentication expired")
  1315. if status == 429:
  1316. raise CalendarRateLimitedError("Calendar request was rate limited")
  1317. if status == 403:
  1318. raise CalendarAccessDeniedError("Calendar access requires operator attention")
  1319. if status in {0, 408, 502, 503, 504}:
  1320. raise CalendarTransientError("Calendar request temporarily failed")
  1321. if status != 200:
  1322. raise CalendarGateError("Availability response status was not 200")
  1323. post_data = packet.request.postData
  1324. if isinstance(post_data, str):
  1325. try:
  1326. post_data = json.loads(post_data)
  1327. except json.JSONDecodeError as exc:
  1328. raise CalendarGateError(
  1329. "Availability request body was not JSON"
  1330. ) from exc
  1331. if not isinstance(post_data, dict) or set(post_data) != {
  1332. "_Servizio",
  1333. "selectedDay",
  1334. }:
  1335. raise CalendarGateError("Availability request keys changed")
  1336. if isinstance(post_data["_Servizio"], bool) or not str(
  1337. post_data["_Servizio"]
  1338. ).strip():
  1339. raise CalendarGateError("Availability runtime service id was empty")
  1340. if (
  1341. not isinstance(post_data["selectedDay"], str)
  1342. or not post_data["selectedDay"].strip()
  1343. ):
  1344. raise CalendarGateError("Availability selectedDay was empty")
  1345. try:
  1346. days = parse_calendar_availability(packet.response.raw_body)
  1347. except ItaProtocolError as exc:
  1348. raise CalendarGateError(
  1349. f"Availability response rejected ({exc.code})"
  1350. ) from exc
  1351. return CalendarProbeResult(
  1352. days=days,
  1353. selected_day=post_data["selectedDay"],
  1354. )
  1355. def validate_next_month_snapshot(
  1356. raw: object,
  1357. *,
  1358. expected_clicked: bool,
  1359. allow_unready: bool = False,
  1360. ) -> dict[str, object]:
  1361. """Require the exact, non-sensitive Calendar month-control shape."""
  1362. if not isinstance(raw, dict):
  1363. raise CalendarGateError(
  1364. "Calendar next-month control did not return an object"
  1365. )
  1366. expected_keys = {
  1367. "pathMatches",
  1368. "candidateCount",
  1369. "actionableCount",
  1370. "clicked",
  1371. }
  1372. if set(raw) != expected_keys:
  1373. raise CalendarGateError(
  1374. "Calendar next-month control returned unexpected fields"
  1375. )
  1376. if raw["pathMatches"] is not True:
  1377. raise CalendarGateError(
  1378. "Calendar next-month control was evaluated outside Calendar"
  1379. )
  1380. candidate_count = require_plain_nonnegative_int(
  1381. raw["candidateCount"],
  1382. "candidateCount",
  1383. )
  1384. actionable_count = require_plain_nonnegative_int(
  1385. raw["actionableCount"],
  1386. "actionableCount",
  1387. )
  1388. if actionable_count > candidate_count:
  1389. raise CalendarGateError(
  1390. "Calendar next-month actionable count exceeded candidates"
  1391. )
  1392. if not isinstance(expected_clicked, bool):
  1393. raise CalendarGateError("expected_clicked must be a boolean")
  1394. if raw["clicked"] is not expected_clicked:
  1395. raise CalendarGateError(
  1396. "Calendar next-month click acknowledgement changed"
  1397. )
  1398. if actionable_count != 1 and not (
  1399. allow_unready and actionable_count == 0
  1400. ):
  1401. raise CalendarGateError(
  1402. "Calendar next-month control was not uniquely actionable"
  1403. )
  1404. return raw
  1405. def click_next_month(
  1406. page: object,
  1407. *,
  1408. timeout: float = 10,
  1409. diagnostic: Callable[[object], None] | None = None,
  1410. ) -> None:
  1411. """Click only the unique visible Bootstrap day-view month control."""
  1412. deadline = time.monotonic() + timeout
  1413. last_raw: object = None
  1414. while time.monotonic() < deadline:
  1415. last_raw = page.run_js(NEXT_MONTH_CONTROL_SCRIPT, False)
  1416. try:
  1417. snapshot = validate_next_month_snapshot(
  1418. last_raw,
  1419. expected_clicked=False,
  1420. allow_unready=True,
  1421. )
  1422. except CalendarGateError:
  1423. if diagnostic:
  1424. diagnostic(last_raw)
  1425. raise
  1426. if snapshot["actionableCount"] == 1:
  1427. break
  1428. time.sleep(0.25)
  1429. else:
  1430. if diagnostic:
  1431. diagnostic(last_raw)
  1432. raise CalendarNextMonthUnavailableError(
  1433. "Calendar next-month control was not actionable before timeout"
  1434. )
  1435. clicked = page.run_js(NEXT_MONTH_CONTROL_SCRIPT, True)
  1436. if diagnostic:
  1437. diagnostic(clicked)
  1438. validate_next_month_snapshot(clicked, expected_clicked=True)
  1439. def refresh_calendar(page: object) -> None:
  1440. page.refresh()
  1441. page.wait.doc_loaded()
  1442. def guard_calendar(page: object) -> dict[str, object]:
  1443. """Disable the final button and reject any observed final request."""
  1444. raw = page.run_js(CALENDAR_GUARD_SCRIPT)
  1445. if not isinstance(raw, dict):
  1446. raise CalendarGateError("Calendar guard did not return an object")
  1447. expected = {
  1448. "path": CALENDAR_PATH,
  1449. "calendarFunctionPresent": True,
  1450. "finalButtonCount": 1,
  1451. "allFinalButtonsGuarded": True,
  1452. "finalRequestCount": 0,
  1453. }
  1454. for key, expected_value in expected.items():
  1455. if raw.get(key) != expected_value:
  1456. raise CalendarGateError(f"Calendar guard rejected {key}")
  1457. return raw
  1458. def capture_initial_probe(page: object) -> CalendarProbeResult:
  1459. packet = listen_once(
  1460. page,
  1461. target=AVAILABILITY_PATH,
  1462. method="POST",
  1463. action=lambda: refresh_calendar(page),
  1464. timeout=30,
  1465. )
  1466. probe = parse_availability_packet(packet)
  1467. guard_calendar(page)
  1468. return probe
  1469. def capture_next_probe(page: object) -> CalendarProbeResult:
  1470. packet = listen_once(
  1471. page,
  1472. target=AVAILABILITY_PATH,
  1473. method="POST",
  1474. action=lambda: click_next_month(page),
  1475. timeout=30,
  1476. )
  1477. probe = parse_availability_packet(packet)
  1478. guard_calendar(page)
  1479. return probe
  1480. def scan_until_first_available_month(
  1481. page: object,
  1482. *,
  1483. lookahead_months: int,
  1484. log: Callable[[str], None] | None = None,
  1485. month_click_interval_seconds: float = DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
  1486. ) -> CalendarQueryScanResult:
  1487. """Scan sequential months and stop immediately at the first positive one."""
  1488. months = _validate_lookahead_months(lookahead_months)
  1489. if (
  1490. isinstance(month_click_interval_seconds, bool)
  1491. or not isinstance(month_click_interval_seconds, (int, float))
  1492. or month_click_interval_seconds < 0
  1493. ):
  1494. raise CalendarGateError(
  1495. "month_click_interval_seconds must be nonnegative"
  1496. )
  1497. probes = [capture_initial_probe(page)]
  1498. if log:
  1499. log(
  1500. "Italy Calendar probe "
  1501. f"index=0 available={probes[0].available_count}"
  1502. )
  1503. if probes[0].available_count:
  1504. return CalendarQueryScanResult(
  1505. probes=tuple(probes),
  1506. lookahead_months=months,
  1507. stop_reason="first_available_month",
  1508. )
  1509. for index in range(1, months):
  1510. if month_click_interval_seconds:
  1511. time.sleep(month_click_interval_seconds)
  1512. try:
  1513. probe = capture_next_probe(page)
  1514. except CalendarNextMonthUnavailableError as exc:
  1515. raise CalendarGateError(
  1516. "Calendar scan ended before the configured horizon"
  1517. ) from exc
  1518. if probe.selected_month != next_month_value(
  1519. probes[-1].selected_month
  1520. ):
  1521. raise CalendarGateError(
  1522. "Calendar request did not advance exactly one month"
  1523. )
  1524. probes.append(probe)
  1525. if log:
  1526. log(
  1527. "Italy Calendar probe "
  1528. f"index={index} available={probe.available_count}"
  1529. )
  1530. if probe.available_count:
  1531. return CalendarQueryScanResult(
  1532. probes=tuple(probes),
  1533. lookahead_months=months,
  1534. stop_reason="first_available_month",
  1535. )
  1536. return CalendarQueryScanResult(
  1537. probes=tuple(probes),
  1538. lookahead_months=months,
  1539. stop_reason="horizon_exhausted",
  1540. )
  1541. # ============================================================================
  1542. # CALENDAR_BOOK (from plugins/ita_calendar_book.py)
  1543. # ============================================================================
  1544. """Book-side Calendar response binding and native slot selection.
  1545. The caller owns login, route continuity, date preferences and fresh packet
  1546. capture in the applicant's browser. This adapter neither fetches inventory nor
  1547. accepts a Query snapshot. A returned approval is a pre-final checkpoint, never
  1548. permission to submit or evidence of a completed booking.
  1549. """
  1550. import json
  1551. import time
  1552. from dataclasses import dataclass, field
  1553. from datetime import date, datetime
  1554. from typing import Callable, Mapping
  1555. TIME_SLOTS_PATH = "/BookingCalendar/RetrieveTimeSlots"
  1556. RUNTIME_SERVICE_SCRIPT = r"""
  1557. /* coordinate:ita-book-runtime-service */
  1558. const controls = Array.from(document.querySelectorAll('#idServizio'));
  1559. return {
  1560. path: window.location.pathname,
  1561. count: controls.length,
  1562. value: controls.length === 1 ? controls[0].value : null,
  1563. };
  1564. """
  1565. SLOT_SELECTION_SCRIPT = r"""
  1566. /* coordinate:ita-book-slot-selection */
  1567. const [serviceId, day, dailyId, timeLabel, capacity, shouldClick] = arguments;
  1568. const normalize = (text) => String(text || '').replace(/\s+/g, ' ').trim();
  1569. const service = Array.from(document.querySelectorAll('#idServizio'));
  1570. const runtimeMatches = window.location.origin === 'https://prenotami.esteri.it' &&
  1571. window.location.pathname === '/BookingCalendar' &&
  1572. service.length === 1 && service[0].value === serviceId;
  1573. const finalButtons = Array.from(document.querySelectorAll('#btnPrenotaNoOtp'));
  1574. const finalGuarded = finalButtons.length === 1 && finalButtons[0].disabled &&
  1575. finalButtons[0].dataset.coordinateFinalGuard === 'enabled';
  1576. const timeline = Array.from(document.querySelectorAll('.events a.selected'));
  1577. const content = Array.from(document.querySelectorAll('.events-content li.selected'));
  1578. const links = Array.from(document.querySelectorAll('.events a[data-date]'))
  1579. .filter((element) => element.dataset.date === day);
  1580. const link = links.length === 1 ? links[0] : null;
  1581. const datesMatch = timeline.length === 1 && content.length === 1 &&
  1582. timeline[0].dataset.date === day && content[0].dataset.date === day;
  1583. const firstSelectedMatches = datesMatch && document.querySelector('.selected') === timeline[0];
  1584. const disabled = (element) => !element || element.hasAttribute('disabled') ||
  1585. element.getAttribute('aria-disabled') === 'true' ||
  1586. element.classList.contains('disabled') ||
  1587. element.classList.contains('input-async-disabilitato');
  1588. const dayNegative = !link || link.classList.contains('notAvailableDay');
  1589. const dayPositive = Boolean(link && link.classList.contains('input-async-abilitato'));
  1590. const inputs = (slot) => slot ? Array.from(slot.querySelectorAll('input')) : [];
  1591. const idMatches = (slot) => {
  1592. const fields = inputs(slot);
  1593. return fields.length === 1 && fields[0].type === 'hidden' &&
  1594. fields[0].id === 'idHiddenFasciaServizio' && fields[0].value === dailyId;
  1595. };
  1596. const timeMatches = (slot) => {
  1597. const spans = slot ? slot.querySelectorAll('span') : [];
  1598. return spans.length === 2 && normalize(spans[0].textContent) === timeLabel;
  1599. };
  1600. const capacityMatches = (slot) => {
  1601. const spans = slot ? slot.querySelectorAll('span') : [];
  1602. return spans.length === 2 && normalize(spans[1].textContent) === `(${capacity})`;
  1603. };
  1604. const negative = (slot) => !slot || slot.classList.contains('notAvailableFascia');
  1605. const redDot = (slot) => Boolean(slot && slot.querySelector('.dotRed'));
  1606. const actionable = (element) => {
  1607. if (!element || !element.isConnected || disabled(element)) return false;
  1608. const style = window.getComputedStyle(element);
  1609. if (style.display === 'none' || style.visibility === 'hidden' ||
  1610. style.pointerEvents === 'none' || Number.parseFloat(style.opacity || '1') <= 0) return false;
  1611. const rect = element.getBoundingClientRect();
  1612. const left = Math.max(0, rect.left), right = Math.min(window.innerWidth, rect.right);
  1613. const top = Math.max(0, rect.top), bottom = Math.min(window.innerHeight, rect.bottom);
  1614. if (right <= left || bottom <= top) return false;
  1615. const hit = document.elementFromPoint((left + right) / 2, (top + bottom) / 2);
  1616. return Boolean(hit && (hit === element || element.contains(hit)));
  1617. };
  1618. const slots = content.length === 1 ? Array.from(content[0].querySelectorAll('.fascia')) : [];
  1619. const matches = slots.filter(idMatches);
  1620. const candidate = matches.length === 1 ? matches[0] : null;
  1621. const candidateReady = Boolean(candidate && !negative(candidate) && !redDot(candidate) &&
  1622. timeMatches(candidate) && capacityMatches(candidate) && actionable(candidate));
  1623. let active = Array.from(document.querySelectorAll('.fascia.act'));
  1624. const alreadyActive = active.length === 1 && active[0] === candidate;
  1625. let clicked = false;
  1626. if (shouldClick === true && runtimeMatches && finalGuarded && datesMatch &&
  1627. firstSelectedMatches && links.length === 1 && !disabled(link) && !dayNegative &&
  1628. dayPositive && candidateReady && !alreadyActive) {
  1629. candidate.click();
  1630. clicked = true;
  1631. }
  1632. active = Array.from(document.querySelectorAll('.fascia.act'));
  1633. const selected = active.length === 1 ? active[0] : null;
  1634. return {
  1635. runtimeMatches, finalGuarded, firstSelectedMatches,
  1636. timelineDays: timeline.map((element) => element.dataset.date || ''),
  1637. contentDays: content.map((element) => element.dataset.date || ''),
  1638. matchingDateCount: links.length,
  1639. dayDisabled: disabled(link), dayNegative, dayPositive,
  1640. candidateCount: matches.length, candidateReady, clicked,
  1641. activeCount: active.length,
  1642. activeIsCandidate: Boolean(selected && selected === candidate),
  1643. activeUnavailable: negative(selected), activeRedDot: redDot(selected),
  1644. activeInputCount: inputs(selected).length,
  1645. activeIdMatches: idMatches(selected),
  1646. activeDayMatches: Boolean(selected && datesMatch && content[0].contains(selected)),
  1647. activeTimeMatches: timeMatches(selected),
  1648. activeCapacityMatches: capacityMatches(selected),
  1649. };
  1650. """
  1651. class CalendarBookError(CalendarGateError):
  1652. """A safe stage error; never includes response bodies or runtime IDs."""
  1653. def __init__(self, message: str, *, http_status: int | None = None):
  1654. super().__init__(message)
  1655. self.http_status = http_status
  1656. class CalendarServiceNotReadyError(CalendarBookError):
  1657. """The service control stayed empty during a known initialization boundary."""
  1658. _BOOL_FIELDS = {
  1659. "runtimeMatches", "finalGuarded", "firstSelectedMatches", "dayDisabled",
  1660. "dayNegative", "dayPositive", "candidateReady", "clicked",
  1661. "activeIsCandidate", "activeUnavailable", "activeRedDot", "activeIdMatches",
  1662. "activeDayMatches", "activeTimeMatches", "activeCapacityMatches",
  1663. }
  1664. _COUNT_FIELDS = {"matchingDateCount", "candidateCount", "activeCount", "activeInputCount"}
  1665. _DATE_FIELDS = {"timelineDays", "contentDays"}
  1666. def _runtime_id(value: object) -> str:
  1667. if type(value) is int and value > 0:
  1668. return str(value)
  1669. if isinstance(value, str) and value and value == value.strip() and len(value) <= 128:
  1670. return value
  1671. raise CalendarBookError("Book runtime service identifier was invalid")
  1672. def _read_calendar_service_value(page: object) -> str:
  1673. path, _ = same_origin_path(page.url)
  1674. if path != CALENDAR_PATH:
  1675. raise CalendarBookError("Book selection requires the current Calendar page")
  1676. raw = page.run_js(RUNTIME_SERVICE_SCRIPT)
  1677. if not isinstance(raw, dict) or set(raw) != {"path", "count", "value"}:
  1678. raise CalendarBookError("Book Calendar runtime context changed")
  1679. if raw["path"] != CALENDAR_PATH or type(raw["count"]) is not int or raw["count"] != 1:
  1680. raise CalendarBookError("Book Calendar requires one runtime service control")
  1681. if not isinstance(raw["value"], str):
  1682. raise CalendarBookError("Book Calendar runtime service control has no value")
  1683. return raw["value"]
  1684. def read_calendar_service(page: object) -> str:
  1685. """Strict read for stable phases; empty values are never a valid identity."""
  1686. return _runtime_id(_read_calendar_service_value(page))
  1687. def wait_for_calendar_service(
  1688. page: object, *, session_is_current: Callable[[], bool],
  1689. expected_service: str | None = None, timeout: float = 5,
  1690. ) -> str:
  1691. """Await the site's field assignment without requesting or retrying anything.
  1692. Call only after AVANTI or native Calendar loading. Stable-phase checks stay
  1693. strict: only an exactly empty string is pending, not malformed identities,
  1694. missing/duplicate controls, another service, or a changed applicant/tab.
  1695. The deadline bounds polling; browser transport failures propagate normally.
  1696. """
  1697. if type(timeout) not in (int, float) or not 0 <= timeout < float("inf"):
  1698. raise CalendarBookError("Book Calendar readiness timeout must be finite and nonnegative")
  1699. if not callable(session_is_current):
  1700. raise CalendarBookError("Book Calendar readiness requires a Session check")
  1701. if expected_service is not None:
  1702. expected_service = _runtime_id(expected_service)
  1703. tab_id = getattr(page, "tab_id", None)
  1704. if not isinstance(tab_id, str) or not tab_id:
  1705. raise CalendarBookError("Book Calendar tab identity was unavailable")
  1706. deadline = time.monotonic() + timeout
  1707. def require_session() -> None:
  1708. if session_is_current() is not True or getattr(page, "tab_id", None) != tab_id:
  1709. raise CalendarBookError("Book applicant, route or browser Session changed")
  1710. if same_origin_path(page.url)[0] != CALENDAR_PATH:
  1711. raise CalendarBookError("Book readiness left the current Calendar page")
  1712. while True:
  1713. require_session()
  1714. guard_calendar(page)
  1715. value = _read_calendar_service_value(page)
  1716. require_session()
  1717. if value != "":
  1718. service = _runtime_id(value)
  1719. if expected_service is not None and service != expected_service:
  1720. raise CalendarBookError("Book Calendar runtime service changed")
  1721. return service
  1722. remaining = deadline - time.monotonic()
  1723. if remaining <= 0:
  1724. raise CalendarServiceNotReadyError("Book Calendar service did not initialize before timeout")
  1725. time.sleep(min(0.1, remaining))
  1726. def _request_day(value: object) -> date:
  1727. if isinstance(value, str):
  1728. for date_format in ("%Y-%m-%d", "%d/%m/%Y"):
  1729. try:
  1730. return datetime.strptime(value, date_format).date()
  1731. except ValueError:
  1732. pass
  1733. raise CalendarBookError("Book TimeSlots request date format changed")
  1734. def parse_book_time_slots(
  1735. packet: object, *, target_day: date, runtime_service_id: str,
  1736. ) -> tuple[SlotCandidate, ...]:
  1737. """Bind TimeSlots metadata to the selected day and current DOM service."""
  1738. try:
  1739. path, _ = same_origin_path(packet.url)
  1740. if str(packet.method).upper() != "POST" or path != TIME_SLOTS_PATH:
  1741. raise CalendarBookError("Book TimeSlots request method or path changed")
  1742. if type(packet.response.status) is not int or packet.response.status != 200:
  1743. raise CalendarBookError(
  1744. "Book TimeSlots response status was not 200",
  1745. http_status=packet.response.status if type(packet.response.status) is int else None,
  1746. )
  1747. body = packet.request.postData
  1748. if isinstance(body, str):
  1749. body = json.loads(body)
  1750. if not isinstance(body, dict) or set(body) != {"selectedDay", "idService"}:
  1751. raise CalendarBookError("Book TimeSlots request fields changed")
  1752. if _runtime_id(body["idService"]) != runtime_service_id:
  1753. raise CalendarBookError("Book TimeSlots request does not match the current service")
  1754. if _request_day(body["selectedDay"]) != target_day:
  1755. raise CalendarBookError("Book TimeSlots request does not match the target day")
  1756. candidates = parse_time_slots(packet.response.raw_body)
  1757. if any(item.day != target_day for item in candidates):
  1758. raise CalendarBookError("Book TimeSlots response contains another day")
  1759. return candidates
  1760. except CalendarBookError:
  1761. raise
  1762. except ItaProtocolError as exc:
  1763. raise CalendarBookError(f"Book TimeSlots protocol rejected ({exc.code})") from None
  1764. except Exception:
  1765. raise CalendarBookError("Book TimeSlots packet could not be validated") from None
  1766. def _snapshot(page: object, service: str, target: date, candidate: SlotCandidate, *, click: bool) -> dict:
  1767. raw = page.run_js(
  1768. SLOT_SELECTION_SCRIPT, service, target.isoformat(), candidate.daily_calendar_id,
  1769. candidate.time_label, candidate.slots_free, click,
  1770. )
  1771. if not isinstance(raw, dict) or set(raw) != _BOOL_FIELDS | _COUNT_FIELDS | _DATE_FIELDS:
  1772. raise CalendarBookError("Book slot snapshot fields changed")
  1773. if any(type(raw[key]) is not bool for key in _BOOL_FIELDS):
  1774. raise CalendarBookError("Book slot snapshot boolean types changed")
  1775. for key in _COUNT_FIELDS:
  1776. require_plain_nonnegative_int(raw[key], key)
  1777. for key in _DATE_FIELDS:
  1778. if not isinstance(raw[key], list) or any(not isinstance(item, str) for item in raw[key]):
  1779. raise CalendarBookError("Book selected-date snapshot types changed")
  1780. return raw
  1781. def _require_ready(raw: dict, target_day: date) -> None:
  1782. positive = ("runtimeMatches", "finalGuarded", "firstSelectedMatches", "dayPositive", "candidateReady")
  1783. if any(raw[key] is not True for key in positive):
  1784. raise CalendarBookError("Book candidate is not safely selectable")
  1785. if raw["dayDisabled"] or raw["dayNegative"]:
  1786. raise CalendarBookError("Book selected day is marked unavailable")
  1787. if raw["matchingDateCount"] != 1 or raw["candidateCount"] != 1:
  1788. raise CalendarBookError("Book date or slot is not unique")
  1789. expected = [target_day.isoformat()]
  1790. if raw["timelineDays"] != expected or raw["contentDays"] != expected:
  1791. raise CalendarBookError("Book timeline and content dates do not match the target")
  1792. def _approve_selection_snapshot(
  1793. calendar_day: CalendarDay, candidate: SlotCandidate, raw: dict,
  1794. ) -> PrecommitApproval:
  1795. _require_ready(raw, candidate.day)
  1796. if raw["clicked"]:
  1797. raise CalendarBookError("Book readback unexpectedly clicked")
  1798. return approve_precommit(
  1799. calendar_day, candidate,
  1800. DateSelectionState(
  1801. planned_day=candidate.day, matching_availability_count=1,
  1802. timeline_selected_days=tuple(date.fromisoformat(item) for item in raw["timelineDays"]),
  1803. content_selected_days=tuple(date.fromisoformat(item) for item in raw["contentDays"]),
  1804. day_disabled=raw["dayDisabled"], day_not_available=raw["dayNegative"],
  1805. day_has_positive_state=raw["dayPositive"],
  1806. ),
  1807. SlotSelectionState(
  1808. active_slot_count=raw["activeCount"], active_is_candidate=raw["activeIsCandidate"],
  1809. active_has_unavailable_class=raw["activeUnavailable"], active_has_red_dot=raw["activeRedDot"],
  1810. active_hidden_input_count=raw["activeInputCount"],
  1811. active_daily_id_matches_candidate=raw["activeIdMatches"],
  1812. active_day_matches_candidate=raw["activeDayMatches"],
  1813. active_time_matches_candidate=raw["activeTimeMatches"],
  1814. active_capacity_matches_candidate=raw["activeCapacityMatches"],
  1815. ),
  1816. )
  1817. def verify_precommit_selection(
  1818. page: object, *, runtime_service: str, approval: PrecommitApproval,
  1819. ) -> PrecommitApproval:
  1820. """Read the current selected slot; never select, refresh, or submit anything.
  1821. The caller still owns applicant/session binding and freshness of the Book
  1822. inventory. This is a consistency check, not a reservation or inventory lock.
  1823. """
  1824. if not isinstance(approval, PrecommitApproval):
  1825. raise CalendarBookError("Book selection requires a precommit approval")
  1826. try:
  1827. if read_calendar_service(page) != runtime_service:
  1828. raise CalendarBookError("Book Calendar runtime service changed")
  1829. raw = _snapshot(page, runtime_service, approval.candidate.day, approval.candidate, click=False)
  1830. return _approve_selection_snapshot(approval.calendar_day, approval.candidate, raw)
  1831. except CalendarBookError:
  1832. raise
  1833. except Exception:
  1834. raise CalendarBookError("Book precommit readback failed") from None
  1835. def select_slot_before_final(
  1836. page: object, *, target_day: date, availability_packet: object, time_slots_packet: object,
  1837. ) -> PrecommitApproval | None:
  1838. """Select one positive slot from caller-captured Book packets; never submit.
  1839. Both packets must be fresh captures from this page. Their content alone
  1840. cannot prove capture time, applicant identity or route continuity. The
  1841. orchestrator must establish these preconditions before calling this method.
  1842. """
  1843. if type(target_day) is not date:
  1844. raise CalendarBookError("Book target day must be a date")
  1845. try:
  1846. service = read_calendar_service(page)
  1847. guard_calendar(page)
  1848. try:
  1849. probe = parse_availability_packet(availability_packet)
  1850. if probe.selected_month != (target_day.year, target_day.month):
  1851. raise CalendarBookError("Book Availability belongs to another month")
  1852. slots = parse_book_time_slots(
  1853. time_slots_packet, target_day=target_day, runtime_service_id=service,
  1854. )
  1855. days = [item for item in probe.days if item.day == target_day]
  1856. candidates = available_slot_candidates(slots, start_day=target_day, end_day=target_day)
  1857. if not days or not days[0].is_available:
  1858. if candidates:
  1859. raise CalendarBookError("Book Availability and TimeSlots disagree")
  1860. return None
  1861. if not candidates:
  1862. return None
  1863. candidate = candidates[0]
  1864. before = _snapshot(page, service, target_day, candidate, click=False)
  1865. _require_ready(before, target_day)
  1866. if before["clicked"]:
  1867. raise CalendarBookError("Book read-only snapshot unexpectedly clicked")
  1868. if not (before["activeCount"] == 1 and before["activeIsCandidate"]):
  1869. acted = _snapshot(page, service, target_day, candidate, click=True)
  1870. _require_ready(acted, target_day)
  1871. if not acted["clicked"]:
  1872. raise CalendarBookError("Book slot click was not acknowledged")
  1873. after = _snapshot(page, service, target_day, candidate, click=False)
  1874. return _approve_selection_snapshot(days[0], candidate, after)
  1875. finally:
  1876. guard_calendar(page)
  1877. except CalendarBookError:
  1878. raise
  1879. except ItaProtocolError as exc:
  1880. raise CalendarBookError(f"Book precommit rejected ({exc.code})") from None
  1881. except Exception:
  1882. raise CalendarBookError("Book Calendar selection or final guard failed") from None
  1883. DATE_SELECTION_SCRIPT = r"""
  1884. /* coordinate:ita-book-date-selection */
  1885. const [serviceId, day, shouldClick] = arguments;
  1886. const services = Array.from(document.querySelectorAll('#idServizio'));
  1887. const runtimeMatches = window.location.origin === 'https://prenotami.esteri.it' &&
  1888. window.location.pathname === '/BookingCalendar' && services.length === 1 &&
  1889. services[0].value === serviceId;
  1890. const buttons = Array.from(document.querySelectorAll('#btnPrenotaNoOtp'));
  1891. const finalGuarded = buttons.length === 1 && buttons[0].disabled === true &&
  1892. buttons[0].dataset.coordinateFinalGuard === 'enabled';
  1893. const candidates = Array.from(document.querySelectorAll('.events a[data-date]'))
  1894. .filter((link) => link.dataset.date === day);
  1895. const link = candidates.length === 1 ? candidates[0] : null;
  1896. const enabled = (element) => {
  1897. if (!element || !element.isConnected || element.hasAttribute('disabled') ||
  1898. element.getAttribute('aria-disabled') === 'true' ||
  1899. element.classList.contains('disabled') || element.classList.contains('notAvailableDay') ||
  1900. element.classList.contains('input-async-disabilitato') ||
  1901. !element.classList.contains('input-async-abilitato')) return false;
  1902. const style = window.getComputedStyle(element);
  1903. // Calendar timeline links can have zero layout size while logically enabled.
  1904. // The site's initialization uses HTMLElement.click(), as we do here, rather
  1905. // than a pointer hit. Keep disabled/style checks and response/date readback;
  1906. // do not require a clickable rectangle for this native date action.
  1907. return style.display !== 'none' && style.visibility !== 'hidden' &&
  1908. style.pointerEvents !== 'none' && Number.parseFloat(style.opacity || '1') > 0;
  1909. };
  1910. const timeline = Array.from(document.querySelectorAll('.events a.selected'));
  1911. const content = Array.from(document.querySelectorAll('.events-content li.selected'));
  1912. const selectedMatches = timeline.length === 1 && content.length === 1 &&
  1913. timeline[0].dataset.date === day && content[0].dataset.date === day &&
  1914. document.querySelector('.selected') === timeline[0];
  1915. const candidateEnabled = enabled(link);
  1916. let clicked = false;
  1917. if (shouldClick === true && runtimeMatches && finalGuarded && candidateEnabled && !selectedMatches) {
  1918. link.click();
  1919. clicked = true;
  1920. }
  1921. return {runtimeMatches, finalGuarded, candidateCount: candidates.length,
  1922. candidateEnabled, selectedMatches, clicked};
  1923. """
  1924. @dataclass(frozen=True, slots=True)
  1925. class _CapturedMonth:
  1926. probe: CalendarProbeResult
  1927. availability_packet: object = field(repr=False)
  1928. availability_service: str = field(repr=False)
  1929. automatic_day: date | None = None
  1930. automatic_slots_packet: object | None = field(default=None, repr=False)
  1931. def book_date_preferences(user_inputs: Mapping[str, object]) -> tuple[date, date]:
  1932. """Use the VFS preference keys and inclusive bounds without mutating inputs."""
  1933. if not isinstance(user_inputs, Mapping):
  1934. raise CalendarBookError("Book user inputs must be a mapping")
  1935. dates = []
  1936. for key, default in (("expected_start_date", "2000-01-01"),
  1937. ("expected_end_date", "2100-01-01")):
  1938. value = user_inputs.get(key, default)
  1939. try:
  1940. parsed = date.fromisoformat(value) if isinstance(value, str) else None
  1941. except ValueError:
  1942. parsed = None
  1943. if parsed is None or parsed.isoformat() != value:
  1944. raise CalendarBookError(f"Book {key} must use YYYY-MM-DD")
  1945. dates.append(parsed)
  1946. if dates[0] > dates[1]:
  1947. raise CalendarBookError("Book date preference start exceeds end")
  1948. return dates[0], dates[1]
  1949. def _require_context(page: object, service: str, session_is_current: Callable[[], bool]) -> None:
  1950. if session_is_current() is not True:
  1951. raise CalendarBookError("Book applicant, route or browser Session changed")
  1952. if read_calendar_service(page) != service:
  1953. raise CalendarBookError("Book Calendar runtime service changed")
  1954. guard_calendar(page)
  1955. def _require_packet_tab(page: object, packet: object) -> None:
  1956. tab = getattr(page, "tab_id", None)
  1957. if not isinstance(tab, str) or not tab or getattr(packet, "tab_id", None) != tab:
  1958. raise CalendarBookError("Book response did not belong to the current browser tab")
  1959. if getattr(packet, "is_failed", False) is not False:
  1960. raise CalendarBookError("Book browser request failed")
  1961. def _post_body(packet: object) -> dict:
  1962. body = packet.request.postData
  1963. if isinstance(body, str):
  1964. body = json.loads(body)
  1965. if not isinstance(body, dict):
  1966. raise CalendarBookError("Book request body was not an object")
  1967. return body
  1968. def _date_snapshot(page: object, service: str, day: date, *, click: bool = False) -> dict:
  1969. raw = page.run_js(DATE_SELECTION_SCRIPT, service, day.isoformat(), click)
  1970. boolean_keys = {"runtimeMatches", "finalGuarded", "candidateEnabled", "selectedMatches", "clicked"}
  1971. if not isinstance(raw, dict) or set(raw) != boolean_keys | {"candidateCount"}:
  1972. raise CalendarBookError("Book date control structure changed")
  1973. if any(type(raw[key]) is not bool for key in boolean_keys):
  1974. raise CalendarBookError("Book date control types changed")
  1975. require_plain_nonnegative_int(raw["candidateCount"], "candidateCount")
  1976. if not raw["runtimeMatches"] or not raw["finalGuarded"] or raw["candidateCount"] > 1:
  1977. raise CalendarBookError("Book date control context was not unique and guarded")
  1978. if not click and raw["clicked"]:
  1979. raise CalendarBookError("Book date readback unexpectedly clicked")
  1980. return raw
  1981. def _wait_selected_day(page: object, service: str, day: date, *, timeout: float) -> None:
  1982. deadline = time.monotonic() + timeout
  1983. while True:
  1984. raw = _date_snapshot(page, service, day)
  1985. if raw["candidateCount"] == 1 and raw["selectedMatches"]:
  1986. return
  1987. if time.monotonic() >= deadline:
  1988. raise CalendarBookError("Book selected date did not match the response before timeout")
  1989. time.sleep(0.1)
  1990. def _click_date(page: object, service: str, day: date, *, timeout: float) -> None:
  1991. deadline = time.monotonic() + timeout
  1992. while True:
  1993. raw = _date_snapshot(page, service, day)
  1994. if raw["selectedMatches"]:
  1995. raise CalendarBookError("Book date is already selected without a fresh captured response")
  1996. if raw["candidateCount"] == 1 and raw["candidateEnabled"]:
  1997. break
  1998. if time.monotonic() >= deadline:
  1999. raise CalendarBookError("Book date control was not ready before timeout")
  2000. time.sleep(0.1)
  2001. acted = _date_snapshot(page, service, day, click=True)
  2002. if not acted["clicked"]:
  2003. raise CalendarBookError("Book date click was not acknowledged")
  2004. def _capture_month(
  2005. page: object, *, action: Callable[[], None], service: str,
  2006. session_is_current: Callable[[], bool], timeout: float, dom_timeout: float,
  2007. previous: _CapturedMonth | None = None,
  2008. ) -> _CapturedMonth:
  2009. """Capture Availability plus the site's automatic first-day TimeSlots."""
  2010. _require_context(page, service, session_is_current)
  2011. page.listen.start([AVAILABILITY_PATH, TIME_SLOTS_PATH], method="POST")
  2012. try:
  2013. action()
  2014. wait_for_calendar_service(
  2015. page, session_is_current=session_is_current,
  2016. expected_service=service, timeout=min(dom_timeout, timeout),
  2017. )
  2018. _require_context(page, service, session_is_current)
  2019. deadline = time.monotonic() + timeout
  2020. captured = {}
  2021. probe = None
  2022. # Only two matching responses belong to one normal month-load action.
  2023. for _ in range(2):
  2024. remaining = deadline - time.monotonic()
  2025. if remaining <= 0:
  2026. raise CalendarBookError("Book month responses exceeded the time budget")
  2027. packet = page.listen.wait(timeout=remaining, raise_err=False)
  2028. if not packet:
  2029. raise CalendarBookError("Book month response was not observed before timeout")
  2030. _require_packet_tab(page, packet)
  2031. status = packet.response.status
  2032. if type(status) is not int or status != 200:
  2033. raise CalendarBookError("Book Calendar response status was not 200",
  2034. http_status=status if type(status) is int else None)
  2035. path, _ = same_origin_path(packet.url)
  2036. if path not in {AVAILABILITY_PATH, TIME_SLOTS_PATH} or path in captured:
  2037. raise CalendarBookError("Book month produced an unexpected or duplicate response")
  2038. captured[path] = packet
  2039. if path == AVAILABILITY_PATH:
  2040. probe = parse_availability_packet(packet)
  2041. if previous and probe.selected_month != next_month_value(previous.probe.selected_month):
  2042. raise CalendarBookError("Book Calendar did not advance exactly one month")
  2043. if not probe.days or TIME_SLOTS_PATH in captured:
  2044. break
  2045. elif probe is not None:
  2046. break
  2047. if probe is None:
  2048. raise CalendarBookError("Book month did not return Availability")
  2049. availability_packet = captured[AVAILABILITY_PATH]
  2050. availability_service = _runtime_id(_post_body(availability_packet).get("_Servizio"))
  2051. if previous and availability_service != previous.availability_service:
  2052. raise CalendarBookError("Book Availability runtime service changed")
  2053. automatic = captured.get(TIME_SLOTS_PATH)
  2054. automatic_day = None
  2055. if probe.days:
  2056. if automatic is None:
  2057. raise CalendarBookError("Book automatic day response was not captured")
  2058. automatic_day = _request_day(_post_body(automatic).get("selectedDay"))
  2059. if automatic_day not in {item.day for item in probe.days}:
  2060. raise CalendarBookError("Book automatic day escaped current Availability")
  2061. auto_slots = parse_book_time_slots(automatic, target_day=automatic_day, runtime_service_id=service)
  2062. auto_inventory = next(item for item in probe.days if item.day == automatic_day)
  2063. if not auto_inventory.is_available and available_slot_candidates(auto_slots):
  2064. raise CalendarBookError("Book automatic Availability and TimeSlots disagree")
  2065. _wait_selected_day(page, service, automatic_day, timeout=dom_timeout)
  2066. elif automatic is not None:
  2067. raise CalendarBookError("Book empty Availability unexpectedly returned TimeSlots")
  2068. _require_context(page, service, session_is_current)
  2069. return _CapturedMonth(probe, availability_packet, availability_service, automatic_day, automatic)
  2070. finally:
  2071. page.listen.stop()
  2072. def _try_day(
  2073. page: object, month: _CapturedMonth, day: date, *, service: str,
  2074. session_is_current: Callable[[], bool], timeout: float, dom_timeout: float,
  2075. ) -> PrecommitApproval | None:
  2076. _require_context(page, service, session_is_current)
  2077. current_date = _date_snapshot(page, service, day)
  2078. if day == month.automatic_day and current_date["selectedMatches"]:
  2079. times_packet = month.automatic_slots_packet
  2080. _wait_selected_day(page, service, day, timeout=dom_timeout)
  2081. else:
  2082. times_packet = listen_once(
  2083. page, target=TIME_SLOTS_PATH, method="POST",
  2084. action=lambda: _click_date(page, service, day, timeout=dom_timeout),
  2085. timeout=timeout,
  2086. )
  2087. _require_packet_tab(page, times_packet)
  2088. parse_book_time_slots(times_packet, target_day=day, runtime_service_id=service)
  2089. _wait_selected_day(page, service, day, timeout=dom_timeout)
  2090. slots = parse_book_time_slots(times_packet, target_day=day, runtime_service_id=service)
  2091. candidates = available_slot_candidates(slots, start_day=day, end_day=day)
  2092. if not candidates:
  2093. # Inventory competition is not a protocol error. No slot was clicked.
  2094. _require_context(page, service, session_is_current)
  2095. return None
  2096. deadline = time.monotonic() + dom_timeout
  2097. while True:
  2098. _require_context(page, service, session_is_current)
  2099. raw = _snapshot(page, service, day, candidates[0], click=False)
  2100. if not raw["runtimeMatches"] or not raw["finalGuarded"] or raw["candidateCount"] > 1:
  2101. raise CalendarBookError("Book slot DOM changed its context or uniqueness")
  2102. if raw["candidateReady"]:
  2103. _require_ready(raw, day)
  2104. break
  2105. if time.monotonic() >= deadline:
  2106. raise CalendarBookError("Book slot DOM did not match the response before timeout")
  2107. time.sleep(0.1)
  2108. approval = select_slot_before_final(
  2109. page, target_day=day, availability_packet=month.availability_packet,
  2110. time_slots_packet=times_packet,
  2111. )
  2112. _require_context(page, service, session_is_current)
  2113. return approval
  2114. def recheck_calendar_before_final(
  2115. page: object, *, lookahead_months: int, start_day: date, end_day: date,
  2116. session_is_current: Callable[[], bool], preferred_day: date | None = None,
  2117. month_click_interval_seconds: float = DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
  2118. timeout: float = 30, dom_timeout: float = 5,
  2119. log: Callable[[str], None] | None = None,
  2120. ) -> PrecommitApproval | None:
  2121. """Fresh Book-only scan with an optional date hint; never submit a booking.
  2122. There are at most two bounded passes: the hinted day, then an ascending
  2123. fallback. The caller must attest the prepared applicant/route Session via
  2124. session_is_current. No external snapshot or cached response is accepted.
  2125. """
  2126. try:
  2127. # Use existing pure validators before starting any browser action.
  2128. month_starts(date(2000, 1, 1), lookahead_months)
  2129. if type(start_day) is not date or type(end_day) is not date:
  2130. raise CalendarBookError("Book date bounds must be dates")
  2131. available_calendar_days((), start_day=start_day, end_day=end_day)
  2132. if preferred_day is not None and type(preferred_day) is not date:
  2133. raise CalendarBookError("Book preferred day must be a date")
  2134. for value in (timeout, dom_timeout, month_click_interval_seconds):
  2135. if type(value) not in (int, float) or not 0 <= value < float("inf"):
  2136. raise CalendarBookError("Book time budget must be finite and nonnegative")
  2137. if timeout == 0 or not callable(session_is_current):
  2138. raise CalendarBookError("Book requires a positive timeout and a Session check")
  2139. service = read_calendar_service(page)
  2140. _require_context(page, service, session_is_current)
  2141. common = dict(service=service, session_is_current=session_is_current,
  2142. timeout=timeout, dom_timeout=dom_timeout)
  2143. def initial() -> _CapturedMonth:
  2144. return _capture_month(page, action=lambda: refresh_calendar(page), **common)
  2145. def advance(previous: _CapturedMonth) -> _CapturedMonth:
  2146. if month_click_interval_seconds:
  2147. time.sleep(month_click_interval_seconds)
  2148. return _capture_month(page, action=lambda: click_next_month(page), previous=previous, **common)
  2149. def positive_days(month: _CapturedMonth) -> tuple:
  2150. return available_calendar_days(month.probe.days, start_day=start_day, end_day=end_day)
  2151. first = initial()
  2152. anchor = first.probe.selected_month
  2153. current = first
  2154. attempted = set()
  2155. if preferred_day is not None and start_day <= preferred_day <= end_day:
  2156. offset = (preferred_day.year - anchor[0]) * 12 + preferred_day.month - anchor[1]
  2157. if 0 <= offset < lookahead_months:
  2158. for _ in range(offset):
  2159. current = advance(current)
  2160. if preferred_day in {item.day for item in positive_days(current)}:
  2161. attempted.add(preferred_day)
  2162. approval = _try_day(page, current, preferred_day, **common)
  2163. if approval is not None:
  2164. return approval
  2165. # A failed hint cannot cause a stale earlier month's response
  2166. # to be reused. Restart the native scan once and recapture.
  2167. first = initial()
  2168. if (first.probe.selected_month != anchor or
  2169. first.availability_service != current.availability_service):
  2170. raise CalendarBookError("Book fallback restart changed the Calendar anchor")
  2171. current = first
  2172. for index in range(lookahead_months):
  2173. if current.probe.selected_month > (end_day.year, end_day.month):
  2174. return None
  2175. days = positive_days(current)
  2176. if log:
  2177. log(f"Italy Book Calendar month={month_text(current.probe.selected_month)} candidates={len(days)}")
  2178. for item in days:
  2179. if item.day in attempted:
  2180. continue
  2181. attempted.add(item.day)
  2182. approval = _try_day(page, current, item.day, **common)
  2183. if approval is not None:
  2184. return approval
  2185. if current.probe.selected_month >= (end_day.year, end_day.month):
  2186. return None
  2187. if index + 1 < lookahead_months:
  2188. current = advance(current)
  2189. return None
  2190. except CalendarBookError:
  2191. raise
  2192. except ItaProtocolError as exc:
  2193. raise CalendarBookError(f"Book Calendar protocol rejected ({exc.code})") from None
  2194. except Exception:
  2195. raise CalendarBookError("Book Calendar recheck failed; no further action was attempted") from None
  2196. finally:
  2197. # Do not leave the final button enabled after a native refresh or error.
  2198. try:
  2199. if same_origin_path(page.url)[0] == CALENDAR_PATH:
  2200. guard_calendar(page)
  2201. except Exception:
  2202. raise CalendarBookError("Book final-button guard could not be verified") from None
  2203. # ============================================================================
  2204. # BOOKING_FINAL (from plugins/ita_booking_final.py)
  2205. # ============================================================================
  2206. """Italy final-stage building blocks shared by production and local validation.
  2207. ReservationSnapshot is an internal read-port contract, NOT a discovered website
  2208. schema. A real adapter must prove identity, status and pagination completeness
  2209. before this module can be enabled. Attempts are process-local; the existing
  2210. Booker task pause handles uncertain outcomes. No automatic retry is provided.
  2211. The opt-in local evidence gate adds a checkout-local fence and human confirmation;
  2212. it observes unknown receipts without claiming that production success is proven.
  2213. """
  2214. import json
  2215. import re
  2216. import threading
  2217. import time
  2218. from dataclasses import dataclass, field
  2219. from datetime import date
  2220. from enum import Enum
  2221. from typing import Callable
  2222. from urllib.parse import parse_qsl, urljoin
  2223. from vs_types import VSBookResult, BookingOutcomeUnknownError
  2224. FINAL_PATH = "/BookingCalendar/InsertNewBooking"
  2225. class FinalBookingError(RuntimeError):
  2226. """Fixed messages only: do not include page text, requests or credentials."""
  2227. class FinalOutcomeUnknown(FinalBookingError, BookingOutcomeUnknownError):
  2228. def __init__(self):
  2229. super().__init__("Italy final outcome requires read-only reconciliation")
  2230. class ReservationState(str, Enum):
  2231. ACTIVE = "active"
  2232. CANCELLED = "cancelled"
  2233. WAITLIST = "waitlist"
  2234. UNKNOWN = "unknown"
  2235. class SubmissionSignal(str, Enum):
  2236. ACCEPTED = "accepted_hint"
  2237. REJECTED = "rejected_hint"
  2238. UNKNOWN = "unknown"
  2239. def _final_text(value: object) -> bool:
  2240. return (isinstance(value, str) and 0 < len(value) <= 256 and value == value.strip()
  2241. and not any(ord(ch) < 32 or ord(ch) == 127 for ch in value))
  2242. @dataclass(frozen=True, slots=True)
  2243. class FinalTarget:
  2244. applicant: str = field(repr=False)
  2245. session_key: str = field(repr=False)
  2246. tab_id: str = field(repr=False)
  2247. routing_key: str
  2248. service_id: str = field(repr=False)
  2249. runtime_service: str = field(repr=False)
  2250. approval: PrecommitApproval = field(repr=False)
  2251. service_name: str | None = field(default=None, repr=False)
  2252. def __post_init__(self):
  2253. if not all(_final_text(getattr(self, key)) for key in (
  2254. "applicant", "session_key", "tab_id", "routing_key", "service_id", "runtime_service",
  2255. )):
  2256. raise FinalBookingError("Italy final target identity is invalid")
  2257. if not isinstance(self.approval, PrecommitApproval):
  2258. raise FinalBookingError("Italy final requires a Book precommit approval")
  2259. if self.service_name is not None and not _final_text(self.service_name):
  2260. raise FinalBookingError("Italy final displayed service is invalid")
  2261. day, slot = self.approval.calendar_day, self.approval.candidate
  2262. if (not isinstance(day, CalendarDay) or not isinstance(slot, SlotCandidate)
  2263. or day.day != slot.day or not day.is_available or not slot.is_available):
  2264. raise FinalBookingError("Italy final target inventory is inconsistent")
  2265. @dataclass(frozen=True, slots=True, repr=False)
  2266. class VerifiedSubmission:
  2267. """Native POST matched this exact session/tab/precommit; not a receipt field.
  2268. Created from an observed packet, even when its RESPONSE schema is unknown.
  2269. A caller must also enforce the one-request audit before passing it to a read port.
  2270. """
  2271. target: FinalTarget
  2272. @dataclass(frozen=True, slots=True)
  2273. class ReservationRecord:
  2274. """Normalized by a verified, identity-bound site reader.
  2275. time_label is an independently evidenced selected interval, not an interval
  2276. inferred from appointment_time. A real receipt may expose only the assigned
  2277. HH:mm time. That is enough to preserve cancelled history, not prove a new
  2278. record belongs to the selected slot. Cancelled history may have an unbound
  2279. service_id only with a fingerprint retaining all observed business facts.
  2280. This exception never establishes a target-service or selected-slot binding.
  2281. submission is a separate verified native-request witness, used by the bound
  2282. real read port for new active receipts. It never rewrites the receipt fields.
  2283. """
  2284. reference: str = field(repr=False)
  2285. service_id: str | None = field(repr=False)
  2286. day: date
  2287. time_label: str | None
  2288. state: ReservationState
  2289. appointment_time: str | None = None
  2290. receipt_fingerprint: str | None = field(default=None, repr=False)
  2291. submission: VerifiedSubmission | None = field(default=None, repr=False)
  2292. def _valid_receipt_time(record: ReservationRecord) -> bool:
  2293. interval, assigned = record.time_label, record.appointment_time
  2294. if interval is None and assigned is None:
  2295. return False
  2296. if interval is not None and (
  2297. not isinstance(interval, str)
  2298. or re.fullmatch(r"(?:[01][0-9]|2[0-3]):[0-5][0-9] - (?:[01][0-9]|2[0-3]):[0-5][0-9]", interval) is None
  2299. or interval[:5] >= interval[-5:]
  2300. ):
  2301. return False
  2302. assigned_valid = assigned is None or (
  2303. isinstance(assigned, str)
  2304. and re.fullmatch(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]", assigned) is not None
  2305. )
  2306. if not assigned_valid:
  2307. return False
  2308. # Negative consistency check only: containment never creates a binding.
  2309. return interval is None or assigned is None or interval[:5] <= assigned <= interval[-5:]
  2310. @dataclass(frozen=True, slots=True)
  2311. class ReservationSnapshot:
  2312. applicant: str = field(repr=False)
  2313. session_key: str = field(repr=False)
  2314. captured_at: float
  2315. complete: bool
  2316. records: tuple[ReservationRecord, ...] = field(repr=False)
  2317. # Reuse the actual slot readback JS in the same synchronous browser turn as the
  2318. # native final click, so a Python/browser round trip cannot select another slot.
  2319. # Never reconstruct the POST payload: the website handler remains its owner.
  2320. NATIVE_FINAL_SCRIPT = r"""
  2321. /* coordinate:ita-native-final-once */
  2322. const [serviceId, day, dailyId, timeLabel, capacity] = arguments;
  2323. const state = (function () {
  2324. """ + SLOT_SELECTION_SCRIPT + r"""
  2325. }).apply(null, [serviceId, day, dailyId, timeLabel, capacity, false]);
  2326. const positive = ['runtimeMatches', 'finalGuarded', 'firstSelectedMatches',
  2327. 'dayPositive', 'candidateReady', 'activeIsCandidate', 'activeIdMatches',
  2328. 'activeDayMatches', 'activeTimeMatches', 'activeCapacityMatches'];
  2329. const negative = ['dayDisabled', 'dayNegative', 'activeUnavailable', 'activeRedDot', 'clicked'];
  2330. const ready = positive.every(k => state[k] === true) && negative.every(k => state[k] === false) &&
  2331. ['matchingDateCount', 'candidateCount', 'activeCount', 'activeInputCount'].every(k => state[k] === 1) &&
  2332. JSON.stringify(state.timelineDays) === JSON.stringify([day]) &&
  2333. JSON.stringify(state.contentDays) === JSON.stringify([day]);
  2334. const buttons = Array.from(document.querySelectorAll('#btnPrenotaNoOtp'));
  2335. if (!ready || buttons.length !== 1 || !buttons[0].isConnected ||
  2336. buttons[0].dataset.coordinateFinalAttemptConsumed) return {clicked: false};
  2337. const button = buttons[0];
  2338. button.dataset.coordinateFinalAttemptConsumed = 'true';
  2339. try {
  2340. button.disabled = false;
  2341. button.removeAttribute('aria-disabled');
  2342. button.click();
  2343. return {clicked: true};
  2344. } finally {
  2345. button.disabled = true;
  2346. button.setAttribute('aria-disabled', 'true');
  2347. button.dataset.coordinateFinalGuard = 'enabled';
  2348. }
  2349. """
  2350. def _unique_object(pairs):
  2351. result = {}
  2352. for key, value in pairs:
  2353. if key in result:
  2354. raise ValueError("duplicate field")
  2355. result[key] = value
  2356. return result
  2357. def inspect_final_packet(packet: object, target: FinalTarget) -> tuple[SubmissionSignal, VerifiedSubmission | None, str]:
  2358. """Validate the observed request before interpreting a response as a hint.
  2359. Invalid metadata/HTTP/schema is UNKNOWN after a write, not a retryable
  2360. authentication/no-slot error. Never expose the raw server errorMessage.
  2361. """
  2362. evidence = None
  2363. reason = "request_metadata"
  2364. try:
  2365. path, parsed = same_origin_path(packet.url)
  2366. if (path != FINAL_PATH or parsed.query or parsed.fragment or packet.method != "POST"
  2367. or packet.tab_id != target.tab_id or getattr(packet, "is_failed", False)):
  2368. return SubmissionSignal.UNKNOWN, None, reason
  2369. reason = "request_fields"
  2370. body = packet.request.postData
  2371. if isinstance(body, str) and len(body) <= MAX_PROTOCOL_PAYLOAD_CHARS:
  2372. body = _unique_object(parse_qsl(body, keep_blank_values=True, strict_parsing=True))
  2373. if not isinstance(body, dict) or set(body) != {
  2374. "idCalendarioGiornaliero", "selectedDay", "selectedHour",
  2375. } or any(not isinstance(value, str) for value in body.values()):
  2376. return SubmissionSignal.UNKNOWN, None, reason
  2377. reason = "request_selection"
  2378. slot = target.approval.candidate
  2379. if body["idCalendarioGiornaliero"] != slot.daily_calendar_id or body["selectedDay"] != slot.day.isoformat():
  2380. return SubmissionSignal.UNKNOWN, None, reason
  2381. compact = lambda value: re.sub(r"\s+", "", value)
  2382. if compact(body["selectedHour"]) != compact(f"{slot.time_label}({slot.slots_free})"):
  2383. return SubmissionSignal.UNKNOWN, None, reason
  2384. evidence = VerifiedSubmission(target)
  2385. reason = "response_metadata"
  2386. response = packet.response
  2387. if type(response.status) is not int or response.status != 200:
  2388. return SubmissionSignal.UNKNOWN, evidence, reason
  2389. response_url = getattr(response, "url", None)
  2390. if response_url:
  2391. response_path, response_parsed = same_origin_path(response_url)
  2392. if response_path != FINAL_PATH or response_parsed.query or response_parsed.fragment:
  2393. return SubmissionSignal.UNKNOWN, evidence, reason
  2394. reason = "response_body"
  2395. raw = response.raw_body
  2396. if not isinstance(raw, str) or not 0 < len(raw) <= MAX_PROTOCOL_PAYLOAD_CHARS:
  2397. return SubmissionSignal.UNKNOWN, evidence, reason
  2398. data = json.loads(raw, object_pairs_hook=_unique_object)
  2399. reason = "response_fields"
  2400. if not isinstance(data, dict) or not {"errorMessage", "url"} <= set(data):
  2401. return SubmissionSignal.UNKNOWN, evidence, reason
  2402. error, destination = data["errorMessage"], data["url"]
  2403. if not isinstance(error, str) or not _final_text(destination):
  2404. return SubmissionSignal.UNKNOWN, evidence, reason
  2405. reason = "response_destination"
  2406. same_origin_path(urljoin(packet.url, destination))
  2407. return (SubmissionSignal.REJECTED if error.strip() else SubmissionSignal.ACCEPTED), evidence, "recognized"
  2408. except Exception:
  2409. return SubmissionSignal.UNKNOWN, evidence, reason
  2410. def classify_final_packet(packet: object, target: FinalTarget) -> SubmissionSignal:
  2411. return inspect_final_packet(packet, target)[0]
  2412. class NativeFinalSubmitter:
  2413. """One native click with the existing listener; no navigation/retry/OTP.
  2414. A process-local latch is not a durable task fence. Production reaches this
  2415. adapter only with explicit final-submit configuration; default pre-final
  2416. CLIs never call it. The opt-in local evidence gate has its own persistent fence.
  2417. """
  2418. def __init__(self, page: object, target: FinalTarget, session_is_current: Callable[[], bool]):
  2419. self.page, self.target, self.session_is_current = page, target, session_is_current
  2420. self._lock = threading.Lock()
  2421. self._consumed = False
  2422. self.submitted_selection: VerifiedSubmission | None = None
  2423. self.diagnostic = {"requestMatched": False, "reason": "not_observed"}
  2424. def __call__(self) -> SubmissionSignal:
  2425. with self._lock:
  2426. if self._consumed:
  2427. raise FinalBookingError("Italy native final attempt is already consumed")
  2428. self._consumed = True
  2429. target = self.target
  2430. def require_context():
  2431. if (self.session_is_current() is not True or self.page.tab_id != target.tab_id
  2432. or same_origin_path(self.page.url)[0] != CALENDAR_PATH):
  2433. raise FinalBookingError("Italy native final context changed")
  2434. def action():
  2435. require_context()
  2436. slot = target.approval.candidate
  2437. raw = self.page.run_js(
  2438. NATIVE_FINAL_SCRIPT, target.runtime_service, slot.day.isoformat(),
  2439. slot.daily_calendar_id, slot.time_label, slot.slots_free,
  2440. )
  2441. if raw != {"clicked": True} or type(raw.get("clicked")) is not bool:
  2442. raise FinalBookingError("Italy native final click was not acknowledged")
  2443. try:
  2444. require_context()
  2445. verify_precommit_selection(self.page, runtime_service=target.runtime_service, approval=target.approval)
  2446. packet = listen_once(self.page, target=FINAL_PATH, method="POST", action=action, timeout=30)
  2447. signal, self.submitted_selection, reason = inspect_final_packet(packet, target)
  2448. self.diagnostic = {"requestMatched": self.submitted_selection is not None, "reason": reason}
  2449. return signal
  2450. except Exception:
  2451. # A lost browser acknowledgement can follow a committed write.
  2452. self.diagnostic = {"requestMatched": False, "reason": "native_or_listener_error"}
  2453. return SubmissionSignal.UNKNOWN
  2454. class FinalBookingAttempt:
  2455. """Single-use orchestration; reconciliation only after a possible write.
  2456. read_reservations must perform a fresh, complete, read-only site read bound
  2457. to this applicant/session. The real read port accepts only empty/cancelled
  2458. baselines, then binds new confirmed receipts to a verified native request. submit_native
  2459. is an injected NativeFinalSubmitter (or an offline test double), not an HTTP
  2460. replay function. Context checks must work after a same-session redirect.
  2461. """
  2462. def __init__(
  2463. self, target: FinalTarget, *, read_reservations: Callable[[], ReservationSnapshot],
  2464. submit_native: Callable[[], SubmissionSignal], session_is_current: Callable[[], bool],
  2465. ):
  2466. if not isinstance(target, FinalTarget) or not all(callable(item) for item in (
  2467. read_reservations, submit_native, session_is_current,
  2468. )):
  2469. raise FinalBookingError("Italy final adapters are required")
  2470. self.target = target
  2471. self._read_reservations = read_reservations
  2472. self._submit_native = submit_native
  2473. self._session_is_current = session_is_current
  2474. self._lock = threading.Lock()
  2475. self._state = "ready"
  2476. self._signal = SubmissionSignal.UNKNOWN
  2477. self._before: ReservationSnapshot | None = None
  2478. @property
  2479. def state(self) -> str:
  2480. return self._state
  2481. def _require_context(self):
  2482. if self._session_is_current() is not True:
  2483. raise FinalBookingError("Italy final applicant or Session changed")
  2484. def _read(self) -> ReservationSnapshot:
  2485. self._require_context()
  2486. started = time.monotonic()
  2487. snapshot = self._read_reservations()
  2488. self._require_context()
  2489. now = time.monotonic()
  2490. if (not isinstance(snapshot, ReservationSnapshot) or snapshot.complete is not True
  2491. or snapshot.applicant != self.target.applicant or snapshot.session_key != self.target.session_key
  2492. or type(snapshot.captured_at) not in (int, float) or not started <= snapshot.captured_at <= now
  2493. or not isinstance(snapshot.records, tuple) or len(snapshot.records) > 512):
  2494. raise FinalBookingError("Italy reservation snapshot is incomplete or not current")
  2495. seen = set()
  2496. for record in snapshot.records:
  2497. if (not isinstance(record, ReservationRecord) or not _final_text(record.reference)
  2498. or record.reference in seen or type(record.day) is not date
  2499. or not _valid_receipt_time(record)
  2500. or not isinstance(record.state, ReservationState) or record.state is ReservationState.UNKNOWN):
  2501. raise FinalBookingError("Italy reservation records require verified identity and status")
  2502. fingerprint = record.receipt_fingerprint
  2503. if fingerprint is not None and (not isinstance(fingerprint, str) or
  2504. re.fullmatch(r"[0-9a-f]{64}", fingerprint) is None):
  2505. raise FinalBookingError("Italy receipt fingerprint is invalid")
  2506. if record.submission is not None and not self._submitted_binding(record):
  2507. raise FinalBookingError("Italy receipt submission evidence does not match this attempt")
  2508. if not _final_text(record.service_id) and not (
  2509. record.service_id is None and fingerprint is not None and
  2510. (record.state is ReservationState.CANCELLED or self._submitted_binding(record))):
  2511. raise FinalBookingError("Italy live reservation service binding is unverified")
  2512. seen.add(record.reference)
  2513. return snapshot
  2514. def _submitted_binding(self, record: ReservationRecord) -> bool:
  2515. slot = self.target.approval.candidate
  2516. return (self._state in {"submitted", "unknown"} and
  2517. isinstance(record.submission, VerifiedSubmission) and
  2518. record.submission.target == self.target and _final_text(self.target.service_name) and
  2519. record.state is ReservationState.ACTIVE and record.service_id is None and
  2520. record.time_label is None and record.receipt_fingerprint is not None and
  2521. record.day == slot.day and isinstance(record.appointment_time, str) and
  2522. slot.time_label[:5] <= record.appointment_time <= slot.time_label[-5:])
  2523. def _live(self, snapshot: ReservationSnapshot) -> list[ReservationRecord]:
  2524. return [record for record in snapshot.records if (record.service_id == self.target.service_id or
  2525. self._submitted_binding(record))
  2526. and record.state in {ReservationState.ACTIVE, ReservationState.WAITLIST}]
  2527. def execute(self, *, enabled: bool = False) -> VSBookResult:
  2528. if enabled is not True:
  2529. raise FinalBookingError("Italy final submission is disabled")
  2530. if not self._lock.acquire(blocking=False):
  2531. raise FinalBookingError("Italy final attempt is already running")
  2532. try:
  2533. if self._state != "ready":
  2534. raise FinalBookingError("Italy final attempt is already consumed")
  2535. self._state = "checking"
  2536. try:
  2537. self._before = self._read()
  2538. self._require_context()
  2539. except Exception:
  2540. self._state = "blocked"
  2541. raise FinalBookingError("Italy final preflight blocked; no submission attempted") from None
  2542. if self._live(self._before):
  2543. self._state = "blocked"
  2544. raise FinalBookingError("Italy service already has an active reservation or waitlist")
  2545. self._state = "submitted"
  2546. try:
  2547. signal = self._submit_native()
  2548. self._signal = signal if isinstance(signal, SubmissionSignal) else SubmissionSignal.UNKNOWN
  2549. except Exception:
  2550. self._signal = SubmissionSignal.UNKNOWN
  2551. return self._reconcile()
  2552. finally:
  2553. # Ctrl-C/SystemExit must not make a possibly dispatched write look
  2554. # unattempted, nor make read-only reconciliation impossible.
  2555. if self._state == "submitted":
  2556. self._state = "unknown"
  2557. elif self._state == "checking":
  2558. self._state = "blocked"
  2559. self._lock.release()
  2560. def reconcile(self) -> VSBookResult:
  2561. """One read-only check. Never enters the native submit path."""
  2562. if not self._lock.acquire(blocking=False):
  2563. raise FinalBookingError("Italy final attempt is already running")
  2564. try:
  2565. if self._state != "unknown":
  2566. raise FinalBookingError("Italy final attempt does not need reconciliation")
  2567. return self._reconcile()
  2568. finally:
  2569. self._lock.release()
  2570. def _reconcile(self) -> VSBookResult:
  2571. self._state = "unknown"
  2572. try:
  2573. after = self._read()
  2574. live = self._live(after)
  2575. before = {record.reference: record for record in self._before.records}
  2576. after_by_id = {record.reference: record for record in after.records}
  2577. # Missing/modified history and unrelated new rows make attribution
  2578. # ambiguous. Do not equate a count increment with this appointment.
  2579. if any(after_by_id.get(key) != value for key, value in before.items()):
  2580. raise FinalOutcomeUnknown()
  2581. new = [record for record in after.records if record.reference not in before]
  2582. slot = self.target.approval.candidate
  2583. if (len(new) == 1 and len(live) == 1 and new[0] == live[0]
  2584. and live[0].state is ReservationState.ACTIVE and live[0].day == slot.day
  2585. and (live[0].time_label == slot.time_label or self._submitted_binding(live[0]))
  2586. and self._signal is not SubmissionSignal.REJECTED):
  2587. self._state = "confirmed"
  2588. return VSBookResult(
  2589. success=True, account=self.target.applicant, urn=live[0].reference,
  2590. book_date=slot.day.isoformat(), book_time=live[0].appointment_time or slot.time_label,
  2591. )
  2592. if not new and not live and self._signal is SubmissionSignal.REJECTED:
  2593. self._state = "rejected"
  2594. return VSBookResult(success=False, label="italy-final-rejected")
  2595. except Exception:
  2596. pass
  2597. self._state = "unknown"
  2598. raise FinalOutcomeUnknown() from None
  2599. # ============================================================================
  2600. # RESERVATION (from plugins/ita_reservation.py)
  2601. # ============================================================================
  2602. """Read-only Prenot@Mi receipt adapter, not a final-submit read port.
  2603. These objects contain observed display facts, not an inferred service/account
  2604. binding or proof linking an assigned appointment time to a selected slot.
  2605. Only observed Italian cancelled/confirmed states are classified; others stay UNKNOWN.
  2606. No navigation, credentials, OTP, form writes or final actions live here.
  2607. """
  2608. import math
  2609. import re
  2610. import time
  2611. from dataclasses import dataclass, field
  2612. from datetime import date
  2613. LIST_PATH = "/Reservation"
  2614. DETAIL_PREFIX = "/ReservationDetail/Index/"
  2615. HEADERS = ("Codice Prenotazione", "Ufficio", "Servizio", "Data", "Ora", "Stato", "Dati Richiedente")
  2616. DETAIL_LABELS = ("Servizio Consolare", "Servizio Erogato", "Codice Prenotazione",
  2617. "Tipo Prenotazione", "Data", "Ora", "Stato")
  2618. MONTHS_IT = ("gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio",
  2619. "agosto", "settembre", "ottobre", "novembre", "dicembre")
  2620. class ReservationReadError(ValueError):
  2621. """Only adapter-owned reason codes; never include DOM text or browser errors."""
  2622. def __init__(self, reason: str):
  2623. self.reason = reason
  2624. super().__init__(f"Italy reservation read rejected: {reason}")
  2625. @dataclass(frozen=True, slots=True, repr=False)
  2626. class ReservationDetail:
  2627. reference: str
  2628. office: str
  2629. service_name: str
  2630. booking_type: str
  2631. day: date
  2632. appointment_time: str
  2633. status_text: str
  2634. status_code: str
  2635. state: ReservationState
  2636. @dataclass(frozen=True, slots=True, repr=False)
  2637. class ReservationListRow:
  2638. reference: str
  2639. detail_url: str
  2640. office: str
  2641. service_name: str
  2642. day: date
  2643. appointment_time: str
  2644. status_text: str
  2645. state: ReservationState
  2646. @dataclass(frozen=True, slots=True)
  2647. class ReservationListing:
  2648. """Coverage of the loaded client data, NOT a fresh account-bound snapshot."""
  2649. rows: tuple[ReservationListRow, ...] = field(repr=False)
  2650. page_count: int
  2651. waitlist_count: int = 0
  2652. _CONTEXT_JS = r"""
  2653. const clean = s => String(s || '').replace(/\s+/g, ' ').trim();
  2654. const fail = reason => ({error: reason});
  2655. if (window.location.origin !== 'https://prenotami.esteri.it') return fail('wrong_page');
  2656. if (document.readyState !== 'complete') return fail('not_ready');
  2657. if (!document.querySelector('.app-menu')) return fail('authentication_missing');
  2658. """
  2659. DETAIL_READ_SCRIPT = _CONTEXT_JS + r"""
  2660. /* coordinate:ita-reservation-detail-readonly */
  2661. if (!/^\/ReservationDetail\/Index\/[^/]+$/.test(window.location.pathname)) return fail('wrong_page');
  2662. const headings = Array.from(document.querySelectorAll('h4'));
  2663. const booking = headings.filter(e => clean(e.textContent) === 'Dati Prenotazione');
  2664. const applicant = headings.filter(e => clean(e.textContent) === 'Dati Richiedente');
  2665. if (booking.length !== 1 || applicant.length !== 1) return fail('section_ambiguous');
  2666. const root = booking[0].parentElement;
  2667. if (!root || !root.classList.contains('my-col-6') || root.contains(applicant[0])) return fail('unsafe_scope');
  2668. const nameOf = e => clean(e.textContent).match(
  2669. /^\*?\s*(Servizio Consolare|Servizio Erogato|Codice Prenotazione|Tipo Prenotazione|Data|Ora|Stato)\s*:\s*$/)?.[1];
  2670. const labels = Array.from(root.querySelectorAll('label')).filter(nameOf);
  2671. if (labels.length !== 7 || new Set(labels.map(nameOf)).size !== 7) return fail('fields_ambiguous');
  2672. const fields = {};
  2673. for (const label of labels) {
  2674. const row = label.parentElement;
  2675. if (labels.filter(e => row.contains(e)).length !== 1) return fail('row_ambiguous');
  2676. const values = [];
  2677. for (const node of row.childNodes) {
  2678. if (node === label || node.nodeType === 8) continue;
  2679. // The observed values are text siblings or one b. Do not read nested
  2680. // forms, print payloads, applicant sections or arbitrary HTML as values.
  2681. if (node.nodeType !== 3 && !(node.nodeType === 1 && node.tagName === 'B' && node.children.length === 0))
  2682. return fail('value_structure_changed');
  2683. const value = clean(node.textContent);
  2684. if (value) values.push(value);
  2685. }
  2686. if (values.length !== 1 || values[0].length > 256) return fail('value_ambiguous');
  2687. fields[nameOf(label)] = values[0];
  2688. }
  2689. const codes = document.querySelectorAll('input#IDTipoStatoPrenotazione');
  2690. if (codes.length !== 1 || codes[0].type !== 'hidden' || codes[0].name !== 'IDTipoStatoPrenotazione')
  2691. return fail('status_control_ambiguous');
  2692. return {path: window.location.pathname, fields, statusCode: clean(codes[0].value)};
  2693. """
  2694. LIST_READ_SCRIPT = _CONTEXT_JS + r"""
  2695. /* coordinate:ita-reservation-list-readonly */
  2696. if (window.location.pathname !== '/Reservation') return fail('wrong_page');
  2697. const readDateCell = cell => {
  2698. // Observed shape: optional hidden element(s), one non-empty text sibling.
  2699. // Do not use the whole cell's textContent (includes hidden metadata), nor
  2700. // innerText (unrendered DataTables pages can fall back to textContent).
  2701. const nodes = Array.from(cell.childNodes), values = [];
  2702. if (nodes.length > 16) return null;
  2703. for (const node of nodes) {
  2704. if (node.nodeType === 8) continue;
  2705. if (node.nodeType === 3) {
  2706. const value = clean(node.textContent);
  2707. if (value) values.push(value);
  2708. continue;
  2709. }
  2710. if (node.nodeType !== 1) return null;
  2711. const style = window.getComputedStyle(node);
  2712. // Own inline/hidden markers remain checkable for detached client rows.
  2713. // visibility:hidden only proves a leaf hidden: descendants can override it.
  2714. const hidden = node.hidden === true || node.style.display === 'none' || style.display === 'none';
  2715. const hiddenLeaf = node.children.length === 0 &&
  2716. (node.style.visibility === 'hidden' || style.visibility === 'hidden');
  2717. if (!hidden && !hiddenLeaf) return null;
  2718. // Hidden metadata is excluded structurally; never parse or log its value.
  2719. }
  2720. return values.length === 1 ? values[0] : null;
  2721. };
  2722. const $ = window.jQuery;
  2723. const ids = ['dataTableReservations', 'dataTableReservationsWL'];
  2724. const tables = [];
  2725. for (const id of ids) {
  2726. const matches = document.querySelectorAll('#' + id);
  2727. if (matches.length !== 1) return fail('table_ambiguous');
  2728. const table = matches[0];
  2729. const headers = Array.from(table.querySelectorAll('thead th')).map(e => clean(e.textContent));
  2730. if (!$?.fn?.dataTable?.isDataTable(table)) {
  2731. const empty = table.querySelectorAll('tbody tr').length === 0 && headers.length === 0 &&
  2732. !table.classList.contains('dataTable') && !table.closest('.dataTables_wrapper');
  2733. if (id !== ids[1] || !empty) return fail('not_ready');
  2734. tables.push({id, structuralEmpty: true});
  2735. continue;
  2736. }
  2737. // This getter is only used after isDataTable: it must never initialize a table.
  2738. const api = $(table).DataTable(), pageInfo = api.page.info();
  2739. const info = Object.fromEntries(['page', 'pages', 'start', 'end', 'length',
  2740. 'recordsTotal', 'recordsDisplay', 'serverSide'].map(k => [k, pageInfo[k]]));
  2741. const count = api.rows().count();
  2742. if (!Number.isInteger(count) || count < 0 || count > 512) return fail('row_limit');
  2743. if (info.serverSide !== false || api.search() || api.columns().search().toArray().some(Boolean) ||
  2744. count !== info.recordsTotal || count !== info.recordsDisplay || api.rows({search: 'applied'}).count() !== count)
  2745. return fail('coverage_incomplete');
  2746. if (id === ids[1]) {
  2747. if (count !== 0) return fail('waitlist_schema_unverified');
  2748. tables.push({id, structuralEmpty: false, count, info});
  2749. continue;
  2750. }
  2751. const expected = ['Codice Prenotazione', 'Ufficio', 'Servizio', 'Data', 'Ora', 'Stato', 'Dati Richiedente'];
  2752. if (![7, 8].includes(headers.length) || expected.some((h, i) => headers[i] !== h) ||
  2753. (headers.length === 8 && headers[7] !== '')) return fail('headers_changed');
  2754. const nodes = api.rows().nodes().toArray();
  2755. if (nodes.length !== count) return fail('row_nodes_incomplete');
  2756. const rows = [];
  2757. for (const node of nodes) {
  2758. const cells = Array.from(node.children);
  2759. if (cells.length !== headers.length || cells.some(c => c.tagName !== 'TD')) return fail('cells_changed');
  2760. const links = cells[0].querySelectorAll('a[href]');
  2761. if (links.length !== 1) return fail('detail_link_ambiguous');
  2762. const date = readDateCell(cells[3]);
  2763. if (date === null) return fail('date_cell_structure_changed');
  2764. const row = {reference: clean(cells[0].textContent), detailUrl: links[0].href,
  2765. office: clean(cells[1].textContent), service: clean(cells[2].textContent),
  2766. date, time: clean(cells[4].textContent), status: clean(cells[5].textContent)};
  2767. if (Object.values(row).some(v => typeof v !== 'string' || !v || v.length > 256)) return fail('field_invalid');
  2768. rows.push(row);
  2769. // Do not access applicant cell 6 or unnamed cell 7.
  2770. }
  2771. tables.push({id, structuralEmpty: false, headers, count, info, rows});
  2772. }
  2773. return {path: window.location.pathname, tables};
  2774. """
  2775. DATE_DIAGNOSTIC_SCRIPT = _CONTEXT_JS + r"""
  2776. /* coordinate:ita-reservation-date-diagnostic-readonly */
  2777. if (window.location.pathname !== '/Reservation') return fail('wrong_page');
  2778. const tables = document.querySelectorAll('#dataTableReservations');
  2779. if (tables.length !== 1) return fail('table_ambiguous');
  2780. const table = tables[0], $ = window.jQuery;
  2781. const headers = Array.from(table.querySelectorAll('thead th')).map(e => clean(e.textContent));
  2782. const expected = ['Codice Prenotazione', 'Ufficio', 'Servizio', 'Data', 'Ora', 'Stato', 'Dati Richiedente'];
  2783. if (![7,8].includes(headers.length) || expected.some((v,i) => headers[i] !== v) ||
  2784. (headers.length === 8 && headers[7] !== '') || !$?.fn?.dataTable?.isDataTable(table))
  2785. return fail('headers_changed');
  2786. const nodes = $(table).DataTable().rows().nodes().toArray();
  2787. if (nodes.length > 512) return fail('row_limit');
  2788. const samples = [];
  2789. for (const row of nodes.slice(0,3)) {
  2790. const cells = Array.from(row.children);
  2791. if (cells.length !== headers.length || cells.some(c => c.tagName !== 'TD')) return fail('cells_changed');
  2792. // Only the verified Data column. No reference, account, applicant, HTML or attributes.
  2793. const cell = cells[3], children = Array.from(cell.childNodes);
  2794. const text = clean(cell.textContent), rendered = clean(cell.innerText);
  2795. if (text.length > 256 || rendered.length > 256) return fail('field_invalid');
  2796. const parts = children.slice(0,6).map(n => {
  2797. const style = n.nodeType === 1 ? window.getComputedStyle(n) : null;
  2798. return {kind: n.nodeType === 3 ? 'text' : (n.nodeType === 1 &&
  2799. ['SPAN','B','I','BR'].includes(n.tagName) ? n.tagName.toLowerCase() : 'other'),
  2800. text: clean(n.textContent), hidden: !!style && (style.display === 'none' || style.visibility === 'hidden')};
  2801. });
  2802. samples.push({text, rendered, parts, partsTruncated: children.length > 6});
  2803. }
  2804. return {path: window.location.pathname, samples, rowsTruncated: nodes.length > 3};
  2805. """
  2806. def _date_shape(value: object) -> dict:
  2807. """Only structural symbols and known month indexes; never emit raw field text."""
  2808. if not isinstance(value, str) or len(value) > 256:
  2809. raise ValueError()
  2810. normalized = " ".join(value.split())
  2811. shape = "".join("D" if c.isdecimal() else "L" if c.isalpha() else c if c in " /:.,-" else "?"
  2812. for c in normalized[:96])
  2813. months = [i for i, month in enumerate(MONTHS_IT, 1)
  2814. if re.search(r"(?<![A-Za-z])" + month + r"(?![A-Za-z])", normalized, re.IGNORECASE)]
  2815. try:
  2816. _day(normalized)
  2817. accepted = True
  2818. except ReservationReadError:
  2819. accepted = False
  2820. return {"shape": shape, "length": len(normalized), "truncated": len(normalized) > 96,
  2821. "italianMonths": months, "acceptedByCurrentParser": accepted}
  2822. def read_reservation_date_diagnostic(page: object) -> dict:
  2823. """One bounded extra read on a failed list parse, not an alternate parser.
  2824. The raw verified date-cell strings stay local; only allowlisted shapes leave
  2825. this function. A malformed diagnostic cannot leak arbitrary browser output.
  2826. """
  2827. try:
  2828. raw = _read_current(page, DATE_DIAGNOSTIC_SCRIPT, detail=False)
  2829. if (set(raw) != {"path", "samples", "rowsTruncated"} or
  2830. type(raw["rowsTruncated"]) is not bool or not isinstance(raw["samples"], list) or
  2831. len(raw["samples"]) > 3):
  2832. raise ValueError()
  2833. samples = []
  2834. for item in raw["samples"]:
  2835. if (not isinstance(item, dict) or set(item) != {"text", "rendered", "parts", "partsTruncated"} or
  2836. type(item["partsTruncated"]) is not bool or not isinstance(item["parts"], list) or
  2837. len(item["parts"]) > 6):
  2838. raise ValueError()
  2839. parts = []
  2840. for part in item["parts"]:
  2841. if (not isinstance(part, dict) or set(part) != {"kind", "text", "hidden"} or
  2842. part["kind"] not in ("text", "span", "b", "i", "br", "other") or
  2843. type(part["hidden"]) is not bool):
  2844. raise ValueError()
  2845. parts.append({"kind": part["kind"], "hidden": part["hidden"], **_date_shape(part["text"])})
  2846. samples.append({"text": _date_shape(item["text"]), "rendered": _date_shape(item["rendered"]),
  2847. "textEqualsRendered": item["text"] == item["rendered"],
  2848. "parts": parts, "partsTruncated": item["partsTruncated"]})
  2849. return {"available": True, "samples": samples, "rowsTruncated": raw["rowsTruncated"]}
  2850. except Exception:
  2851. return {"available": False}
  2852. def _reservation_text(value: object) -> str:
  2853. if (not isinstance(value, str) or not 0 < len(value) <= 256 or value != value.strip()
  2854. or any(ord(c) < 32 or ord(c) == 127 for c in value)):
  2855. raise ReservationReadError("field_invalid")
  2856. return value
  2857. def _day(value: object) -> date:
  2858. value = _reservation_text(value)
  2859. match = re.fullmatch(r"([0-9]{1,2}) ([A-Za-z]+) ([0-9]{4})", value)
  2860. if match:
  2861. try:
  2862. return date(int(match[3]), MONTHS_IT.index(match[2].casefold()) + 1, int(match[1]))
  2863. except ValueError:
  2864. pass
  2865. raise ReservationReadError("date_unrecognized") from None
  2866. def _appointment_time(value: object) -> str:
  2867. value = _reservation_text(value)
  2868. if re.fullmatch(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]", value) is None:
  2869. raise ReservationReadError("time_unrecognized")
  2870. return value
  2871. def _state(text: str, code: str | None = None) -> ReservationState:
  2872. # A list label is a candidate; a detail must also have its observed code.
  2873. # Never infer ACTIVE from "not cancelled" or from the numeric code alone.
  2874. if text.casefold() == "annullata" and code in (None, "3"):
  2875. return ReservationState.CANCELLED
  2876. if text.casefold() == "confermata" and code in (None, "2"):
  2877. return ReservationState.ACTIVE
  2878. return ReservationState.UNKNOWN
  2879. def _detail_path(url: object) -> str:
  2880. try:
  2881. path, parsed = same_origin_path(url)
  2882. suffix = path.removeprefix(DETAIL_PREFIX)
  2883. if (not path.startswith(DETAIL_PREFIX) or not suffix or len(suffix) > 256
  2884. or any(c in suffix for c in "/\\%") or suffix in {".", ".."}
  2885. or parsed.query or parsed.fragment):
  2886. raise ValueError()
  2887. return path
  2888. except Exception:
  2889. raise ReservationReadError("detail_url_invalid") from None
  2890. def parse_reservation_detail(raw: object) -> ReservationDetail:
  2891. if not isinstance(raw, dict) or set(raw) != {"path", "fields", "statusCode"}:
  2892. raise ReservationReadError("detail_schema_changed")
  2893. _detail_path("https://prenotami.esteri.it" + raw["path"] if isinstance(raw["path"], str) else None)
  2894. fields = raw["fields"]
  2895. if not isinstance(fields, dict) or set(fields) != set(DETAIL_LABELS):
  2896. raise ReservationReadError("fields_ambiguous")
  2897. values = {key: _reservation_text(value) for key, value in fields.items()}
  2898. code = raw["statusCode"]
  2899. if not isinstance(code, str) or not re.fullmatch(r"[0-9]{1,4}", code):
  2900. raise ReservationReadError("status_code_invalid")
  2901. return ReservationDetail(
  2902. values["Codice Prenotazione"], values["Servizio Consolare"], values["Servizio Erogato"],
  2903. values["Tipo Prenotazione"], _day(values["Data"]), _appointment_time(values["Ora"]),
  2904. values["Stato"], code, _state(values["Stato"], code),
  2905. )
  2906. def _coverage(table: dict) -> tuple[int, int]:
  2907. info, count = table.get("info"), table.get("count")
  2908. if not isinstance(info, dict) or type(count) is not int or not 0 <= count <= MAX_PROTOCOL_ITEMS:
  2909. raise ReservationReadError("coverage_invalid")
  2910. keys = ("recordsTotal", "recordsDisplay", "page", "pages", "start", "end", "length")
  2911. if any(type(info.get(k)) is not int for k in keys) or info.get("serverSide") is not False:
  2912. raise ReservationReadError("coverage_invalid")
  2913. total, displayed, page, pages, start, end, length = (info[k] for k in keys)
  2914. if total != count or displayed != count or not 0 <= start <= end <= count:
  2915. raise ReservationReadError("coverage_incomplete")
  2916. expected_pages = (math.ceil(count / length) if length > 0 else 1) if count else 0
  2917. if (length not in (-1,) and length <= 0) or pages != expected_pages or not 0 <= page < max(1, pages):
  2918. raise ReservationReadError("pagination_invalid")
  2919. if start != (page * length if length > 0 else 0) or end != (min(start + length, count) if length > 0 else count):
  2920. raise ReservationReadError("pagination_invalid")
  2921. return count, pages
  2922. def parse_reservation_listing(raw: object) -> ReservationListing:
  2923. if not isinstance(raw, dict) or set(raw) != {"path", "tables"} or raw["path"] != LIST_PATH:
  2924. raise ReservationReadError("list_schema_changed")
  2925. tables = raw["tables"]
  2926. if not isinstance(tables, list) or len(tables) != 2 or not all(isinstance(t, dict) for t in tables):
  2927. raise ReservationReadError("table_ambiguous")
  2928. main, waitlist = tables
  2929. if main.get("id") != "dataTableReservations" or waitlist.get("id") != "dataTableReservationsWL":
  2930. raise ReservationReadError("table_ambiguous")
  2931. if main.get("structuralEmpty") is not False or main.get("headers") not in (list(HEADERS), [*HEADERS, ""]):
  2932. raise ReservationReadError("headers_changed")
  2933. count, pages = _coverage(main)
  2934. if waitlist.get("structuralEmpty") is True:
  2935. if set(waitlist) != {"id", "structuralEmpty"}:
  2936. raise ReservationReadError("waitlist_ambiguous")
  2937. elif waitlist.get("structuralEmpty") is not False or _coverage(waitlist)[0] != 0:
  2938. raise ReservationReadError("waitlist_schema_unverified")
  2939. rows = main.get("rows")
  2940. if not isinstance(rows, list) or len(rows) != count:
  2941. raise ReservationReadError("row_nodes_incomplete")
  2942. result, references, destinations = [], set(), set()
  2943. for row in rows:
  2944. if not isinstance(row, dict) or set(row) != {"reference", "detailUrl", "office", "service", "date", "time", "status"}:
  2945. raise ReservationReadError("row_schema_changed")
  2946. values = {key: _reservation_text(value) for key, value in row.items()}
  2947. path = _detail_path(values["detailUrl"])
  2948. if values["reference"] in references or path in destinations:
  2949. raise ReservationReadError("duplicate_record")
  2950. references.add(values["reference"])
  2951. destinations.add(path)
  2952. result.append(ReservationListRow(values["reference"], values["detailUrl"], values["office"],
  2953. values["service"], _day(values["date"]), _appointment_time(values["time"]),
  2954. values["status"], _state(values["status"])))
  2955. return ReservationListing(tuple(result), pages)
  2956. def _read_current(page: object, script: str, *, detail: bool) -> object:
  2957. try:
  2958. before_url, before_tab = page.url, page.tab_id
  2959. path, parsed = same_origin_path(before_url)
  2960. if parsed.query or parsed.fragment or (not detail and path != LIST_PATH):
  2961. raise ReservationReadError("wrong_page")
  2962. if detail:
  2963. _detail_path(before_url)
  2964. if not isinstance(before_tab, str) or not before_tab:
  2965. raise ReservationReadError("context_changed")
  2966. raw = page.run_js(script)
  2967. if page.url != before_url or page.tab_id != before_tab:
  2968. raise ReservationReadError("context_changed")
  2969. if not isinstance(raw, dict) or raw.get("path") != path:
  2970. reason = "not_ready" if isinstance(raw, dict) and raw == {"error": "not_ready"} else "page_read_rejected"
  2971. raise ReservationReadError(reason)
  2972. return raw
  2973. except ReservationReadError:
  2974. raise
  2975. except Exception:
  2976. raise ReservationReadError("browser_read_failed") from None
  2977. def read_reservation_detail(page: object) -> ReservationDetail:
  2978. """Read the current detail page once. No URL, reference or PII is logged."""
  2979. return parse_reservation_detail(_read_current(page, DETAIL_READ_SCRIPT, detail=True))
  2980. def read_reservation_listing(page: object, *, timeout: float = 5, poll_interval: float = 0.25) -> ReservationListing:
  2981. """Two stable reads within a bound, reusing the existing count tool pattern.
  2982. Only not-ready states are polled; unsupported schemas/coverage fail closed.
  2983. This checks the current page and never navigates, draws or clears filters.
  2984. """
  2985. if (any(type(v) not in (int, float) or not math.isfinite(v) or v <= 0 for v in (timeout, poll_interval))
  2986. or poll_interval > timeout or timeout > 60):
  2987. raise ReservationReadError("wait_config_invalid")
  2988. try:
  2989. binding = (page.url, page.tab_id)
  2990. except Exception:
  2991. raise ReservationReadError("browser_read_failed") from None
  2992. deadline, previous = time.monotonic() + timeout, None
  2993. while time.monotonic() < deadline:
  2994. try:
  2995. try:
  2996. context_matches = (page.url, page.tab_id) == binding
  2997. except Exception:
  2998. raise ReservationReadError("browser_read_failed") from None
  2999. if not context_matches:
  3000. raise ReservationReadError("context_changed")
  3001. current = parse_reservation_listing(_read_current(page, LIST_READ_SCRIPT, detail=False))
  3002. except ReservationReadError as error:
  3003. if error.reason != "not_ready":
  3004. raise
  3005. previous = None
  3006. else:
  3007. if current == previous:
  3008. return current
  3009. previous = current
  3010. time.sleep(min(poll_interval, max(0, deadline - time.monotonic())))
  3011. raise ReservationReadError("stability_timeout")
  3012. # ============================================================================
  3013. # FINAL_READ_PORT (from plugins/ita_final_read_port.py)
  3014. # ============================================================================
  3015. """Read-port adapter shared by production Book and local final validation.
  3016. Preserves the applicant Calendar in its original tab. Reads existing receipts in
  3017. an owned background tab of the SAME browser/context. Baselines allow only empty
  3018. or cancelled history. A new confirmed receipt may bind to a verified native POST;
  3019. observed receipt fields remain distinct from submission evidence.
  3020. """
  3021. import hashlib
  3022. import json
  3023. import threading
  3024. import time
  3025. from dataclasses import dataclass, field
  3026. from uuid import uuid4
  3027. from urllib.parse import parse_qsl
  3028. LIST_URL = "https://prenotami.esteri.it/Reservation"
  3029. MAX_DETAIL_READS = 20
  3030. @dataclass(frozen=True, repr=False)
  3031. class ReceiptObservation:
  3032. """Bound display evidence only; UNKNOWN is never promoted to success."""
  3033. records: tuple = field(repr=False) # (verified list row, matching detail)
  3034. def _require(condition, reason):
  3035. if condition is not True:
  3036. raise FinalBookingError(reason)
  3037. def _cancelled_record(row, detail) -> ReservationRecord:
  3038. _require(row.state is ReservationState.CANCELLED and detail.state is ReservationState.CANCELLED and
  3039. detail.status_code == "3" and all(getattr(row, field) == getattr(detail, field) for field in (
  3040. "reference", "office", "service_name", "day", "appointment_time", "status_text")),
  3041. "Italy cancelled receipt is not verified")
  3042. # Equality of fingerprints preserves changes to fields absent from the final
  3043. # model (office, displayed service, booking type). It is NOT identity proof.
  3044. facts = [detail.reference, row.detail_url, detail.office, detail.service_name, detail.booking_type,
  3045. detail.day.isoformat(), detail.appointment_time, detail.status_text, detail.status_code]
  3046. digest = hashlib.sha256(json.dumps(facts, ensure_ascii=True, separators=(",", ":")).encode()).hexdigest()
  3047. return ReservationRecord(detail.reference, None, detail.day, None, ReservationState.CANCELLED,
  3048. appointment_time=detail.appointment_time, receipt_fingerprint=digest)
  3049. def _confirmed_record(row, detail, submission: VerifiedSubmission) -> ReservationRecord:
  3050. target, slot = submission.target, submission.target.approval.candidate
  3051. _require(row.state is ReservationState.ACTIVE and detail.state is ReservationState.ACTIVE and
  3052. detail.status_code == "2" and detail.booking_type == "Prenotazione Singola" and
  3053. isinstance(target.service_name, str) and detail.service_name == target.service_name and
  3054. detail.day == slot.day and slot.time_label[:5] <= detail.appointment_time <= slot.time_label[-5:] and
  3055. all(getattr(row, key) == getattr(detail, key) for key in (
  3056. "reference", "office", "service_name", "day", "appointment_time", "status_text")),
  3057. "Italy confirmed receipt does not match the submitted selection")
  3058. facts = [detail.reference, row.detail_url, detail.office, detail.service_name, detail.booking_type,
  3059. detail.day.isoformat(), detail.appointment_time, detail.status_text, detail.status_code]
  3060. digest = hashlib.sha256(json.dumps(facts, ensure_ascii=True, separators=(",", ":")).encode()).hexdigest()
  3061. # The website receipt supplies neither service_id nor the selected interval.
  3062. # Keep them None; the separate evidence explicitly identifies the native POST.
  3063. return ReservationRecord(detail.reference, None, detail.day, None, ReservationState.ACTIVE,
  3064. appointment_time=detail.appointment_time, receipt_fingerprint=digest,
  3065. submission=submission)
  3066. class FinalReceiptReadPort:
  3067. """Capture an existing applicant Book precommit, then read fresh snapshots.
  3068. Uses the plugin's established session/route checks, not a caller-supplied
  3069. username assertion. Constructor does no navigation. Calling the port reads
  3070. only; it never touches final buttons, rebuilds calendars or generates OTP.
  3071. The owning Book workflow must serialize this with other browser work.
  3072. """
  3073. def __init__(self, plugin, route: ItaRouteConfig, *, observe_tab=None):
  3074. try:
  3075. _require(isinstance(route, ItaRouteConfig) and
  3076. route.capability is ItaCapability.SINGLE_SCHENGEN_TOURISM,
  3077. "Italy final read route is invalid")
  3078. self._plugin, self._route = plugin, route
  3079. _require(observe_tab is None or callable(observe_tab), "Italy receipt observer is invalid")
  3080. self._observe_tab = observe_tab
  3081. self._page = plugin.page
  3082. self._browser = self._page.browser
  3083. self._browser_id = self._browser.id
  3084. self._generation = plugin.session_create_time
  3085. self._prepared = plugin._calendar_book_prepared_context
  3086. self._approval = plugin.last_booking_precommit
  3087. self._username = plugin.config.account.username.strip().casefold()
  3088. _require(isinstance(self._approval, PrecommitApproval) and
  3089. isinstance(self._prepared, tuple) and len(self._prepared) == 7 and
  3090. isinstance(self._browser_id, str) and bool(self._browser_id) and
  3091. same_origin_path(self._page.url)[0] == CALENDAR_PATH,
  3092. "Italy final read requires the current Book precommit")
  3093. _, calendar_url = same_origin_path(self._page.url)
  3094. names = [value for key, value in parse_qsl(calendar_url.query, keep_blank_values=True)
  3095. if key == "selectedService"]
  3096. service_name = names[0] if len(names) == 1 and names[0] else None
  3097. self._target = FinalTarget(self._username, uuid4().hex, self._page.tab_id,
  3098. route.routing_key, str(route.service_id), self._prepared[5], self._approval,
  3099. service_name=service_name)
  3100. self._lock = threading.Lock()
  3101. self._unusable = False
  3102. self._baseline = None
  3103. self._submission = None
  3104. _require(self.session_is_current(), "Italy final read Session is not current")
  3105. except Exception:
  3106. raise FinalBookingError("Italy final read context could not be captured") from None
  3107. @property
  3108. def target(self):
  3109. return self._target
  3110. def session_is_current(self) -> bool:
  3111. try:
  3112. p = self._plugin
  3113. same_origin_path(self._page.url)
  3114. return (not self._unusable and p.page is self._page and self._page.browser is self._browser and
  3115. self._browser.id == self._browser_id and self._page.tab_id == self._target.tab_id and
  3116. p.session_create_time == self._generation and p.is_healthy is True and
  3117. p.last_booking_precommit is self._approval and
  3118. p._calendar_book_prepared_context == self._prepared and
  3119. p.config.account.username.strip().casefold() == self._username and
  3120. p._calendar_book_context_matches(self._route, self._username) is True)
  3121. except Exception:
  3122. return False
  3123. def __call__(self) -> ReservationSnapshot:
  3124. snapshot = self._read(observation=False)
  3125. if self._submission is None:
  3126. self._baseline = snapshot
  3127. return snapshot
  3128. def record_submission(self, submission: VerifiedSubmission) -> None:
  3129. """Called only after a matched native POST and one-request audit."""
  3130. _require(self.session_is_current() and self._baseline is not None and self._submission is None and
  3131. isinstance(submission, VerifiedSubmission) and submission.target == self.target and
  3132. self.target.service_name is not None, "Italy submission binding is not current")
  3133. self._submission = submission
  3134. def observe_receipts(self) -> ReceiptObservation:
  3135. """Read unknown status text for controlled discovery, NOT reconciliation."""
  3136. return self._read(observation=True)
  3137. def _read(self, *, observation: bool):
  3138. if not self._lock.acquire(blocking=False):
  3139. raise FinalBookingError("Italy receipt read is already running")
  3140. receipt_page = None
  3141. finish_observation = None
  3142. close_failed = False
  3143. cleanup_interrupt = None
  3144. try:
  3145. _require(self.session_is_current(), "Italy final read Session changed")
  3146. origin = (self._page.url, self._page.tab_id)
  3147. candidate = self._browser.new_tab(background=True, new_context=False)
  3148. # Only close a separately identified tab created by our own browser.
  3149. # A broken factory returning the original/foreign page is not owned.
  3150. _require(candidate is not self._page and candidate.browser is self._browser and
  3151. isinstance(candidate.tab_id, str) and bool(candidate.tab_id) and
  3152. candidate.tab_id != self._target.tab_id, "Italy receipt tab ownership is unverified")
  3153. receipt_page, receipt_tab = candidate, candidate.tab_id
  3154. if self._observe_tab is not None:
  3155. finish_observation = self._observe_tab(receipt_page)
  3156. _require(callable(finish_observation), "Italy receipt observer did not start")
  3157. def context():
  3158. _require(self.session_is_current() and (self._page.url, self._page.tab_id) == origin and
  3159. receipt_page.browser is self._browser and receipt_page.tab_id == receipt_tab,
  3160. "Italy receipt read context changed")
  3161. def navigate(url):
  3162. context()
  3163. _require(receipt_page.get(url, retry=0, timeout=30) is not False,
  3164. "Italy receipt navigation failed")
  3165. context()
  3166. same_origin_path(receipt_page.url)
  3167. _require(receipt_page.url == url, "Italy receipt navigation was redirected")
  3168. navigate(LIST_URL)
  3169. before = read_reservation_listing(receipt_page)
  3170. context()
  3171. _require(before.waitlist_count == 0 and len(before.rows) <= MAX_DETAIL_READS,
  3172. "Italy receipt coverage exceeds supported verification")
  3173. if not observation and self._submission is None:
  3174. _require(all(row.state is ReservationState.CANCELLED for row in before.rows),
  3175. "Italy live receipt attribution is not verified")
  3176. records = []
  3177. for row in before.rows:
  3178. # Only actual links accepted by the established listing parser.
  3179. navigate(row.detail_url)
  3180. detail = read_reservation_detail(receipt_page)
  3181. context()
  3182. _require(all(getattr(row, key) == getattr(detail, key) for key in (
  3183. "reference", "office", "service_name", "day", "appointment_time", "status_text")),
  3184. "Italy observed receipt does not match its list row")
  3185. if observation:
  3186. records.append((row, detail))
  3187. elif row.state is ReservationState.CANCELLED:
  3188. records.append(_cancelled_record(row, detail))
  3189. else:
  3190. _require(self._submission is not None and self._baseline is not None and
  3191. row.reference not in {r.reference for r in self._baseline.records},
  3192. "Italy receipt is not new to this submission")
  3193. records.append(_confirmed_record(row, detail, self._submission))
  3194. navigate(LIST_URL)
  3195. after = read_reservation_listing(receipt_page)
  3196. context()
  3197. _require({r.reference: r for r in before.rows} == {r.reference: r for r in after.rows} and
  3198. before.waitlist_count == after.waitlist_count, "Italy receipt history changed during read")
  3199. snapshot = (ReceiptObservation(tuple(records)) if observation else
  3200. ReservationSnapshot(self._target.applicant, self._target.session_key,
  3201. time.monotonic(), True, tuple(records)))
  3202. except Exception:
  3203. raise FinalBookingError("Italy bound receipt read could not be verified") from None
  3204. finally:
  3205. if callable(finish_observation):
  3206. try:
  3207. finish_observation()
  3208. except BaseException as exc:
  3209. self._unusable = True
  3210. if isinstance(exc, Exception):
  3211. close_failed = True
  3212. else:
  3213. cleanup_interrupt = exc
  3214. if receipt_page is not None:
  3215. try:
  3216. receipt_page.close()
  3217. except BaseException as exc:
  3218. # Do not trust a later read after losing control of an owned tab.
  3219. self._unusable = True
  3220. if isinstance(exc, Exception):
  3221. close_failed = True
  3222. else:
  3223. cleanup_interrupt = exc
  3224. self._lock.release()
  3225. if cleanup_interrupt is not None:
  3226. raise cleanup_interrupt
  3227. if close_failed:
  3228. raise FinalBookingError("Italy owned receipt tab cleanup failed") from None
  3229. _require(self.session_is_current() and (self._page.url, self._page.tab_id) == origin,
  3230. "Italy final read context changed during cleanup")
  3231. return snapshot
  3232. # ============================================================================
  3233. # CALENDAR_SESSION (from plugins/ita_calendar_session.py)
  3234. # ============================================================================
  3235. """Shared Italy form preparation and passive request audit.
  3236. Extracted from the real-tested Calendar gate. Production and diagnostic tools
  3237. use the same protocol; no tool imports, credentials, or network calls on import.
  3238. """
  3239. import json
  3240. import time
  3241. from enum import Enum
  3242. from threading import Lock
  3243. from urllib.parse import parse_qs, urljoin, urlparse
  3244. _header = header_value; _same_origin_path = same_origin_path
  3245. OTP_PATH = "/BookingCalendar/GenerateOTP"
  3246. def booking_preflight_state(raw: object) -> str:
  3247. """Classify observed readiness, not the unknown cause of a widget failure."""
  3248. if not isinstance(raw, dict):
  3249. return "snapshot_unavailable"
  3250. token, disabled = raw.get("turnstileTokenPresent"), raw.get("avantiDisabled")
  3251. if type(token) is not bool or type(disabled) is not bool:
  3252. return "invalid_snapshot"
  3253. if not token:
  3254. return "turnstile_and_avanti_pending" if disabled else "turnstile_token_pending"
  3255. return "avanti_disabled" if disabled else "ready"
  3256. def safe_booking_preflight_diagnostic(raw: object, *, stage, outcome: str) -> dict:
  3257. """Only bounded booleans/counts and fixed categories; never token/value/HTML."""
  3258. snapshot = raw if isinstance(raw, dict) else {}
  3259. result = {
  3260. "contract": "ita-book-preflight-v2",
  3261. "stage": stage.value if isinstance(stage, BookingPreflightStage) else "invalid",
  3262. "outcome": outcome if outcome in {"ready", "waiting", "rejected", "timeout", "read_failed"} else "invalid",
  3263. "state": booking_preflight_state(raw),
  3264. }
  3265. for key in ("pathMatches", "formPresent", "privacyChecked", "otpDisabled", "otpValuePresent",
  3266. "turnstileTokenPresent", "avantiDisabled", "turnstileApiPresent",
  3267. "turnstileScriptPresent", "documentVisible"):
  3268. value = snapshot.get(key)
  3269. result[key] = value if type(value) is bool else None
  3270. for key in ("turnstileCount", "avantiButtonCount", "unknownRequiredCount"):
  3271. value = snapshot.get(key)
  3272. result[key] = value if type(value) is int and 0 <= value <= 1000 else None
  3273. return result
  3274. def _print_booking_preflight_diagnostic(raw: object, *, stage, outcome: str) -> None:
  3275. print("ITA_BOOK_PREFLIGHT_DIAGNOSTIC=" + json.dumps(
  3276. safe_booking_preflight_diagnostic(raw, stage=stage, outcome=outcome), sort_keys=True,
  3277. ), flush=True)
  3278. def wait_for_booking_preflight(
  3279. page: object,
  3280. *,
  3281. script: str,
  3282. stage: BookingPreflightStage = None,
  3283. timeout: float = 120,
  3284. diagnostic=None,
  3285. wait_action=None,
  3286. check_current=None,
  3287. ) -> dict[str, object]:
  3288. """Wait without relaxing structure; optional bounded form interaction.
  3289. An interaction return value is never evidence of readiness: only the next
  3290. validated site snapshot can permit OTP/AVANTI. No recovery is enabled by
  3291. default; callers must explicitly supply their preparation recovery.
  3292. """
  3293. stage = stage if stage is not None else BookingPreflightStage.BEFORE_OTP_SEND
  3294. report = diagnostic or _print_booking_preflight_diagnostic
  3295. started = time.monotonic()
  3296. deadline = started + timeout
  3297. announced = False
  3298. raw = None
  3299. last_state = None
  3300. next_report = started
  3301. while (now := time.monotonic()) < deadline:
  3302. if check_current is not None:
  3303. check_current()
  3304. try:
  3305. raw = page.run_js(script)
  3306. except Exception:
  3307. report(None, stage=stage, outcome="read_failed")
  3308. raise CalendarGateError("Italy booking preflight read_failed") from None
  3309. if check_current is not None:
  3310. check_current()
  3311. try:
  3312. _validate_preflight_except_dynamic_token(raw, stage=stage)
  3313. except CalendarGateError:
  3314. report(
  3315. raw,
  3316. stage=stage,
  3317. outcome="rejected",
  3318. )
  3319. raise
  3320. if raw.get("turnstileTokenPresent") and not raw.get("avantiDisabled"):
  3321. try:
  3322. validate_booking_preflight(raw, stage=stage)
  3323. except CalendarGateError:
  3324. report(
  3325. raw,
  3326. stage=stage,
  3327. outcome="rejected",
  3328. )
  3329. raise
  3330. report(
  3331. raw,
  3332. stage=stage,
  3333. outcome="ready",
  3334. )
  3335. return raw
  3336. if not announced:
  3337. print("ITA_BOOK_WAITING_FOR_FORM: watch the opened browser; complete any human verification. "
  3338. "Do not click OTP, AVANTI, or final Prenota.", flush=True)
  3339. announced = True
  3340. state = booking_preflight_state(raw)
  3341. if state != last_state or now >= next_report:
  3342. report(raw, stage=stage, outcome="waiting")
  3343. last_state, next_report = state, now + 15
  3344. if wait_action is not None:
  3345. wait_action(raw, stage=stage, elapsed=now - started, remaining=deadline - now)
  3346. time.sleep(0.5)
  3347. report(raw, stage=stage, outcome="timeout")
  3348. raise CalendarGateError(f"Italy booking preflight timed out: {booking_preflight_state(raw)}")
  3349. def guarded_preflight_script(route: ItaRouteConfig, booking_path: str) -> str:
  3350. """Check scope before the reused script changes any visible form control."""
  3351. prefix = """
  3352. /* coordinate:ita-book-gate-form-boundary */
  3353. const bookGateForms = document.querySelectorAll('#bookingForm');
  3354. const bookGateForm = bookGateForms.length === 1 ? bookGateForms[0] : null;
  3355. let bookGateAction = null;
  3356. try { bookGateAction = bookGateForm ? new URL(bookGateForm.action, location.href) : null; }
  3357. catch (_) {}
  3358. if (location.origin !== 'https://prenotami.esteri.it' ||
  3359. location.pathname !== BOOK_GATE_PATH || !bookGateForm ||
  3360. bookGateForm.method.toUpperCase() !== 'POST' ||
  3361. bookGateForm.enctype !== 'multipart/form-data' ||
  3362. !bookGateAction || bookGateAction.origin !== location.origin ||
  3363. bookGateAction.pathname !== BOOK_GATE_PATH || bookGateAction.search || bookGateAction.hash ||
  3364. bookGateForm.querySelectorAll('input[type="file"]').length !== 0) {
  3365. return {pathMatches: false, formPresent: false};
  3366. }
  3367. """.replace("BOOK_GATE_PATH", json.dumps(booking_path))
  3368. return prefix + _booking_preflight_script(route, booking_path)
  3369. class BookingPreflightStage(Enum):
  3370. BEFORE_OTP_SEND = "before_otp_send"
  3371. AFTER_OTP_SEND = "after_otp_send"
  3372. class CalendarRequestAudit:
  3373. """Passively count business requests across refreshes; never retain bodies.
  3374. The production page.listen owns a separate CDP connection. This diagnostic
  3375. callback uses the page driver and refuses to replace an existing handler.
  3376. It never enables Fetch interception or changes any browser request.
  3377. """
  3378. EVENT = "Network.requestWillBeSent"
  3379. def __init__(self, page: object, *, include_time_slots: bool = False) -> None:
  3380. self.page = page
  3381. self.driver = page.driver
  3382. self._callback = self._on_request
  3383. self._lock = Lock()
  3384. self._started = False
  3385. self._invalid_event = False
  3386. self._counts = {
  3387. "otpRequests": 0,
  3388. "avantiPosts": 0,
  3389. "availabilityRequests": 0,
  3390. "finalRequests": 0,
  3391. }
  3392. if include_time_slots:
  3393. self._counts["timeSlotRequests"] = 0
  3394. def enable_time_slot_counting(self) -> None:
  3395. """Opt in for the soak; existing gate counter shapes stay unchanged."""
  3396. with self._lock:
  3397. self._counts.setdefault("timeSlotRequests", 0)
  3398. def start(self) -> None:
  3399. if self._started:
  3400. raise CalendarGateError("Passive request audit was already started")
  3401. for name in ("event_handlers", "immediate_event_handlers"):
  3402. handlers = getattr(self.driver, name, None)
  3403. if not isinstance(handlers, dict) or self.EVENT in handlers:
  3404. raise CalendarGateError(
  3405. "Passive request audit cannot replace an existing callback"
  3406. )
  3407. self.driver.set_callback(self.EVENT, self._callback, immediate=True)
  3408. self._started = True
  3409. try:
  3410. self.page.run_cdp("Network.enable")
  3411. except Exception:
  3412. self.stop()
  3413. raise
  3414. def stop(self) -> None:
  3415. if not self._started:
  3416. return
  3417. if self.driver.immediate_event_handlers.get(self.EVENT) is not self._callback:
  3418. raise CalendarGateError("Passive request audit callback changed")
  3419. self.driver.set_callback(self.EVENT, None, immediate=True)
  3420. self._started = False
  3421. def _on_request(self, **event: object) -> None:
  3422. request = event.get("request")
  3423. if (
  3424. not isinstance(request, dict)
  3425. or not isinstance(request.get("url"), str)
  3426. or not isinstance(request.get("method"), str)
  3427. ):
  3428. with self._lock:
  3429. self._invalid_event = True
  3430. return
  3431. try:
  3432. path, _ = _same_origin_path(request["url"])
  3433. except CalendarGateError:
  3434. return
  3435. method = request["method"].upper()
  3436. key = None
  3437. if path == OTP_PATH:
  3438. key = "otpRequests"
  3439. elif path == "/BookingCalendar/InsertNewBooking":
  3440. key = "finalRequests"
  3441. elif method == "POST" and path.startswith("/Services/Booking/"):
  3442. key = "avantiPosts"
  3443. elif path == AVAILABILITY_PATH:
  3444. key = "availabilityRequests"
  3445. elif path == "/BookingCalendar/RetrieveTimeSlots" and "timeSlotRequests" in self._counts:
  3446. key = "timeSlotRequests"
  3447. if key is not None:
  3448. with self._lock:
  3449. self._counts[key] += 1
  3450. def require_active_on(self, page: object) -> None:
  3451. """Validate a borrowed audit without registering or removing callbacks."""
  3452. if self.page is not page or self.driver is not getattr(page, "driver", None):
  3453. raise CalendarGateError("Passive request audit belongs to another page or driver")
  3454. if not self._started or self.driver.is_running is not True:
  3455. raise CalendarGateError("Passive request audit is not connected")
  3456. immediate = getattr(self.driver, "immediate_event_handlers", None)
  3457. regular = getattr(self.driver, "event_handlers", None)
  3458. if (not isinstance(immediate, dict) or immediate.get(self.EVENT) is not self._callback
  3459. or not isinstance(regular, dict) or self.EVENT in regular):
  3460. raise CalendarGateError("Passive request audit callback changed")
  3461. def snapshot(self) -> dict[str, int]:
  3462. self.require_active_on(self.page)
  3463. with self._lock:
  3464. if self._invalid_event:
  3465. raise CalendarGateError("Passive request audit received an invalid event")
  3466. return dict(self._counts)
  3467. def retained_snapshot(self) -> dict[str, int]:
  3468. """Best-effort last observed counters, not proof after a disconnect."""
  3469. with self._lock:
  3470. if self._invalid_event:
  3471. raise CalendarGateError("Passive request audit received an invalid event")
  3472. return dict(self._counts)
  3473. def settled_snapshot(self, *, timeout: float = 3) -> dict[str, int]:
  3474. # A read-only CDP round trip plus a bounded stable-count window lets
  3475. # already-arriving callbacks catch up before a per-query comparison.
  3476. self.page.run_cdp("Page.getFrameTree")
  3477. deadline = time.monotonic() + timeout
  3478. previous = self.snapshot()
  3479. stable_since = time.monotonic()
  3480. while time.monotonic() < deadline:
  3481. time.sleep(0.1)
  3482. current = self.snapshot()
  3483. if current != previous:
  3484. previous = current
  3485. stable_since = time.monotonic()
  3486. elif time.monotonic() - stable_since >= 0.3:
  3487. return current
  3488. raise CalendarGateError("Passive business-request counts did not settle")
  3489. def validate_otp_packet(packet: object, *, service_id: int) -> None:
  3490. path, parsed = _same_origin_path(packet.url)
  3491. if str(packet.method).upper() != "GET" or path != OTP_PATH:
  3492. raise CalendarGateError("OTP request method or path changed")
  3493. if parse_qs(parsed.query) != {"ServiceID": [str(service_id)]}:
  3494. raise CalendarGateError("OTP request service id changed")
  3495. if packet.response.status != 200:
  3496. raise CalendarGateError("OTP response status was not 200")
  3497. raw_body = packet.response.raw_body
  3498. if not isinstance(raw_body, str):
  3499. raise CalendarGateError("OTP response body type changed")
  3500. try:
  3501. decoded = json.loads(raw_body)
  3502. except json.JSONDecodeError as exc:
  3503. raise CalendarGateError("OTP response was not the observed JSON string") from exc
  3504. if decoded != "SENT":
  3505. raise CalendarGateError("OTP response did not confirm SENT")
  3506. def validate_avanti_packet(
  3507. packet: object,
  3508. *,
  3509. booking_path: str,
  3510. final_page_url: str,
  3511. ) -> str:
  3512. path, request_url = _same_origin_path(packet.url)
  3513. if (
  3514. str(packet.method).upper() != "POST"
  3515. or path != booking_path
  3516. or request_url.query
  3517. or request_url.fragment
  3518. ):
  3519. raise CalendarGateError("AVANTI request method or path changed")
  3520. status = packet.response.status
  3521. if status == 302:
  3522. raw_location = _header(packet.response.headers, "location")
  3523. redirect_path, _ = _same_origin_path(
  3524. urljoin("https://prenotami.esteri.it", raw_location)
  3525. )
  3526. if redirect_path != CALENDAR_PATH:
  3527. raise CalendarGateError("AVANTI redirect did not target Calendar")
  3528. transition_mode = "direct_302"
  3529. elif status == 200:
  3530. response_path, _ = _same_origin_path(
  3531. getattr(packet.response, "url", "")
  3532. )
  3533. if response_path != CALENDAR_PATH:
  3534. raise CalendarGateError(
  3535. "AVANTI followed response did not target Calendar"
  3536. )
  3537. transition_mode = "followed_redirect_200"
  3538. else:
  3539. raise CalendarGateError(
  3540. "AVANTI response status was not an allowed redirect representation"
  3541. )
  3542. final_path, _ = _same_origin_path(final_page_url)
  3543. if final_path != CALENDAR_PATH:
  3544. raise CalendarGateError("AVANTI browser did not finish on Calendar")
  3545. return transition_mode
  3546. def validate_booking_preflight(
  3547. raw: object,
  3548. *,
  3549. stage: BookingPreflightStage = BookingPreflightStage.BEFORE_OTP_SEND,
  3550. ) -> None:
  3551. """Validate shared form shape and the stage-sensitive OTP-send control."""
  3552. if not isinstance(raw, dict):
  3553. raise CalendarGateError("Booking preflight did not return an object")
  3554. if not isinstance(stage, BookingPreflightStage):
  3555. raise CalendarGateError("Booking preflight stage is invalid")
  3556. true_fields = (
  3557. "pathMatches",
  3558. "formPresent",
  3559. "bookingTypeOptionMatched",
  3560. "purposeOptionMatched",
  3561. "bookingVisibleMatches",
  3562. "bookingHiddenMatches",
  3563. "companionsHiddenIsZero",
  3564. "purposeVisibleMatches",
  3565. "purposeHiddenIsPreSubmit",
  3566. "privacyChecked",
  3567. "turnstileTokenPresent",
  3568. )
  3569. for field_name in true_fields:
  3570. if raw.get(field_name) is not True:
  3571. raise CalendarGateError(
  3572. f"Booking preflight rejected {field_name}"
  3573. )
  3574. for field_name in (
  3575. "otpInputCount",
  3576. "otpButtonCount",
  3577. "avantiButtonCount",
  3578. "turnstileCount",
  3579. ):
  3580. if raw.get(field_name) != 1:
  3581. raise CalendarGateError(
  3582. f"Booking preflight rejected {field_name}"
  3583. )
  3584. otp_disabled = raw.get("otpDisabled")
  3585. if not isinstance(otp_disabled, bool) or (
  3586. stage is BookingPreflightStage.BEFORE_OTP_SEND
  3587. and otp_disabled
  3588. ):
  3589. raise CalendarGateError(
  3590. "Booking preflight rejected otpDisabled"
  3591. )
  3592. if raw.get("avantiDisabled") is not False:
  3593. raise CalendarGateError(
  3594. "Booking preflight rejected avantiDisabled"
  3595. )
  3596. otp_value_present = raw.get("otpValuePresent")
  3597. expected_otp_value_present = (
  3598. stage is BookingPreflightStage.AFTER_OTP_SEND
  3599. )
  3600. if (
  3601. not isinstance(otp_value_present, bool)
  3602. or otp_value_present is not expected_otp_value_present
  3603. ):
  3604. raise CalendarGateError(
  3605. "Booking preflight rejected otpValuePresent"
  3606. )
  3607. if raw.get("unknownRequiredCount") != 0:
  3608. raise CalendarGateError(
  3609. "Booking preflight rejected unknownRequiredCount"
  3610. )
  3611. def _booking_preflight_script(
  3612. route: ItaRouteConfig,
  3613. booking_path: str,
  3614. ) -> str:
  3615. if route.booking_type is None or route.purpose is None:
  3616. raise CalendarGateError("Q-CAL route is missing form controls")
  3617. config = {
  3618. "bookingPath": booking_path,
  3619. "bookingTypeId": route.booking_type.control_id,
  3620. "bookingTypeValue": route.booking_type.value,
  3621. "bookingTypeLabels": list(route.booking_type.labels),
  3622. "purposeId": route.purpose.control_id,
  3623. "purposeValue": route.purpose.value,
  3624. "purposeLabels": list(route.purpose.labels),
  3625. }
  3626. config_json = json.dumps(config, ensure_ascii=False)
  3627. return f"""
  3628. /* coordinate:ita-qcal-booking-preflight */
  3629. const cfg = {config_json};
  3630. const normalize = (value) => String(value || '')
  3631. .replace(/\\s+/g, ' ').trim().toLocaleLowerCase();
  3632. const form = document.querySelector('#bookingForm');
  3633. const booking = document.getElementById(cfg.bookingTypeId);
  3634. const purpose = document.getElementById(cfg.purposeId);
  3635. const bookingOption = booking
  3636. ? Array.from(booking.options).find(
  3637. (option) => option.value === cfg.bookingTypeValue
  3638. )
  3639. : null;
  3640. const purposeOption = purpose
  3641. ? Array.from(purpose.options).find(
  3642. (option) => option.value === cfg.purposeValue
  3643. )
  3644. : null;
  3645. const bookingLabels = cfg.bookingTypeLabels.map(normalize);
  3646. const purposeLabels = cfg.purposeLabels.map(normalize);
  3647. const bookingTypeOptionMatched = Boolean(
  3648. bookingOption && bookingLabels.includes(normalize(bookingOption.textContent))
  3649. );
  3650. const purposeOptionMatched = Boolean(
  3651. purposeOption && purposeLabels.includes(normalize(purposeOption.textContent))
  3652. );
  3653. if (bookingTypeOptionMatched && booking.value !== cfg.bookingTypeValue) {{
  3654. booking.value = cfg.bookingTypeValue;
  3655. booking.dispatchEvent(new Event('change', {{bubbles: true}}));
  3656. }}
  3657. if (purposeOptionMatched && purpose.value !== cfg.purposeValue) {{
  3658. purpose.value = cfg.purposeValue;
  3659. purpose.dispatchEvent(new Event('change', {{bubbles: true}}));
  3660. }}
  3661. const privacy = document.getElementById('PrivacyCheck');
  3662. if (privacy && !privacy.checked) privacy.click();
  3663. const allowedRequiredIds = new Set([
  3664. cfg.bookingTypeId,
  3665. cfg.purposeId,
  3666. 'otp-input',
  3667. 'PrivacyCheck',
  3668. 'hiddenTipoPrenotazione',
  3669. 'numAccSelected',
  3670. 'hiddenSelezionato_0',
  3671. ]);
  3672. const allowedRequiredNames = new Set([
  3673. 'otp-input',
  3674. 'PrivacyCheck',
  3675. 'cf-turnstile-response',
  3676. '__RequestVerificationToken',
  3677. ]);
  3678. const unknownRequired = form
  3679. ? Array.from(form.querySelectorAll('[required]')).filter((element) =>
  3680. !allowedRequiredIds.has(element.id) &&
  3681. !allowedRequiredNames.has(element.name)
  3682. )
  3683. : [];
  3684. const bookingHidden = document.getElementById('hiddenTipoPrenotazione');
  3685. const companionsHidden = document.getElementById('numAccSelected');
  3686. const purposeHidden = document.getElementById('hiddenSelezionato_0');
  3687. const otpInputs = document.querySelectorAll('#otp-input');
  3688. const otpButtons = document.querySelectorAll('#otp-send');
  3689. const avantiButtons = document.querySelectorAll('#btnAvanti');
  3690. const turnstile = document.querySelectorAll(
  3691. 'input[name="cf-turnstile-response"]'
  3692. );
  3693. return {{
  3694. pathMatches: window.location.pathname === cfg.bookingPath,
  3695. formPresent: Boolean(form),
  3696. bookingTypeOptionMatched,
  3697. purposeOptionMatched,
  3698. bookingVisibleMatches: Boolean(
  3699. booking && booking.value === cfg.bookingTypeValue
  3700. ),
  3701. bookingHiddenMatches: Boolean(
  3702. bookingHidden && bookingHidden.value === cfg.bookingTypeValue
  3703. ),
  3704. companionsHiddenIsZero: Boolean(
  3705. companionsHidden && companionsHidden.value === '0'
  3706. ),
  3707. purposeVisibleMatches: Boolean(
  3708. purpose && purpose.value === cfg.purposeValue
  3709. ),
  3710. purposeHiddenIsPreSubmit: Boolean(
  3711. purposeHidden && ['0', cfg.purposeValue].includes(purposeHidden.value)
  3712. ),
  3713. privacyChecked: Boolean(privacy && privacy.checked),
  3714. otpInputCount: otpInputs.length,
  3715. otpValuePresent: Boolean(
  3716. otpInputs.length === 1 && String(otpInputs[0].value || '').trim()
  3717. ),
  3718. otpButtonCount: otpButtons.length,
  3719. otpDisabled: otpButtons.length === 1 ? otpButtons[0].disabled : null,
  3720. avantiButtonCount: avantiButtons.length,
  3721. avantiDisabled:
  3722. avantiButtons.length === 1 ? avantiButtons[0].disabled : null,
  3723. turnstileCount: turnstile.length,
  3724. turnstileTokenPresent: Boolean(
  3725. turnstile.length === 1 && turnstile[0].value
  3726. ),
  3727. turnstileApiPresent: Boolean(window.turnstile),
  3728. turnstileScriptPresent: Boolean(document.querySelector(
  3729. 'script[src^="https://challenges.cloudflare.com/turnstile/"]'
  3730. )),
  3731. documentVisible: document.visibilityState === 'visible',
  3732. unknownRequiredCount: unknownRequired.length,
  3733. }};
  3734. """
  3735. def _validate_preflight_except_dynamic_token(
  3736. raw: object,
  3737. *,
  3738. stage: BookingPreflightStage,
  3739. ) -> None:
  3740. if not isinstance(raw, dict):
  3741. raise CalendarGateError("Booking preflight did not return an object")
  3742. for key in ("turnstileTokenPresent", "avantiDisabled"):
  3743. if type(raw.get(key)) is not bool:
  3744. raise CalendarGateError(f"Booking preflight rejected {key}")
  3745. candidate = dict(raw)
  3746. candidate["turnstileTokenPresent"] = True
  3747. candidate["avantiDisabled"] = False
  3748. validate_booking_preflight(candidate, stage=stage)
  3749. def _wait_for_calendar(page: object, timeout: float = 30) -> None:
  3750. deadline = time.monotonic() + timeout
  3751. while time.monotonic() < deadline:
  3752. if (urlparse(str(page.url or "")).path.rstrip("/") or "/") == CALENDAR_PATH:
  3753. page.wait.doc_loaded()
  3754. return
  3755. time.sleep(0.25)
  3756. raise CalendarGateError("AVANTI did not reach Calendar before timeout")
  3757. def _element_or_fail(page: object, selector: str) -> object:
  3758. element = page.ele(selector, timeout=5)
  3759. if not element:
  3760. raise CalendarGateError(f"Required element is missing: {selector}")
  3761. return element
  3762. def _read_manual_otp() -> str:
  3763. otp = input(
  3764. "Italy booking OTP "
  3765. "(visible; terminal scrollback may retain it): "
  3766. ).strip()
  3767. if not otp.isdigit() or not 4 <= len(otp) <= 12:
  3768. raise CalendarGateError("OTP must be 4-12 digits")
  3769. return otp
  3770. def _enter_otp(plugin: object, otp: str) -> None:
  3771. """Focus, type, and compare in-page without returning the OTP value."""
  3772. otp_input = _element_or_fail(plugin.page, "#otp-input")
  3773. plugin.mouse.human_click_ele(otp_input)
  3774. otp_input.input(otp, clear=True)
  3775. value_matches = otp_input.run_js(
  3776. "return this.value === arguments[0];",
  3777. otp,
  3778. )
  3779. if value_matches is not True:
  3780. raise CalendarGateError("OTP DOM write verification failed")
  3781. print("ITA_QCAL_OTP_DOM_WRITE_VERIFIED matched=true")
  3782. # ============================================================================
  3783. # OTP (from plugins/ita_otp.py)
  3784. # ============================================================================
  3785. """Italy-only OTP adapter.
  3786. The adapter deliberately reuses ``VSCloudApi.fetch_mail_content`` instead of
  3787. creating another mail provider. It adds the Italy contract around that call:
  3788. one sent-time window, a fixed Prenot@Mi sender filter, deterministic body
  3789. parsing, and fail-closed errors that never carry the raw mail body.
  3790. The provider returns body only: its header/time filtering is a dependency, not
  3791. independent sender authentication or freshness proof by this adapter.
  3792. """
  3793. import logging
  3794. import re
  3795. from datetime import datetime, timezone
  3796. import vs_log_macros
  3797. from toolkit.vs_cloud_api import VSCloudApi
  3798. from vs_types import (
  3799. BizLogicError,
  3800. PermissionDeniedError,
  3801. RateLimiteddError,
  3802. SessionExpiredOrInvalidError,
  3803. )
  3804. _OTP_EMAIL_PATTERN = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
  3805. _SENT_AT_FORMAT = "%Y-%m-%d %H:%M:%S"
  3806. def utc_sent_at() -> str:
  3807. """Return the exact UTC format required by the existing cloud endpoint."""
  3808. return datetime.now(timezone.utc).strftime(_SENT_AT_FORMAT)
  3809. def validate_cloud_otp_logging() -> None:
  3810. """Validate before any shared SDK call; never change logging state.
  3811. Existing SDK DEBUG output includes raw mail. Automatic Italy OTP therefore
  3812. requires a stable INFO-or-higher logger throughout the call. Runtime log
  3813. reconfiguration and backend logging are outside this local guarantee.
  3814. """
  3815. logger = getattr(vs_log_macros, "_active_logger", None)
  3816. if not isinstance(logger, logging.Logger) or logger.isEnabledFor(logging.DEBUG):
  3817. raise CalendarGateError("Italy automatic OTP requires DEBUG payload logging to be disabled")
  3818. def validate_cloud_otp_environment(mail_config: OtpMailConfig, recipient: str) -> None:
  3819. """Validate the configured mailbox policy and actual account before OTP."""
  3820. if not isinstance(mail_config, OtpMailConfig):
  3821. raise CalendarGateError("Italy OTP mail configuration is missing")
  3822. recipient_value = _validate_recipient(recipient)
  3823. mail_config.mailbox_for(recipient_value)
  3824. validate_cloud_otp_logging()
  3825. def _validate_recipient(recipient: str) -> str:
  3826. if not isinstance(recipient, str):
  3827. raise CalendarGateError("Italy OTP recipient must be an email address")
  3828. value = recipient.strip()
  3829. if not _OTP_EMAIL_PATTERN.fullmatch(value):
  3830. raise CalendarGateError("Italy OTP recipient must be an email address")
  3831. return value
  3832. def _validate_sent_at(sent_at: str) -> str:
  3833. if not isinstance(sent_at, str):
  3834. raise CalendarGateError("Italy OTP sent time is invalid")
  3835. value = sent_at.strip()
  3836. try:
  3837. datetime.strptime(value, _SENT_AT_FORMAT)
  3838. except ValueError:
  3839. raise CalendarGateError("Italy OTP sent time is invalid") from None
  3840. return value
  3841. def fetch_otp_from_cloud(
  3842. mail_config: OtpMailConfig,
  3843. *,
  3844. recipient: str,
  3845. sent_at: str,
  3846. api: VSCloudApi | None = None,
  3847. ) -> str:
  3848. """Read and parse one new Italy OTP through the existing cloud API.
  3849. The call is intentionally one-shot. ``fetch-top`` is not a fallback and
  3850. no retry or second OTP request is issued after a read/parse failure.
  3851. """
  3852. validate_cloud_otp_environment(mail_config, recipient)
  3853. recipient_value = _validate_recipient(recipient)
  3854. sent_at_value = _validate_sent_at(sent_at)
  3855. try:
  3856. client = api if api is not None else VSCloudApi.Instance()
  3857. # Keep the body inside this scope; callers receive only the parsed
  3858. # digits and must not log either the body or the code.
  3859. body = client.fetch_mail_content(
  3860. email=mail_config.mailbox_for(recipient_value),
  3861. sender=PRENOTAMI_OTP_SENDER,
  3862. recipient=recipient_value,
  3863. subject_keywords=mail_config.subject_keywords,
  3864. body_keywords=mail_config.body_keywords,
  3865. sent_date=sent_at_value,
  3866. expiry=mail_config.expiry_seconds,
  3867. only_text=True,
  3868. )
  3869. except SessionExpiredOrInvalidError:
  3870. # Mail API authentication is NOT the appointment site's Session.
  3871. raise CalendarGateError("Italy OTP mailbox API authentication failed") from None
  3872. except PermissionDeniedError:
  3873. raise CalendarGateError(
  3874. "Italy OTP mailbox authorization is not permitted"
  3875. ) from None
  3876. except RateLimiteddError:
  3877. raise CalendarGateError("Italy OTP mailbox read was rate limited") from None
  3878. except BizLogicError:
  3879. # The shared SDK may include a provider response body in this error.
  3880. raise CalendarGateError("Italy OTP mailbox read failed") from None
  3881. except Exception:
  3882. # Suppress provider exception context in standard traceback rendering.
  3883. raise CalendarGateError("Italy OTP mailbox read failed") from None
  3884. try:
  3885. return parse_otp_body(body)
  3886. except ItaProtocolError as exc:
  3887. raise CalendarGateError(
  3888. f"Italy OTP mail rejected ({exc.code})"
  3889. ) from None
  3890. # ============================================================================
  3891. # TURNSTILE (from plugins/ita_turnstile.py)
  3892. # ============================================================================
  3893. """Bounded Calendar-preparation interaction, composing the existing VFS helper.
  3894. This adapter never declares success: Italy's next preflight must observe the
  3895. actual response field AND an enabled AVANTI. No refresh, reset, token injection,
  3896. OTP action, blanket DFS search, or final submission lives here.
  3897. """
  3898. import json
  3899. from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
  3900. class ItalyTurnstileRecovery:
  3901. """One instance per Query/Book preparation; three attempts across stages."""
  3902. MAX_ATTEMPTS = 3
  3903. INITIAL_DELAY = 5
  3904. RETRY_INTERVAL = 10
  3905. def __init__(self, page, *, check_current):
  3906. self.page = page
  3907. self.check_current = check_current
  3908. self.attempts = 0
  3909. self._stage = None
  3910. self._next_attempt = self.INITIAL_DELAY
  3911. self._helper = None
  3912. def __call__(self, raw, *, stage, elapsed, remaining):
  3913. if not isinstance(stage, BookingPreflightStage):
  3914. raise CalendarGateError("Italy Turnstile interaction stage invalid")
  3915. if (not isinstance(raw, dict) or raw.get("pathMatches") is not True
  3916. or raw.get("formPresent") is not True or type(raw.get("turnstileCount")) is not int
  3917. or raw.get("turnstileCount") != 1):
  3918. raise CalendarGateError("Italy Turnstile interaction requires the verified booking form")
  3919. if raw.get("turnstileTokenPresent") is not False:
  3920. return # Never touch a verified widget to fix an unrelated button.
  3921. if self._stage is not stage:
  3922. self._stage = stage
  3923. self._next_attempt = self.INITIAL_DELAY
  3924. if self.attempts >= self.MAX_ATTEMPTS or elapsed < self._next_attempt or remaining < 2:
  3925. return
  3926. self.check_current()
  3927. self.attempts += 1
  3928. self._next_attempt = elapsed + self.RETRY_INTERVAL
  3929. clicked = False
  3930. failed = False
  3931. try:
  3932. if self._helper is None:
  3933. # Reuse the exact helper used by VFS. Suppress its free-form
  3934. # browser exceptions; emit only fixed Italy metadata below.
  3935. self._helper = CloudflareBypasser(self.page, log=False)
  3936. # Do NOT use bypass(): its page-title success check would accept
  3937. # "Booking - Prenot@Mi" while the embedded widget is still pending.
  3938. clicked = self._helper.click_verification_button(is_dfs=False) is True
  3939. except Exception:
  3940. failed = True
  3941. self.check_current()
  3942. print("ITA_BOOK_TURNSTILE_INTERACTION=" + json.dumps({
  3943. "contract": "ita-book-preflight-v2", "stage": stage.value,
  3944. "attempt": self.attempts, "maxAttempts": self.MAX_ATTEMPTS,
  3945. "clicked": clicked, "helperFailed": failed,
  3946. }, sort_keys=True), flush=True)
  3947. # ============================================================================
  3948. # WORKFLOW (from plugins/ita_workflow.py)
  3949. # ============================================================================
  3950. """Compose Italy's verified site adapters behind the normal plugin interface.
  3951. No scheduler, queue, or local test-gate dependency. Calendar preparation uses
  3952. one explicit manual/cloud OTP provider for either role. Only applicant Book
  3953. may enter the separately enabled final submission and receipt reconciliation.
  3954. """
  3955. import re
  3956. import sys
  3957. from time import monotonic
  3958. from threading import Lock
  3959. from vs_types import BizLogicError, PermissionDeniedError
  3960. # Reuse the existing preparation lock, including cloud reads: no competing OTP
  3961. # requests inside this process. This does not coordinate other worker processes.
  3962. # The existing factory executes this file separately for each instance.
  3963. # Keep only the primitive process-wide lock on the shared host module; never
  3964. # cache plugin functions/classes there. setdefault preserves concurrent loads
  3965. # and hot reloads without requiring another Italy file or a host code change.
  3966. import vs_plg as _ita_host
  3967. _OTP_INPUT_LOCK = vars(_ita_host).setdefault("_coordinate_ita_otp_input_lock", Lock())
  3968. def prepare_calendar(plugin, route, *, role):
  3969. """One native OTP + AVANTI, using the same functions as the tested gate."""
  3970. if (role not in {"query", "book"} or route.capability is not ItaCapability.SINGLE_SCHENGEN_TOURISM
  3971. or route.calendar_scan is None):
  3972. raise BizLogicError("Italy Calendar preparation requires a single-tourism route")
  3973. cloud = plugin.free_config.get("otp_mode") == "cloud"
  3974. if cloud:
  3975. query_config = plugin.free_config.get("query_mode", "services_probe") == "calendar"
  3976. if ((role == "query") != query_config
  3977. or plugin._book_final_configuration_valid() is not True):
  3978. raise PermissionDeniedError("Italy automatic OTP requires a matching Query/Book role and valid final configuration")
  3979. validate_cloud_otp_environment(route.mail, plugin.config.account.username)
  3980. elif plugin.free_config.get("otp_mode") != "manual" or not sys.stdin.isatty():
  3981. raise PermissionDeniedError("Italy Calendar needs an attached terminal for manual OTP (ITA-OTP-01)")
  3982. page, generation = plugin.page, plugin.session_create_time
  3983. username = plugin.config.account.username.strip().casefold()
  3984. tab_id = page.tab_id
  3985. booking_path = plugin._booking_path(route)
  3986. def current(path):
  3987. if (plugin.page is not page or page.tab_id != tab_id or plugin.session_create_time != generation
  3988. or plugin.config.account.username.strip().casefold() != username
  3989. or same_origin_path(page.url)[0] != path):
  3990. raise CalendarGateError("Italy preparation Session or page changed")
  3991. def packet_current(packet):
  3992. if getattr(packet, "tab_id", None) != tab_id or getattr(packet, "is_failed", None) is not False:
  3993. raise CalendarGateError("Italy preparation response came from another tab or failed")
  3994. def click(selector):
  3995. current(booking_path)
  3996. plugin.mouse.human_click_ele(_element_or_fail(page, selector))
  3997. # A failed partial preparation cannot resend OTP on every Query signal.
  3998. # A fresh login/session permits another operator-assisted attempt.
  3999. preparation_key = (generation, tab_id, route.routing_key)
  4000. with _OTP_INPUT_LOCK:
  4001. if getattr(plugin, "_manual_preparation_attempt", None) == preparation_key:
  4002. raise PermissionDeniedError("Italy preparation failed; restore the session before retrying")
  4003. current(booking_path)
  4004. script = guarded_preflight_script(route, booking_path)
  4005. check_form = lambda: current(booking_path)
  4006. # Both roles must pass the same form before entering Calendar. Reuse
  4007. # one bounded recovery across both stages; prepared scans skip this path.
  4008. recovery = ItalyTurnstileRecovery(page, check_current=check_form)
  4009. plugin._log(f"Italy {role} Calendar preparation: reusing bounded Turnstile recovery.")
  4010. wait_for_booking_preflight(page, script=script,
  4011. check_current=check_form, wait_action=recovery)
  4012. plugin._manual_preparation_attempt = preparation_key
  4013. sent_at, sent_monotonic = None, None
  4014. def send_otp():
  4015. nonlocal sent_at, sent_monotonic
  4016. if cloud:
  4017. validate_cloud_otp_environment(route.mail, username)
  4018. sent_at, sent_monotonic = utc_sent_at(), monotonic()
  4019. click("#otp-send")
  4020. def check_cloud_window():
  4021. if cloud and (sent_monotonic is None or
  4022. not 0 <= monotonic() - sent_monotonic < route.mail.expiry_seconds):
  4023. raise CalendarGateError("Italy OTP local read window expired; no automatic resend")
  4024. packet = listen_once(page, target=OTP_PATH, method="GET", timeout=30,
  4025. action=send_otp)
  4026. packet_current(packet)
  4027. validate_otp_packet(packet, service_id=route.service_id)
  4028. current(booking_path)
  4029. if cloud:
  4030. check_cloud_window()
  4031. plugin._log(f"Italy {role} OTP sent; waiting for the authorized mailbox (one read attempt).")
  4032. otp = fetch_otp_from_cloud(route.mail, recipient=username, sent_at=sent_at)
  4033. else:
  4034. plugin._log(f"Italy {role} OTP sent; enter the code in this terminal.")
  4035. otp = _read_manual_otp()
  4036. try:
  4037. pattern = r"[0-9]{6}" if cloud else r"[0-9]{4,12}"
  4038. if not isinstance(otp, str) or re.fullmatch(pattern, otp) is None:
  4039. raise CalendarGateError("Italy OTP format rejected")
  4040. current(booking_path)
  4041. check_cloud_window()
  4042. try:
  4043. _enter_otp(plugin, otp)
  4044. except Exception:
  4045. if cloud:
  4046. # Browser transport exceptions may contain typed values.
  4047. raise CalendarGateError("Italy automatic OTP DOM write verification failed") from None
  4048. raise
  4049. if cloud:
  4050. plugin._log("Italy automatic OTP DOM write verified; continuing to Calendar.")
  4051. finally:
  4052. del otp
  4053. wait_for_booking_preflight(
  4054. page, script=script, stage=BookingPreflightStage.AFTER_OTP_SEND,
  4055. check_current=check_form, wait_action=recovery,
  4056. )
  4057. check_cloud_window()
  4058. try:
  4059. page.set.auto_handle_alert(accept=True)
  4060. packet = listen_once(page, target=booking_path, method="POST", timeout=30,
  4061. action=lambda: click("#btnAvanti"))
  4062. packet_current(packet)
  4063. _wait_for_calendar(page)
  4064. current(CALENDAR_PATH)
  4065. validate_avanti_packet(packet, booking_path=booking_path, final_page_url=page.url)
  4066. finally:
  4067. page.set.auto_handle_alert(on_off=False)
  4068. guard_calendar(page)
  4069. wait_for_calendar_service(page, session_is_current=lambda: current(CALENDAR_PATH) is None)
  4070. if role == "query":
  4071. plugin._record_calendar_query_prepared_route(route)
  4072. else:
  4073. plugin._record_calendar_book_prepared_route(route)
  4074. plugin._manual_preparation_attempt = None
  4075. def prepare_query_if_needed(plugin, apt_type):
  4076. """Return a negative entry result, or prepare and let Query scan real dates."""
  4077. if same_origin_path(plugin.page.url)[0] == CALENDAR_PATH:
  4078. return None # Existing Query continuity checks remain authoritative.
  4079. route = plugin._resolve_route(apt_type)
  4080. entry = plugin._query_once(apt_type, query_mode="services_probe")
  4081. if not entry.success:
  4082. return entry
  4083. plugin._clear_calendar_query_state()
  4084. prepare_calendar(plugin, route, role="query")
  4085. return None
  4086. def book(plugin, slot_info, user_inputs):
  4087. """Applicant-owned Calendar → existing pre-final adapter → standard result."""
  4088. if plugin._book_final_configuration_valid() is not True:
  4089. raise PermissionDeniedError("Italy final submission configuration is invalid")
  4090. if not isinstance(user_inputs, dict) or not isinstance(user_inputs.get("username"), str):
  4091. raise BizLogicError("Italy Book requires the applicant username")
  4092. username = user_inputs["username"].strip().casefold()
  4093. if (not username or username != plugin.config.account.username.strip().casefold()
  4094. or plugin.free_config.get("query_mode", "services_probe") == "calendar"
  4095. or getattr(plugin, "_calendar_query_route_key", None) is not None):
  4096. raise BizLogicError("Italy Book requires a separate applicant Session, not a Query Session")
  4097. route = plugin._resolve_route(slot_info.apt_type)
  4098. attempt = getattr(plugin, "_production_final_attempt", None)
  4099. if attempt is not None and attempt.state not in {"blocked", "rejected"}:
  4100. # The same task may retry success reporting, but must never submit twice.
  4101. result = getattr(plugin, "_production_book_result", None)
  4102. if (attempt.state == "confirmed" and result is not None
  4103. and attempt.target.applicant == username and attempt.target.routing_key == route.routing_key):
  4104. return result
  4105. raise FinalOutcomeUnknown()
  4106. if same_origin_path(plugin.page.url)[0] != CALENDAR_PATH:
  4107. entry = plugin._book_discovery_or_prepared(slot_info, user_inputs)
  4108. if entry.label != "booking-form-ready-before-avanti":
  4109. return entry
  4110. prepare_calendar(plugin, route, role="book")
  4111. elif plugin._calendar_book_context_matches(route, username):
  4112. # Refresh inventory on the next signal after a definite negative result.
  4113. plugin._calendar_book_attempted = False
  4114. result = plugin._book_discovery_or_prepared(slot_info, user_inputs)
  4115. if plugin.last_booking_precommit is None or plugin.free_config.get("final_submit_enabled") is not True:
  4116. return result
  4117. return submit_final(plugin, route)
  4118. def submit_final(plugin, route, *, request_audit: CalendarRequestAudit | None = None):
  4119. """Reuse native submission and attribution with one audit per page.
  4120. A caller observing the whole workflow may lend its live audit. Ownership
  4121. stays with that caller; standalone production calls own their audit as
  4122. before. Neither path replaces callbacks or interrupts request coverage.
  4123. """
  4124. port = FinalReceiptReadPort(plugin, route)
  4125. owns_audit = request_audit is None
  4126. audit = CalendarRequestAudit(plugin.page, include_time_slots=True) if owns_audit else request_audit
  4127. if owns_audit:
  4128. audit.start()
  4129. else:
  4130. audit.require_active_on(plugin.page)
  4131. if "timeSlotRequests" not in audit.snapshot():
  4132. raise CalendarGateError("Final request audit must include time slots")
  4133. try:
  4134. before = audit.settled_snapshot()
  4135. def submit():
  4136. native = NativeFinalSubmitter(plugin.page, port.target, port.session_is_current)
  4137. signal = native()
  4138. after = audit.settled_snapshot()
  4139. if (after["finalRequests"] - before["finalRequests"] == 1
  4140. and all(after[key] == before[key] for key in before if key != "finalRequests")
  4141. and isinstance(native.submitted_selection, VerifiedSubmission)):
  4142. port.record_submission(native.submitted_selection)
  4143. return signal
  4144. attempt = FinalBookingAttempt(port.target, read_reservations=port, submit_native=submit,
  4145. session_is_current=port.session_is_current)
  4146. plugin._production_final_attempt = attempt
  4147. result = attempt.execute(enabled=True)
  4148. plugin._production_book_result = result if result.success else None
  4149. return result
  4150. finally:
  4151. # A diagnostic teardown failure must not turn a verified success into a
  4152. # generic booking failure (and a second real booking on the next signal).
  4153. if owns_audit:
  4154. try:
  4155. audit.stop()
  4156. except Exception:
  4157. plugin._log("Italy passive request audit cleanup failed; session needs cleanup.")
  4158. # ============================================================================
  4159. # PLUGIN (from plugins/ita_plugin.py)
  4160. # ============================================================================
  4161. import time
  4162. import json
  4163. import random
  4164. import socket
  4165. import uuid
  4166. import shutil
  4167. import re
  4168. import os
  4169. import stat
  4170. from dataclasses import dataclass
  4171. from datetime import datetime
  4172. from pathlib import Path
  4173. from typing import Dict, Optional, Any, Callable
  4174. from urllib.parse import parse_qs, urlparse
  4175. try:
  4176. import fcntl
  4177. except ImportError: # pragma: no cover - persistent local profiles require POSIX.
  4178. fcntl = None
  4179. from DrissionPage import ChromiumPage, ChromiumOptions
  4180. from DrissionPage.errors import PageDisconnectedError
  4181. import configure
  4182. from vs_plg import IVSPlg
  4183. from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, DateAvailability, AvailabilityStatus, SessionExpiredOrInvalidError, RateLimiteddError, PermissionDeniedError, BizLogicError, PluginStatus, utc_now_str
  4184. from toolkit.mihomo_tunnel import MihomoTunnel
  4185. from utils.mouse import HumanMouse
  4186. from utils.keyboard import HumanKeyboard
  4187. from utils.fingerprint_utils import FingerprintGenerator
  4188. BOOKING_FORM_DISCOVERY_STOP_LABEL = "booking-form-ready-before-avanti"
  4189. BOOKING_RECHECK_NONE_AVAILABLE_LABEL = "no-availability-after-user-recheck"
  4190. BOOKING_CALENDAR_PREFINAL_STOP_LABEL = "calendar-ready-before-final"
  4191. PERSISTENT_BROWSER_PROFILE_KEY = "persistent_browser_profile_path"
  4192. RADWARE_VALIDATION_HOSTS = frozenset({"validate.perfdrive.com"})
  4193. SERVICE_LINK_WAIT_SECONDS = 15
  4194. SERVICES_PROBE_QUERY_MODE = "services_probe"
  4195. CALENDAR_QUERY_MODE = "calendar"
  4196. SERVICE_LIST_DIAGNOSTIC_SCRIPT = r"""
  4197. /* coordinate:ita-service-list-structure */
  4198. const targetPath = '__TARGET_PATH__';
  4199. const tables = Array.from(document.querySelectorAll('table'));
  4200. const bookingLinks = Array.from(
  4201. document.querySelectorAll('a[href^="/Services/Booking/"]')
  4202. );
  4203. // Page-level diagnostic only: a row without its booking link exposes no
  4204. // verified service-id binding. Never turn this count into a booking result.
  4205. const normalizeNotice = (value) => String(value || '').replace(/\s+/g, ' ')
  4206. .trim().toLowerCase().replace(/[.。!!]+$/, '');
  4207. const alreadyBookedNotice = 'prenotazione già effettuata per questo servizio';
  4208. const alreadyBookedRows = tables.flatMap((table) =>
  4209. Array.from(table.querySelectorAll('tbody tr')),
  4210. ).filter((row) => Array.from(row.cells).some((cell) => {
  4211. const style = window.getComputedStyle(cell);
  4212. return cell.getClientRects().length > 0 && style.visibility === 'visible'
  4213. && normalizeNotice(cell.innerText) === alreadyBookedNotice;
  4214. }));
  4215. return {
  4216. path: window.location.pathname,
  4217. ready_state: document.readyState,
  4218. table_count: tables.length,
  4219. row_count: tables.reduce(
  4220. (count, table) => count + table.querySelectorAll('tbody tr').length,
  4221. 0,
  4222. ),
  4223. booking_link_count: bookingLinks.length,
  4224. target_link_count: bookingLinks.filter(
  4225. (link) => link.getAttribute('href') === targetPath,
  4226. ).length,
  4227. already_booked_notice_row_count: alreadyBookedRows.length,
  4228. };
  4229. """
  4230. class ItaAuthenticationChallengeError(BizLogicError):
  4231. """Raised when website authentication requires an external security challenge."""
  4232. class ItaTargetServiceLinkMissingError(BizLogicError):
  4233. """Raised when the authenticated Services page lacks the configured link."""
  4234. class ItaCalendarPreparationRequiredError(BizLogicError):
  4235. """Read-only recovery cannot restore Calendar; ITA-OTP-01 remains pending."""
  4236. class ItaCalendarTransientError(BizLogicError):
  4237. """A bounded read-only retry is possible without repeating preparation."""
  4238. @dataclass(frozen=True, slots=True, repr=False)
  4239. class CalendarQueryCheckpoint:
  4240. """In-memory comparison reference, never authentication proof or a signal.
  4241. Kept only by the owner of the prepared Query session. It must not be
  4242. serialized, sent to Book, or used for a different account/profile/route.
  4243. """
  4244. route: ItaRouteConfig
  4245. username: str
  4246. profile_path: str
  4247. calendar_url: str
  4248. runtime_service: str
  4249. BOOKING_FORM_DISCOVERY_SCRIPT = r"""
  4250. const form = document.querySelector('#bookingForm');
  4251. if (!form) {
  4252. return null;
  4253. }
  4254. const toPath = (rawUrl) => {
  4255. try {
  4256. return new URL(rawUrl, window.location.origin).pathname;
  4257. } catch (_error) {
  4258. return null;
  4259. }
  4260. };
  4261. const allFields = Array.from(
  4262. form.querySelectorAll('input, select, textarea')
  4263. );
  4264. const allButtons = Array.from(
  4265. form.querySelectorAll('button, input[type="submit"], input[type="button"]')
  4266. );
  4267. return {
  4268. path: window.location.pathname,
  4269. form: {
  4270. method: (form.getAttribute('method') || 'GET').toUpperCase(),
  4271. action_path: toPath(form.getAttribute('action') || window.location.href),
  4272. },
  4273. field_count: allFields.length,
  4274. fields_truncated: allFields.length > 100,
  4275. fields: allFields.slice(0, 100).map((element) => ({
  4276. tag: element.tagName.toLowerCase(),
  4277. type: element.tagName === 'INPUT'
  4278. ? (element.getAttribute('type') || 'text').toLowerCase()
  4279. : null,
  4280. id: element.getAttribute('id'),
  4281. name: element.getAttribute('name'),
  4282. required: Boolean(element.required),
  4283. })),
  4284. button_count: allButtons.length,
  4285. buttons_truncated: allButtons.length > 50,
  4286. buttons: allButtons.slice(0, 50).map((element) => ({
  4287. tag: element.tagName.toLowerCase(),
  4288. type: (element.getAttribute('type') || 'button').toLowerCase(),
  4289. id: element.getAttribute('id'),
  4290. name: element.getAttribute('name'),
  4291. text: element.tagName === 'BUTTON'
  4292. ? (element.textContent || '').trim()
  4293. : (element.getAttribute('aria-label') || '').trim(),
  4294. })),
  4295. };
  4296. """
  4297. # ==========================================
  4298. # 2. ItaPlugin 核心逻辑
  4299. # ==========================================
  4300. class ItaPlugin(IVSPlg):
  4301. name = "ita_plugin"
  4302. version = "1.0.1"
  4303. description = "意大利Prenot@Mi领事预约插件 (支持拟人化交互与多领区调度)"
  4304. _KNOWN_NO_AVAILABILITY_NOTICES = frozenset(
  4305. {
  4306. "stante l'elevata richiesta i posti disponibili per il servizio "
  4307. "scelto sono esauriti",
  4308. }
  4309. )
  4310. def __init__(self, group_id: str):
  4311. self.group_id = group_id
  4312. self.config: Optional[VSPlgConfig] = None
  4313. self.free_config: Dict[str, Any] = {}
  4314. self.is_healthy = True
  4315. self._cleanup_attempted = False
  4316. self.logger = None
  4317. self.page: Optional[ChromiumPage] = None
  4318. # Prenotami 特有配置
  4319. self.ita_url = 'https://prenotami.esteri.it'
  4320. self.instance_id = uuid.uuid4().hex[:8]
  4321. self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}"))
  4322. self._transient_user_data_path = os.path.join(self.root_workspace, "user_data")
  4323. self.user_data_path = self._transient_user_data_path
  4324. self._persistent_profile_path: Optional[Path] = None
  4325. self._profile_lock_handle = None
  4326. if not os.path.exists(self.root_workspace):
  4327. os.makedirs(self.root_workspace)
  4328. self.tunnel = None
  4329. self.session_create_time: float = 0
  4330. self.last_booking_form_structure: Optional[Dict[str, Any]] = None
  4331. self.last_service_list_structure: Optional[Dict[str, Any]] = None
  4332. self.last_calendar_query_scan: Optional[CalendarQueryScanResult] = None
  4333. self._calendar_query_route_key: Optional[str] = None
  4334. self._calendar_query_checkpoint: Optional[CalendarQueryCheckpoint] = None
  4335. self._calendar_query_page = None
  4336. self._calendar_query_generation = None
  4337. self._calendar_query_tab_id = None
  4338. self._query_stop_reason = None
  4339. self._reset_calendar_book_state()
  4340. def set_log(self, logger: Callable[[str], None]) -> None:
  4341. self.logger = logger
  4342. def _log(self, message):
  4343. if self.logger:
  4344. self.logger(f'[ItaPlugin] [{self.group_id}] {message}')
  4345. else:
  4346. print(f'[ItaPlugin] [{self.group_id}] {message}')
  4347. @staticmethod
  4348. def _url_for_log(raw_url: str) -> str:
  4349. parsed = urlparse(str(raw_url or ""))
  4350. path = parsed.path or "/"
  4351. if path.startswith("/signin/") and path != "/signin/":
  4352. path = "/signin/<redacted>"
  4353. if (parsed.hostname or "").lower() in RADWARE_VALIDATION_HOSTS:
  4354. path = "/<redacted-challenge>"
  4355. if parsed.scheme and parsed.netloc:
  4356. return f"{parsed.scheme}://{parsed.netloc}{path}"
  4357. return path
  4358. @staticmethod
  4359. def _normalize_service_notice(message: str) -> str:
  4360. normalized = str(message or "").replace("’", "'").replace("‘", "'")
  4361. normalized = re.sub(r"\s+", " ", normalized).strip().casefold()
  4362. return normalized.rstrip(".。!!")
  4363. @classmethod
  4364. def _classify_service_notice(
  4365. cls,
  4366. message: str,
  4367. ) -> Optional[AvailabilityStatus]:
  4368. """Classify only service notices backed by current website evidence."""
  4369. normalized = cls._normalize_service_notice(message)
  4370. if normalized in cls._KNOWN_NO_AVAILABILITY_NOTICES:
  4371. return AvailabilityStatus.NoneAvailable
  4372. return None
  4373. def _random_sleep(self, min_sec=30, max_sec=60):
  4374. sleep_time = random.uniform(min_sec, max_sec)
  4375. self._log(f"Anti-Rate-Limit: Sleeping for {sleep_time:.2f} seconds...")
  4376. time.sleep(sleep_time)
  4377. def set_config(self, config: VSPlgConfig):
  4378. self.config = config
  4379. self.free_config = config.free_config or {}
  4380. query_mode = self.free_config.get(
  4381. "query_mode",
  4382. SERVICES_PROBE_QUERY_MODE,
  4383. )
  4384. if query_mode not in {
  4385. SERVICES_PROBE_QUERY_MODE,
  4386. CALENDAR_QUERY_MODE,
  4387. }:
  4388. raise BizLogicError(
  4389. "Italy query_mode must be services_probe or calendar"
  4390. )
  4391. otp_mode = self.free_config.get("otp_mode")
  4392. if otp_mode not in (None, "manual", "cloud"):
  4393. raise BizLogicError("Italy otp_mode must be manual, cloud, or omitted")
  4394. if not self._book_final_configuration_valid():
  4395. raise BizLogicError(
  4396. "Italy final submission requires explicit OTP mode on an applicant Book configuration"
  4397. )
  4398. self.user_data_path = self._transient_user_data_path
  4399. self._persistent_profile_path = None
  4400. self._clear_calendar_query_state()
  4401. self._reset_calendar_book_state()
  4402. configured_profile = self.free_config.get(PERSISTENT_BROWSER_PROFILE_KEY)
  4403. if configured_profile is not None:
  4404. if not isinstance(configured_profile, str) or not configured_profile.strip():
  4405. raise BizLogicError(
  4406. "Italy persistent browser profile path must be a non-empty string"
  4407. )
  4408. candidate = Path(configured_profile).expanduser()
  4409. if candidate.is_symlink():
  4410. raise BizLogicError(
  4411. "Italy persistent browser profile path must not be a symlink"
  4412. )
  4413. try:
  4414. resolved_profile = candidate.resolve(strict=True)
  4415. except OSError as exc:
  4416. raise BizLogicError(
  4417. "Italy persistent browser profile directory does not exist"
  4418. ) from exc
  4419. if not resolved_profile.is_dir():
  4420. raise BizLogicError(
  4421. "Italy persistent browser profile path must be a directory"
  4422. )
  4423. if os.name == "posix":
  4424. profile_mode = stat.S_IMODE(resolved_profile.stat().st_mode)
  4425. if profile_mode != 0o700:
  4426. raise BizLogicError(
  4427. "Italy persistent browser profile permissions must be 700"
  4428. )
  4429. transient_root = Path(self.root_workspace).resolve()
  4430. if (
  4431. resolved_profile == transient_root
  4432. or resolved_profile.is_relative_to(transient_root)
  4433. ):
  4434. raise BizLogicError(
  4435. "Italy persistent browser profile must stay outside the temporary workspace"
  4436. )
  4437. self._persistent_profile_path = resolved_profile
  4438. self.user_data_path = str(resolved_profile)
  4439. def _resolve_route(self, apt_type: AppointmentType) -> ItaRouteConfig:
  4440. """Resolve the current route through the shared pure protocol core."""
  4441. if not isinstance(apt_type, AppointmentType):
  4442. raise BizLogicError("Italy route requires an AppointmentType")
  4443. try:
  4444. return resolve_route_config(
  4445. self.free_config.get("apt_configs", {}),
  4446. apt_type.routing_key,
  4447. )
  4448. except ItaProtocolError as exc:
  4449. raise BizLogicError(
  4450. f"Italy route configuration rejected ({exc.code})"
  4451. ) from exc
  4452. @staticmethod
  4453. def _booking_path(route: ItaRouteConfig) -> str:
  4454. return f"/Services/Booking/{route.service_id}"
  4455. def _record_calendar_query_prepared_route(
  4456. self,
  4457. route: ItaRouteConfig,
  4458. ) -> None:
  4459. """Record route continuity only after a validated AVANTI transition."""
  4460. if not isinstance(route, ItaRouteConfig):
  4461. raise BizLogicError(
  4462. "Italy Calendar preparation requires an ItaRouteConfig"
  4463. )
  4464. current_path, _ = same_origin_path(self.page.url)
  4465. if current_path != CALENDAR_PATH:
  4466. raise BizLogicError(
  4467. "Italy Calendar route cannot be recorded outside Calendar"
  4468. )
  4469. self._calendar_query_route_key = route.routing_key
  4470. def _clear_calendar_query_state(self) -> None:
  4471. self._calendar_query_route_key = None
  4472. self.last_calendar_query_scan = None
  4473. self._calendar_query_checkpoint = None
  4474. self._calendar_query_page = None
  4475. self._calendar_query_generation = None
  4476. self._calendar_query_tab_id = None
  4477. def _invalidate_query_session(self, reason: str) -> None:
  4478. # Same health -> cleanup -> creator contract as VFS/BLS. The caller
  4479. # owns the retry budget; Query itself never logs in or sends an OTP.
  4480. self.is_healthy = False
  4481. self._query_stop_reason = reason
  4482. self._clear_calendar_query_state()
  4483. def _check_query_checkpoint_owner(
  4484. self, apt_type: AppointmentType, checkpoint: CalendarQueryCheckpoint,
  4485. ) -> None:
  4486. account = self.config.account if self.config else None
  4487. username = account.username.strip().casefold() if account else ""
  4488. if (
  4489. not isinstance(checkpoint, CalendarQueryCheckpoint)
  4490. or not username
  4491. or username != checkpoint.username
  4492. or getattr(self, "_persistent_profile_path", None) is None
  4493. or str(self._persistent_profile_path) != checkpoint.profile_path
  4494. or self.user_data_path != checkpoint.profile_path
  4495. or self._resolve_route(apt_type) != checkpoint.route
  4496. or self.free_config.get("query_mode") != CALENDAR_QUERY_MODE
  4497. or self.free_config.get("final_submit_enabled", False) is not False
  4498. or getattr(self, "_calendar_book_prepared_context", None) is not None
  4499. ):
  4500. raise BizLogicError("Italy Query recovery account, profile, or route does not match")
  4501. def capture_calendar_query_checkpoint(
  4502. self, apt_type: AppointmentType,
  4503. ) -> CalendarQueryCheckpoint:
  4504. """Read a recovery reference only from this already-prepared Calendar."""
  4505. route = self._resolve_route(apt_type)
  4506. if (
  4507. not self.page or not self.is_healthy or self.session_create_time <= 0
  4508. or getattr(self, "_calendar_query_route_key", None) != route.routing_key
  4509. or route.capability is not ItaCapability.SINGLE_SCHENGEN_TOURISM
  4510. or route.calendar_scan is None
  4511. ):
  4512. raise BizLogicError("Italy Query recovery requires a prepared current Session")
  4513. self._validate_calendar_query_url(self.page.url)
  4514. guard_calendar(self.page)
  4515. checkpoint = CalendarQueryCheckpoint(
  4516. route=route,
  4517. username=self.config.account.username.strip().casefold(),
  4518. profile_path=str(getattr(self, "_persistent_profile_path", "")),
  4519. calendar_url=str(self.page.url),
  4520. runtime_service=read_calendar_service(self.page),
  4521. )
  4522. self._check_query_checkpoint_owner(apt_type, checkpoint)
  4523. tab_id = self.page.tab_id
  4524. if not isinstance(tab_id, str) or not tab_id:
  4525. raise BizLogicError("Italy Query recovery requires a current browser tab")
  4526. self._calendar_query_checkpoint = checkpoint
  4527. self._calendar_query_page = self.page
  4528. self._calendar_query_generation = self.session_create_time
  4529. self._calendar_query_tab_id = tab_id
  4530. return checkpoint
  4531. @staticmethod
  4532. def _validate_calendar_query_url(raw_url: str) -> None:
  4533. path, parsed = same_origin_path(raw_url)
  4534. query = parse_qs(parsed.query, keep_blank_values=True)
  4535. if (
  4536. path != CALENDAR_PATH or parsed.fragment
  4537. or set(query) - {"selectedService"}
  4538. or any(len(values) != 1 or not values[0] for values in query.values())
  4539. ):
  4540. raise BizLogicError("Italy Query recovery requires the observed Calendar URL shape")
  4541. def _check_current_query_checkpoint(self, apt_type: AppointmentType) -> None:
  4542. checkpoint = getattr(self, "_calendar_query_checkpoint", None)
  4543. if checkpoint is None:
  4544. return # Existing CS3A callers attest the same-instance route.
  4545. self._check_query_checkpoint_owner(apt_type, checkpoint)
  4546. if (
  4547. self.page is not self._calendar_query_page
  4548. or self.session_create_time != self._calendar_query_generation
  4549. or self.page.tab_id != self._calendar_query_tab_id
  4550. or read_calendar_service(self.page) != checkpoint.runtime_service
  4551. ):
  4552. raise BizLogicError("Italy Query current Calendar identity changed")
  4553. def _check_calendar_access(self, booking_path: str) -> None:
  4554. parsed = urlparse(str(self.page.url or ""))
  4555. if parsed.hostname == "iam.esteri.it":
  4556. raise SessionExpiredOrInvalidError("Italy session is no longer authenticated")
  4557. if parsed.hostname in RADWARE_VALIDATION_HOSTS:
  4558. raise PermissionDeniedError("Italy Calendar requires browser verification")
  4559. path, _ = same_origin_path(self.page.url)
  4560. if self.page.ele("#pingid-button", timeout=0.5):
  4561. raise SessionExpiredOrInvalidError("Italy session is no longer authenticated")
  4562. if path != CALENDAR_PATH:
  4563. if path in {"/UserArea", "/Services", booking_path}:
  4564. raise ItaCalendarPreparationRequiredError(
  4565. "Italy Calendar requires preparation; automatic OTP is pending (ITA-OTP-01)"
  4566. )
  4567. raise CalendarGateError("Italy Calendar reached an unexpected page")
  4568. def restore_calendar_query(
  4569. self, apt_type: AppointmentType, checkpoint: CalendarQueryCheckpoint,
  4570. ) -> None:
  4571. """Try one observed read-only navigation after same-account login.
  4572. A checkpoint only supplies comparison values. New page/route/service
  4573. evidence is required before the new instance may query again.
  4574. """
  4575. self._clear_calendar_query_state()
  4576. self._check_query_checkpoint_owner(apt_type, checkpoint)
  4577. if not self.page or not self.is_healthy or self.session_create_time <= 0:
  4578. raise SessionExpiredOrInvalidError("Italy Query recovery requires a new authenticated Session")
  4579. self._validate_calendar_query_url(checkpoint.calendar_url)
  4580. try:
  4581. self.page.get(checkpoint.calendar_url)
  4582. self.page.wait.doc_loaded()
  4583. self._check_calendar_access(self._booking_path(checkpoint.route))
  4584. guard_calendar(self.page)
  4585. if read_calendar_service(self.page) != checkpoint.runtime_service:
  4586. raise BizLogicError("Italy Query restored Calendar service does not match")
  4587. self._record_calendar_query_prepared_route(checkpoint.route)
  4588. self.capture_calendar_query_checkpoint(apt_type)
  4589. self._query_stop_reason = None
  4590. except SessionExpiredOrInvalidError:
  4591. self._invalidate_query_session("session_expired")
  4592. raise
  4593. except PageDisconnectedError:
  4594. self._invalidate_query_session("browser_disconnected")
  4595. raise
  4596. except Exception:
  4597. self._clear_calendar_query_state()
  4598. self._query_stop_reason = "needs_manual"
  4599. raise
  4600. def _reset_calendar_book_state(self) -> None:
  4601. self._calendar_book_prepared_context = None
  4602. self._calendar_book_attempted = False
  4603. self.last_booking_precommit = None
  4604. def _record_calendar_book_prepared_route(self, route: ItaRouteConfig) -> None:
  4605. """Attest Book preparation after the caller validates this route's AVANTI.
  4606. This private hook does not perform or infer preparation. It must not be
  4607. called merely because a persisted browser happens to show Calendar.
  4608. """
  4609. self._calendar_book_prepared_context = None
  4610. self.last_booking_precommit = None
  4611. if (not isinstance(route, ItaRouteConfig)
  4612. or route.capability is not ItaCapability.SINGLE_SCHENGEN_TOURISM
  4613. or route.calendar_scan is None):
  4614. raise BizLogicError("Italy Book preparation requires a single-tourism Calendar route")
  4615. configured = self._resolve_route(AppointmentType(routing_key=route.routing_key))
  4616. if route != configured or getattr(self, "_calendar_query_route_key", None) is not None:
  4617. raise BizLogicError("Italy Book cannot reuse a Query preparation or another route")
  4618. username = self.config.account.username.strip().casefold() if self.config else ""
  4619. if (not username or not self.page or self.session_create_time <= 0
  4620. or not self._book_final_configuration_valid()):
  4621. raise BizLogicError("Italy Book preparation requires an authenticated user Session and final disabled")
  4622. try:
  4623. runtime_service = read_calendar_service(self.page)
  4624. tab_id = self.page.tab_id
  4625. if not isinstance(tab_id, str) or not tab_id:
  4626. raise CalendarBookError("Book Calendar tab identity was unavailable")
  4627. except Exception:
  4628. raise BizLogicError("Italy Book preparation did not identify the current Calendar service") from None
  4629. self._calendar_book_prepared_context = (
  4630. id(self), self.page, username, self.session_create_time, route, runtime_service, tab_id,
  4631. )
  4632. self._calendar_book_attempted = False
  4633. def _calendar_book_context_matches(self, route: ItaRouteConfig, username: str) -> bool:
  4634. context = getattr(self, "_calendar_book_prepared_context", None)
  4635. try:
  4636. return (
  4637. context is not None
  4638. and len(context) == 7
  4639. and context[1] is self.page
  4640. and context[6] == self.page.tab_id
  4641. and context[:5] == (id(self), self.page, username, self.session_create_time, route)
  4642. and self.config.account.username.strip().casefold() == username
  4643. and getattr(self, "_calendar_query_route_key", None) is None
  4644. and self._book_final_configuration_valid()
  4645. and self._resolve_route(AppointmentType(routing_key=route.routing_key)) == route
  4646. )
  4647. except Exception:
  4648. return False
  4649. def _book_prepared_calendar(
  4650. self, slot_info: VSQueryResult, route: ItaRouteConfig, user_inputs: Dict,
  4651. ) -> VSBookResult:
  4652. """Recheck only the prepared applicant Session; stop before final."""
  4653. if getattr(self, "_calendar_book_attempted", False):
  4654. raise BizLogicError("Italy Book Calendar was already attempted; fresh preparation is required")
  4655. if not isinstance(user_inputs, dict) or not isinstance(user_inputs.get("username"), str):
  4656. raise BizLogicError("Italy Calendar Book requires user_inputs.username for applicant binding")
  4657. username = user_inputs["username"].strip().casefold()
  4658. if not username or not self._calendar_book_context_matches(route, username):
  4659. raise BizLogicError("Italy Book Calendar preparation does not match the current applicant and route")
  4660. try:
  4661. start_day, end_day = book_date_preferences(user_inputs)
  4662. if read_calendar_service(self.page) != self._calendar_book_prepared_context[5]:
  4663. raise CalendarBookError("Book Calendar no longer matches the prepared service")
  4664. self._calendar_book_attempted = True
  4665. approval = recheck_calendar_before_final(
  4666. self.page,
  4667. lookahead_months=route.calendar_scan.lookahead_months,
  4668. start_day=start_day, end_day=end_day,
  4669. preferred_day=slot_info.earliest_date.date() if slot_info.earliest_date else None,
  4670. session_is_current=lambda: self._calendar_book_context_matches(route, username),
  4671. log=self._log,
  4672. )
  4673. if not self._calendar_book_context_matches(route, username):
  4674. raise CalendarBookError("Book Session changed before publishing the pre-final checkpoint")
  4675. except CalendarGateError as exc:
  4676. self._calendar_book_prepared_context = None
  4677. self.last_booking_precommit = None
  4678. if getattr(exc, "http_status", None) == 401 or urlparse(str(self.page.url or "")).hostname == "iam.esteri.it":
  4679. raise SessionExpiredOrInvalidError("Italy Book Session is no longer authenticated") from None
  4680. if getattr(exc, "http_status", None) == 429:
  4681. raise RateLimiteddError("Italy Book Calendar is rate limited") from None
  4682. raise BizLogicError(str(exc)) from None
  4683. except Exception:
  4684. self._calendar_book_prepared_context = None
  4685. self.last_booking_precommit = None
  4686. raise BizLogicError("Italy Book Calendar failed before final confirmation") from None
  4687. self.last_booking_precommit = approval
  4688. result = VSBookResult(success=False)
  4689. if approval is None:
  4690. result.label = BOOKING_RECHECK_NONE_AVAILABLE_LABEL
  4691. else:
  4692. result.label = BOOKING_CALENDAR_PREFINAL_STOP_LABEL
  4693. self._log(
  4694. "Italy Book selected current user Calendar slot "
  4695. f"date={approval.candidate.day.isoformat()} time={approval.candidate.time_label}; "
  4696. "stopped before final confirmation."
  4697. )
  4698. return result
  4699. def _acquire_persistent_profile_lock(self) -> None:
  4700. profile_path = self._persistent_profile_path
  4701. if profile_path is None or self._profile_lock_handle is not None:
  4702. return
  4703. if fcntl is None:
  4704. raise BizLogicError(
  4705. "Italy persistent browser profiles require POSIX file locking"
  4706. )
  4707. lock_path = profile_path / ".coordinate-profile.lock"
  4708. try:
  4709. lock_handle = lock_path.open("a+", encoding="utf-8")
  4710. lock_path.chmod(0o600)
  4711. fcntl.flock(lock_handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
  4712. except BlockingIOError as exc:
  4713. try:
  4714. lock_handle.close()
  4715. except UnboundLocalError:
  4716. pass
  4717. raise BizLogicError(
  4718. "Italy persistent browser profile is already in use"
  4719. ) from exc
  4720. except OSError as exc:
  4721. try:
  4722. lock_handle.close()
  4723. except UnboundLocalError:
  4724. pass
  4725. raise BizLogicError(
  4726. f"Cannot lock Italy persistent browser profile ({type(exc).__name__})"
  4727. ) from exc
  4728. self._profile_lock_handle = lock_handle
  4729. def _release_persistent_profile_lock(self) -> None:
  4730. lock_handle = getattr(self, "_profile_lock_handle", None)
  4731. if lock_handle is None:
  4732. return
  4733. try:
  4734. if fcntl is not None:
  4735. fcntl.flock(lock_handle.fileno(), fcntl.LOCK_UN)
  4736. finally:
  4737. lock_handle.close()
  4738. self._profile_lock_handle = None
  4739. def keep_alive(self):
  4740. pass
  4741. def health_check(self) -> bool:
  4742. if not self.is_healthy:
  4743. return False
  4744. if not self.page:
  4745. self._invalidate_query_session("browser_disconnected")
  4746. return False
  4747. try:
  4748. if not self.page.run_js("return 1;"):
  4749. self._invalidate_query_session("browser_disconnected")
  4750. return False
  4751. except Exception:
  4752. self._invalidate_query_session("browser_disconnected")
  4753. return False
  4754. if self.config.session_max_life > 0:
  4755. if time.time() - self.session_create_time > self.config.session_max_life:
  4756. self._log("Session expired.")
  4757. self._invalidate_query_session("configured_lifetime_reached")
  4758. return False
  4759. return True
  4760. def create_session(self):
  4761. """
  4762. 创建认证浏览器会话,并在登录后的 /UserArea 停止。
  4763. """
  4764. self._log(f"Initializing Session (ID: {self.instance_id})...")
  4765. self._cleanup_attempted = False
  4766. self.is_healthy = False
  4767. self._query_stop_reason = None
  4768. self._clear_calendar_query_state()
  4769. self._reset_calendar_book_state()
  4770. co = ChromiumOptions()
  4771. def get_free_port():
  4772. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  4773. s.bind(('', 0))
  4774. return s.getsockname()[1]
  4775. debug_port = get_free_port()
  4776. self._log(f"Assigned Debug Port: {debug_port}")
  4777. self._log(f"Account id={self.config.account.id}, proxy id={self.config.proxy.id}")
  4778. self._acquire_persistent_profile_lock()
  4779. if self._persistent_profile_path is not None:
  4780. self._log(
  4781. "Browser profile mode=persistent "
  4782. f"id={self._persistent_profile_path.name}"
  4783. )
  4784. else:
  4785. self._log("Browser profile mode=transient")
  4786. co.set_local_port(debug_port)
  4787. co.set_user_data_path(self.user_data_path)
  4788. chrome_path = configure.CHROME_PATH
  4789. if not chrome_path:
  4790. chrome_path = os.getenv("CHROME_BIN")
  4791. if chrome_path and os.path.exists(chrome_path):
  4792. co.set_paths(browser_path=chrome_path)
  4793. if self.config.proxy and self.config.proxy.ip:
  4794. p = self.config.proxy
  4795. if p.username and p.password:
  4796. self._log(f"Starting Proxy Tunnel for {p.ip}...")
  4797. exit_node = {
  4798. "name": "ExitNode",
  4799. "type": p.proto,
  4800. "server": p.ip,
  4801. "port": p.port,
  4802. "username": p.username,
  4803. "password": p.password
  4804. }
  4805. relay_node = None
  4806. if configure.MIHOMO_RELAY_NODES:
  4807. relay_node = random.choice(configure.MIHOMO_RELAY_NODES)
  4808. mihomo_path = configure.MIHOMO_BIN_PATH
  4809. if not mihomo_path:
  4810. mihomo_path = os.getenv("MIHOMO_BIN")
  4811. if not mihomo_path:
  4812. raise BizLogicError(message='Mihomo path is null, You need set mihomo bin path in configure or os env')
  4813. self.tunnel = MihomoTunnel(mihomo_path, exit_node=exit_node, relay_node=relay_node)
  4814. local_proxy = self.tunnel.start()
  4815. self._log(f"Tunnel started at {local_proxy}")
  4816. co.set_argument(f'--proxy-server={local_proxy}')
  4817. else:
  4818. proxy_str = f"{p.proto}://{p.ip}:{p.port}"
  4819. co.set_argument(f'--proxy-server={proxy_str}')
  4820. else:
  4821. self._log("[WARN] No proxy configured!")
  4822. specific_fp = FingerprintGenerator().generate(self.config.account.username)
  4823. fp_seed = specific_fp.get("seed")
  4824. fp_platform = specific_fp.get("platform")
  4825. fp_brand = specific_fp.get("brand")
  4826. self._log(f'browser fingerprint seed={fp_seed}')
  4827. co.headless(False)
  4828. co.set_argument('--no-sandbox')
  4829. co.set_argument('--disable-dev-shm-usage')
  4830. co.set_argument('--window-size=1920,1080')
  4831. co.set_argument('--disable-blink-features=AutomationControlled')
  4832. co.set_argument(f"--fingerprint={fp_seed}")
  4833. co.set_argument(f"--fingerprint-platform={fp_platform}")
  4834. co.set_argument(f"--fingerprint-brand={fp_brand}")
  4835. self.page = ChromiumPage(co)
  4836. if self.config.debug:
  4837. self.page.get('https://example.com')
  4838. js_script = """
  4839. function getFingerprint() {
  4840. let webglVendor = 'Unknown';
  4841. let webglRenderer = 'Unknown';
  4842. try {
  4843. let canvas = document.createElement('canvas');
  4844. let gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
  4845. if (gl) {
  4846. let debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
  4847. if (debugInfo) {
  4848. webglVendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
  4849. webglRenderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
  4850. }
  4851. }
  4852. } catch(e) {}
  4853. return {
  4854. "User-Agent": navigator.userAgent,
  4855. "Platform": navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform,
  4856. "Brands": navigator.userAgentData ? navigator.userAgentData.brands.map(b => b.brand).join(', ') : 'Not Supported',
  4857. "CPU Cores": navigator.hardwareConcurrency,
  4858. "Language": navigator.language,
  4859. "Timezone": Intl.DateTimeFormat().resolvedOptions().timeZone,
  4860. "WebGL Vendor": webglVendor,
  4861. "WebGL Renderer": webglRenderer
  4862. };
  4863. }
  4864. return getFingerprint();
  4865. """
  4866. fp_data = self.page.run_js(js_script)
  4867. self._log("================ 预检浏览器指纹数据 ================")
  4868. self._log(json.dumps(fp_data, indent=4, ensure_ascii=False))
  4869. self._log("====================================================")
  4870. self.page = ChromiumPage(co)
  4871. ita_url = self.ita_url
  4872. self._log(f"Navigating to {ita_url}")
  4873. self.page.get(ita_url)
  4874. self._log("Init humanize tools...")
  4875. self.mouse = HumanMouse(self.page, debug=True)
  4876. self.keyboard = HumanKeyboard(self.page)
  4877. self._log("Random mouse start position...")
  4878. viewport_width = self.page.rect.viewport_size[0]
  4879. viewport_height = self.page.rect.viewport_size[1]
  4880. init_x = random.randint(10, viewport_width - 10)
  4881. init_y = random.randint(10, viewport_height - 10)
  4882. self.mouse.move(init_x, init_y)
  4883. max_steps = 15
  4884. stuck_counter = 0
  4885. last_url = ""
  4886. session_created = False
  4887. has_clicked_login = False
  4888. has_submitted_login = False
  4889. username = self.config.account.username
  4890. password = self.config.account.password
  4891. for step in range(max_steps):
  4892. self.page.wait.doc_loaded()
  4893. time.sleep(1)
  4894. current_url = self.page.url
  4895. current_parsed_url = urlparse(current_url)
  4896. current_host = (current_parsed_url.hostname or "").lower()
  4897. current_path = urlparse(current_url).path.rstrip("/") or "/"
  4898. current_title = self.page.title.lower()
  4899. current_html_content = self.page.html
  4900. self._log(
  4901. f"--- [Router Step {step+1}] Current URL: "
  4902. f"{self._url_for_log(current_url)} ---"
  4903. )
  4904. if current_host in RADWARE_VALIDATION_HOSTS:
  4905. raise ItaAuthenticationChallengeError(
  4906. "Italy authentication requires Radware browser validation; "
  4907. "automatic retry is disabled"
  4908. )
  4909. # --- [异常处理与反爬对抗层] ---
  4910. if current_url == last_url:
  4911. stuck_counter += 1
  4912. else:
  4913. last_url = current_url
  4914. stuck_counter = 0
  4915. if stuck_counter >= 3:
  4916. if current_path == "/UserArea":
  4917. # The URL can stay stable while authenticated DOM finishes
  4918. # rendering; let the success predicate below inspect it.
  4919. pass
  4920. elif has_clicked_login or has_submitted_login:
  4921. self._log(
  4922. "[WARN] Authentication flow is still on the same page; "
  4923. "waiting without refresh or repeated submission."
  4924. )
  4925. time.sleep(2)
  4926. continue
  4927. self._log("[WARN] Page stucked before authentication, try to refresh...")
  4928. self.page.refresh()
  4929. self._random_sleep(5, 8)
  4930. stuck_counter = 0
  4931. continue
  4932. server_error_indicators = ["502 Bad Gateway", "503 Service Temporarily Unavailable", "error 1020"]
  4933. if any(err in current_html_content for err in server_error_indicators):
  4934. if has_clicked_login or has_submitted_login:
  4935. raise BizLogicError(
  4936. "Italy authentication reached a server error; "
  4937. "refusing to refresh or repeat the login attempt"
  4938. )
  4939. self._log(f"[WARN] Server network error, try to refresh (Step: {step})...")
  4940. self.page.refresh()
  4941. self._random_sleep(10, 15)
  4942. continue
  4943. # Cloudflare 拦截
  4944. cloudflare_blocked_indicators = [
  4945. "Sorry, you have been blocked",
  4946. "You are being rate limited",
  4947. "Cloudflare Ray ID"
  4948. ]
  4949. if any(indicator in current_html_content for indicator in cloudflare_blocked_indicators):
  4950. raise BizLogicError(message="Blocked by Cloudflare WAF. Need to change IP or browser fingerprint.")
  4951. # 遇到五秒盾先绕盾 (保留你原有的逻辑)
  4952. if "just a moment" in current_title or "cloudflare" in current_title:
  4953. # 假设你有 cf_bypasser 实例
  4954. # if not cf_bypasser.bypass(max_retry=3): continue
  4955. self._log("[State] CF 5-second shield detected. Waiting...")
  4956. time.sleep(5)
  4957. continue
  4958. # 状态 0: 登录成功后的用户控制台。
  4959. if (
  4960. current_path == "/UserArea"
  4961. and self.page.ele('.app-menu', timeout=1)
  4962. and self.page.ele('@href=/Services', timeout=1)
  4963. ):
  4964. self._log("Successfully reached authenticated /UserArea.")
  4965. self.session_create_time = time.time()
  4966. self.is_healthy = True
  4967. session_created = True
  4968. break
  4969. # 状态 1: 登录前的初始首页
  4970. elif self.page.ele('#pingid-button', timeout=1):
  4971. if has_clicked_login:
  4972. self._log(
  4973. "[State] Login entry was already clicked; "
  4974. "waiting without clicking it again."
  4975. )
  4976. time.sleep(2)
  4977. continue
  4978. self._log("[State] Initial Landing Page detected. Clicking login button...")
  4979. login_btn = self.page.ele('#pingid-button')
  4980. self.mouse.human_click_ele(login_btn)
  4981. has_clicked_login = True
  4982. self._log("Redirecting to PingID...")
  4983. self._random_sleep(3, 5)
  4984. continue
  4985. # 状态 2: 真正的表单登录页 (PingID)
  4986. elif self.page.ele('@name=callback_1', timeout=1):
  4987. if has_submitted_login:
  4988. self._log(
  4989. "[State] Login form is still present after submission; "
  4990. "waiting without resubmitting credentials."
  4991. )
  4992. time.sleep(2)
  4993. continue
  4994. self._log("[State] PingID Login Form detected. Submitting credentials...")
  4995. user_input = self.page.ele('@name=callback_1')
  4996. pwd_input = self.page.ele('@name=callback_2')
  4997. submit_btn = self.page.ele('tag:button@type=submit')
  4998. if not user_input or not pwd_input or not submit_btn:
  4999. raise BizLogicError(
  5000. "Italy IAM login form is missing callback_1, "
  5001. "callback_2, or the submit button"
  5002. )
  5003. self._log("Entering username...")
  5004. self.mouse.human_click_ele(user_input)
  5005. user_input.input(username, clear=True)
  5006. time.sleep(1)
  5007. self._log("Entering password...")
  5008. self.mouse.human_click_ele(pwd_input)
  5009. pwd_input.input(password, clear=True)
  5010. time.sleep(1)
  5011. self._log("Clicking submit login button...")
  5012. self.mouse.human_click_ele(submit_btn)
  5013. has_submitted_login = True
  5014. self._log("Login form submitted. Waiting for dashboard to load...")
  5015. self._random_sleep(5, 7)
  5016. continue
  5017. # /UserArea 只有在认证 DOM 同时就绪时才能成功。
  5018. elif current_path == "/UserArea":
  5019. self._log(
  5020. "[State] /UserArea loaded without complete authentication "
  5021. "markers; waiting."
  5022. )
  5023. time.sleep(2)
  5024. continue
  5025. else:
  5026. self._log("[State] In unknown or transitional state. Waiting for next polling cycle...")
  5027. time.sleep(2)
  5028. if not session_created:
  5029. raise BizLogicError(
  5030. f"Failed to create authenticated /UserArea session after "
  5031. f"{max_steps} navigation steps. Stuck at: "
  5032. f"{self._url_for_log(self.page.url)}"
  5033. )
  5034. # -------------------------------------------------------------
  5035. # 2. Query Availability
  5036. # -------------------------------------------------------------
  5037. def _inspect_service_list_structure(
  5038. self,
  5039. booking_path: str,
  5040. ) -> Optional[Dict[str, Any]]:
  5041. """Return counts, including known notices; never export row text or IDs."""
  5042. if not self.page:
  5043. return None
  5044. script = SERVICE_LIST_DIAGNOSTIC_SCRIPT.replace(
  5045. "__TARGET_PATH__",
  5046. booking_path,
  5047. )
  5048. raw = self.page.run_js(script)
  5049. if not isinstance(raw, dict):
  5050. self.last_service_list_structure = None
  5051. return None
  5052. def bounded_count(value: object) -> int:
  5053. try:
  5054. parsed = int(value)
  5055. except (TypeError, ValueError):
  5056. parsed = 0
  5057. return max(0, min(parsed, 10000))
  5058. path = str(raw.get("path") or "").strip()[:120] or None
  5059. ready_state = str(raw.get("ready_state") or "").strip().lower()
  5060. if ready_state not in {"loading", "interactive", "complete"}:
  5061. ready_state = "unknown"
  5062. structure = {
  5063. "path": path,
  5064. "ready_state": ready_state,
  5065. "table_count": bounded_count(raw.get("table_count")),
  5066. "row_count": bounded_count(raw.get("row_count")),
  5067. "booking_link_count": bounded_count(
  5068. raw.get("booking_link_count")
  5069. ),
  5070. "target_link_count": bounded_count(raw.get("target_link_count")),
  5071. "already_booked_notice_row_count": (
  5072. bounded_count(raw["already_booked_notice_row_count"])
  5073. if type(raw.get("already_booked_notice_row_count")) is int else 0
  5074. ),
  5075. }
  5076. self.last_service_list_structure = structure
  5077. return structure
  5078. def query(self, apt_type: AppointmentType) -> VSQueryResult:
  5079. """Preserve the framework's typed failures and unhealthy handoff."""
  5080. self.last_calendar_query_scan = None
  5081. if getattr(self, "is_healthy", True) is False:
  5082. raise SessionExpiredOrInvalidError("Italy Query cannot reuse an unhealthy Session")
  5083. try:
  5084. if (self.page and self.free_config.get("otp_mode") in {"manual", "cloud"}
  5085. and self.free_config.get("query_mode") == CALENDAR_QUERY_MODE
  5086. and urlparse(self.page.url or "").hostname == "prenotami.esteri.it"):
  5087. entry = prepare_query_if_needed(self, apt_type)
  5088. if entry is not None:
  5089. return entry
  5090. return self._query_once(apt_type)
  5091. except SessionExpiredOrInvalidError:
  5092. self._invalidate_query_session("session_expired")
  5093. raise
  5094. except PageDisconnectedError:
  5095. self._invalidate_query_session("browser_disconnected")
  5096. raise
  5097. except RateLimiteddError:
  5098. self._invalidate_query_session("rate_limited")
  5099. raise
  5100. except PermissionDeniedError:
  5101. self._invalidate_query_session("needs_manual")
  5102. raise
  5103. except ItaCalendarPreparationRequiredError:
  5104. self._clear_calendar_query_state()
  5105. self._query_stop_reason = "needs_manual"
  5106. raise
  5107. def _query_once(self, apt_type: AppointmentType, *, query_mode=None) -> VSQueryResult:
  5108. # Diagnostic evidence is per call, never a reusable availability cache.
  5109. self.last_calendar_query_scan = None
  5110. if not self.page:
  5111. raise BizLogicError("Italy query requires an initialized browser session")
  5112. route = self._resolve_route(apt_type)
  5113. query_mode = query_mode or self.free_config.get(
  5114. "query_mode",
  5115. SERVICES_PROBE_QUERY_MODE,
  5116. )
  5117. current_url = self.page.url or ""
  5118. current_parsed_url = urlparse(current_url)
  5119. current_path = current_parsed_url.path.rstrip("/") or "/"
  5120. if query_mode == CALENDAR_QUERY_MODE:
  5121. if route.capability is not ItaCapability.SINGLE_SCHENGEN_TOURISM:
  5122. raise BizLogicError(
  5123. "Italy calendar query requires the "
  5124. "single_schengen_tourism capability"
  5125. )
  5126. if (
  5127. current_parsed_url.netloc.lower() == "iam.esteri.it"
  5128. or self.page.ele("#pingid-button", timeout=0.5)
  5129. ):
  5130. raise SessionExpiredOrInvalidError(
  5131. "Italy session is no longer authenticated"
  5132. )
  5133. same_origin_path(current_url)
  5134. if current_path != CALENDAR_PATH:
  5135. raise ItaCalendarPreparationRequiredError(
  5136. "Italy calendar query requires a route-confirmed "
  5137. "Calendar Session; preparation is not complete (ITA-OTP-01)"
  5138. )
  5139. if getattr(self, "_calendar_query_route_key", None) != route.routing_key:
  5140. raise BizLogicError(
  5141. "Italy calendar query route continuity is not confirmed"
  5142. )
  5143. self._check_current_query_checkpoint(apt_type)
  5144. return self._query_calendar(apt_type, route)
  5145. service_id = route.service_id
  5146. result = VSQueryResult(
  5147. success=False,
  5148. apt_type=apt_type,
  5149. availability_status=AvailabilityStatus.NoneAvailable,
  5150. )
  5151. self.last_service_list_structure = None
  5152. services_path = "/Services"
  5153. services_url = f"{self.ita_url}{services_path}"
  5154. booking_path = self._booking_path(route)
  5155. if current_path not in {"/UserArea", services_path, booking_path}:
  5156. if (
  5157. current_parsed_url.netloc.lower() == "iam.esteri.it"
  5158. or self.page.ele("#pingid-button", timeout=0.5)
  5159. ):
  5160. raise SessionExpiredOrInvalidError(
  5161. "Italy session is no longer authenticated"
  5162. )
  5163. raise BizLogicError(
  5164. "Italy query expected /UserArea or /Services, "
  5165. f"got {current_path}"
  5166. )
  5167. # Always reload Services before probing. The no-slot response leaves a
  5168. # modal over the service list, so reusing the old DOM can block the next
  5169. # Sentinel iteration even though the URL is still /Services.
  5170. self.page.get(services_url)
  5171. self.page.wait.doc_loaded()
  5172. current_url = self.page.url or ""
  5173. current_parsed_url = urlparse(current_url)
  5174. current_path = current_parsed_url.path.rstrip("/") or "/"
  5175. if (
  5176. current_parsed_url.netloc.lower() == "iam.esteri.it"
  5177. or self.page.ele("#pingid-button", timeout=0.5)
  5178. ):
  5179. raise SessionExpiredOrInvalidError(
  5180. "Italy session expired while loading the service list"
  5181. )
  5182. if current_path != services_path:
  5183. raise BizLogicError(
  5184. f"Italy service-list navigation reached {current_path}"
  5185. )
  5186. self._log(f"Checking configured Italy service id={service_id}...")
  5187. booking_link = self.page.ele(
  5188. f"tag:a@@href={booking_path}",
  5189. timeout=SERVICE_LINK_WAIT_SECONDS,
  5190. )
  5191. if not booking_link:
  5192. structure = self._inspect_service_list_structure(booking_path)
  5193. if structure is not None:
  5194. self._log(
  5195. "Italy service-list structure after missing target link: "
  5196. + json.dumps(structure, sort_keys=True)
  5197. )
  5198. message = (
  5199. "Italy target service link is missing after the bounded wait: "
  5200. f"{booking_path}"
  5201. )
  5202. if structure and structure["already_booked_notice_row_count"] > 0:
  5203. message += (
  5204. "; Services contains an already-booked notice "
  5205. "(Prenotazione già effettuata per questo servizio). "
  5206. "Check the target service row and existing reservations; "
  5207. "the notice is not bound to the configured service ID."
  5208. )
  5209. raise ItaTargetServiceLinkMissingError(message)
  5210. self.mouse.human_click_ele(booking_link)
  5211. self.page.wait.load_start()
  5212. self.page.wait.doc_loaded()
  5213. current_url = self.page.url or ""
  5214. current_parsed_url = urlparse(current_url)
  5215. current_path = current_parsed_url.path.rstrip("/") or "/"
  5216. if (
  5217. current_parsed_url.netloc.lower() == "iam.esteri.it"
  5218. or self.page.ele("#pingid-button", timeout=0.5)
  5219. ):
  5220. raise SessionExpiredOrInvalidError(
  5221. "Italy session expired while checking the target service"
  5222. )
  5223. not_available = self.page.ele("#WNotAvailable", timeout=2)
  5224. not_available_message = ""
  5225. if not_available:
  5226. not_available_message = (
  5227. not_available.attr("value")
  5228. or getattr(not_available, "value", "")
  5229. or ""
  5230. ).strip()
  5231. visible_notice = self.page.ele(".jconfirm-content", timeout=2)
  5232. visible_notice_message = ""
  5233. if visible_notice:
  5234. visible_notice_message = (visible_notice.text or "").strip()
  5235. visible_notice_status = self._classify_service_notice(
  5236. visible_notice_message
  5237. )
  5238. if current_path == services_path and not_available_message:
  5239. self._log("Target Italy service explicitly reported no availability.")
  5240. return result
  5241. if (
  5242. current_path == services_path
  5243. and visible_notice_status == AvailabilityStatus.NoneAvailable
  5244. ):
  5245. self._log(
  5246. "Target Italy service showed the verified no-availability notice."
  5247. )
  5248. return result
  5249. if current_path == services_path:
  5250. if visible_notice_message:
  5251. raise BizLogicError(
  5252. "Italy service returned to /Services with an unrecognized "
  5253. "visible service notice"
  5254. )
  5255. raise BizLogicError(
  5256. "Italy service returned to /Services without a non-empty "
  5257. "#WNotAvailable marker or a recognized no-availability notice"
  5258. )
  5259. booking_form = self.page.ele("#bookingForm", timeout=1)
  5260. if current_path == booking_path and booking_form:
  5261. self._log(
  5262. "Target Italy service accepted entry; returning a weak signal "
  5263. "without form, calendar, or OTP actions."
  5264. )
  5265. result.success = True
  5266. return result
  5267. if current_path == booking_path:
  5268. raise BizLogicError(
  5269. "Italy target service reached the booking path without #bookingForm"
  5270. )
  5271. if booking_form:
  5272. raise BizLogicError(
  5273. "Italy #bookingForm appeared on an unexpected path"
  5274. )
  5275. raise BizLogicError(
  5276. f"Italy query reached an unrecognized path: {current_path}"
  5277. )
  5278. def _query_calendar(
  5279. self,
  5280. apt_type: AppointmentType,
  5281. route: ItaRouteConfig,
  5282. ) -> VSQueryResult:
  5283. """Publish only the earliest day from the first positive month."""
  5284. if route.calendar_scan is None:
  5285. raise BizLogicError(
  5286. "Italy calendar query route is missing calendar_scan"
  5287. )
  5288. try:
  5289. scan = scan_until_first_available_month(
  5290. self.page,
  5291. lookahead_months=route.calendar_scan.lookahead_months,
  5292. log=self._log,
  5293. )
  5294. except CalendarAuthenticationExpiredError:
  5295. raise SessionExpiredOrInvalidError("Italy Calendar authentication expired") from None
  5296. except CalendarRateLimitedError:
  5297. raise RateLimiteddError("Italy Calendar request was rate limited") from None
  5298. except CalendarAccessDeniedError:
  5299. raise PermissionDeniedError("Italy Calendar access requires operator attention") from None
  5300. except (CalendarTransientError, TimeoutError):
  5301. # A refresh may have returned to IAM without producing the XHR
  5302. # being listened for. Inspect current page before calling it a
  5303. # transient network error; never repeat preparation here.
  5304. self._check_calendar_access(self._booking_path(route))
  5305. raise ItaCalendarTransientError("Italy Calendar read temporarily failed") from None
  5306. except CalendarGateError as exc:
  5307. raise BizLogicError(
  5308. "Italy Calendar query failed closed"
  5309. ) from exc
  5310. self._check_current_query_checkpoint(apt_type)
  5311. self.last_calendar_query_scan = scan
  5312. result = VSQueryResult(
  5313. success=False,
  5314. apt_type=apt_type,
  5315. availability_status=AvailabilityStatus.NoneAvailable,
  5316. )
  5317. earliest = scan.earliest_available_date
  5318. if earliest is None:
  5319. self._log(
  5320. "Italy Calendar scan completed without a positive month."
  5321. )
  5322. return result
  5323. earliest_dt = datetime.combine(earliest, datetime.min.time())
  5324. result.success = True
  5325. result.availability_status = AvailabilityStatus.Available
  5326. result.earliest_date = earliest_dt
  5327. result.availability = [
  5328. DateAvailability(date=earliest_dt, times=[])
  5329. ]
  5330. self._log(
  5331. "Italy Calendar found the first positive month; "
  5332. f"earliest_date={earliest.isoformat()}."
  5333. )
  5334. return result
  5335. # -------------------------------------------------------------
  5336. # 3. Book
  5337. # -------------------------------------------------------------
  5338. def _inspect_booking_form_structure(
  5339. self,
  5340. booking_path: str,
  5341. ) -> Dict[str, Any]:
  5342. """Read structural metadata only; never read values or submit the form."""
  5343. if not self.page:
  5344. raise BizLogicError(
  5345. "Italy booking-form inspection requires an initialized browser session"
  5346. )
  5347. raw = self.page.run_js(BOOKING_FORM_DISCOVERY_SCRIPT)
  5348. if not isinstance(raw, dict):
  5349. raise BizLogicError(
  5350. "Italy booking form disappeared before structural inspection"
  5351. )
  5352. raw_form = raw.get("form") if isinstance(raw.get("form"), dict) else {}
  5353. raw_fields = raw.get("fields") if isinstance(raw.get("fields"), list) else []
  5354. raw_buttons = (
  5355. raw.get("buttons") if isinstance(raw.get("buttons"), list) else []
  5356. )
  5357. def metadata_text(value: object) -> Optional[str]:
  5358. if value is None:
  5359. return None
  5360. text = re.sub(r"\s+", " ", str(value)).strip()
  5361. return text[:120] or None
  5362. def bounded_count(value: object, fallback: int, maximum: int) -> int:
  5363. try:
  5364. parsed = int(value)
  5365. except (TypeError, ValueError):
  5366. parsed = fallback
  5367. return max(0, min(parsed, maximum))
  5368. structure = {
  5369. "path": metadata_text(raw.get("path")),
  5370. "form": {
  5371. "method": metadata_text(raw_form.get("method")),
  5372. "action_path": metadata_text(raw_form.get("action_path")),
  5373. },
  5374. "field_count": bounded_count(
  5375. raw.get("field_count"), len(raw_fields), 10000
  5376. ),
  5377. "fields_truncated": bool(
  5378. raw.get("fields_truncated") or len(raw_fields) > 100
  5379. ),
  5380. "fields": [
  5381. {
  5382. "tag": metadata_text(item.get("tag")),
  5383. "type": metadata_text(item.get("type")),
  5384. "id": metadata_text(item.get("id")),
  5385. "name": metadata_text(item.get("name")),
  5386. "required": bool(item.get("required")),
  5387. }
  5388. for item in raw_fields[:100]
  5389. if isinstance(item, dict)
  5390. ],
  5391. "button_count": bounded_count(
  5392. raw.get("button_count"), len(raw_buttons), 10000
  5393. ),
  5394. "buttons_truncated": bool(
  5395. raw.get("buttons_truncated") or len(raw_buttons) > 50
  5396. ),
  5397. "buttons": [
  5398. {
  5399. "tag": metadata_text(item.get("tag")),
  5400. "type": metadata_text(item.get("type")),
  5401. "id": metadata_text(item.get("id")),
  5402. "name": metadata_text(item.get("name")),
  5403. "text": metadata_text(item.get("text")),
  5404. }
  5405. for item in raw_buttons[:50]
  5406. if isinstance(item, dict)
  5407. ],
  5408. }
  5409. self.last_booking_form_structure = structure
  5410. if structure["path"] != booking_path:
  5411. raise BizLogicError(
  5412. "Italy booking form appeared on an unexpected path during Book recheck"
  5413. )
  5414. if not structure["form"]["method"] or not structure["form"]["action_path"]:
  5415. raise BizLogicError(
  5416. "Italy booking form is missing method or action metadata"
  5417. )
  5418. return structure
  5419. def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
  5420. if self.free_config.get("otp_mode") in {"manual", "cloud"}:
  5421. if not self.page or not isinstance(slot_info, VSQueryResult):
  5422. raise BizLogicError("Italy Book requires a browser Session and Query trigger")
  5423. return book(self, slot_info, user_inputs)
  5424. return self._book_discovery_or_prepared(slot_info, user_inputs)
  5425. def _book_final_configuration_valid(self) -> bool:
  5426. value = self.free_config.get("final_submit_enabled", False)
  5427. return value is False or (
  5428. value is True and self.free_config.get("otp_mode") in ("manual", "cloud")
  5429. and self.free_config.get("query_mode", SERVICES_PROBE_QUERY_MODE) == SERVICES_PROBE_QUERY_MODE
  5430. )
  5431. def _book_discovery_or_prepared(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
  5432. """Recheck the user's Session; prepared Calendar stops before final."""
  5433. res = VSBookResult()
  5434. res.success = False
  5435. self.last_booking_form_structure = None
  5436. self.last_booking_precommit = None
  5437. if not self.page:
  5438. raise BizLogicError("Italy Book requires an initialized browser session")
  5439. if not isinstance(slot_info, VSQueryResult):
  5440. raise BizLogicError("Italy Book requires a VSQueryResult trigger")
  5441. self._log(
  5442. "Rechecking the target Italy service in the user's authenticated Session..."
  5443. )
  5444. route = self._resolve_route(slot_info.apt_type)
  5445. current_path = urlparse(str(self.page.url or "")).path.rstrip("/") or "/"
  5446. if (current_path == CALENDAR_PATH
  5447. or getattr(self, "_calendar_book_prepared_context", None) is not None):
  5448. return self._book_prepared_calendar(slot_info, route, user_inputs)
  5449. recheck = self.query(slot_info.apt_type)
  5450. if not recheck.success:
  5451. self._log("Target Italy service is no longer available for this user Session.")
  5452. res.label = BOOKING_RECHECK_NONE_AVAILABLE_LABEL
  5453. return res
  5454. self._inspect_booking_form_structure(self._booking_path(route))
  5455. res.label = BOOKING_FORM_DISCOVERY_STOP_LABEL
  5456. self._log(
  5457. "Italy booking form reached; stopped before AVANTI for field verification."
  5458. )
  5459. return res
  5460. # --- 资源清理核心方法 ---
  5461. def cleanup(self):
  5462. """
  5463. 销毁浏览器并彻底删除临时文件
  5464. """
  5465. self._cleanup_attempted = True
  5466. cleanup_failed = False
  5467. # 1. 关闭浏览器
  5468. if self.page:
  5469. try:
  5470. self.page.quit() # 这会关闭 Chrome 进程
  5471. except Exception:
  5472. # DrissionPage already handles an ordinary disconnection in
  5473. # quit(). An additional failure must not silently permit a
  5474. # second browser to take ownership of this persistent profile.
  5475. cleanup_failed = True
  5476. self.page = None
  5477. self.is_healthy = False
  5478. self._clear_calendar_query_state()
  5479. self._reset_calendar_book_state()
  5480. # 2. 删除文件
  5481. # 注意:Chrome 关闭后可能需要几百毫秒释放文件锁,稍微等待
  5482. if os.path.exists(self.root_workspace):
  5483. for _ in range(3):
  5484. try:
  5485. time.sleep(0.2)
  5486. shutil.rmtree(self.root_workspace, ignore_errors=True)
  5487. break
  5488. except Exception as e:
  5489. # 如果删除失败(通常是Windows文件占用),重试
  5490. self._log(f"Cleanup retry: {e}")
  5491. time.sleep(0.5)
  5492. # 如果依然存在,打印警告(虽然 ignore_errors=True 会掩盖报错,但可以 check exists)
  5493. if os.path.exists(self.root_workspace):
  5494. self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
  5495. cleanup_failed = True
  5496. # 3. [新增] 关闭代理隧道
  5497. if self.tunnel:
  5498. try: self.tunnel.stop()
  5499. except Exception: cleanup_failed = True
  5500. self.tunnel = None
  5501. self._release_persistent_profile_lock()
  5502. if cleanup_failed:
  5503. raise BizLogicError("Italy cleanup did not complete; automatic recreation is unsafe")
  5504. def get_plugin_status(self) -> PluginStatus:
  5505. account_name = self.config.account.username if self.config and self.config.account else ""
  5506. proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
  5507. current_url = ""
  5508. if self.page:
  5509. try:
  5510. current_url = self.page.url
  5511. except Exception:
  5512. pass
  5513. state = getattr(self, "_query_stop_reason", None) or ("running" if self.is_healthy else "unhealthy")
  5514. return PluginStatus(
  5515. instance_id=self.instance_id,
  5516. is_healthy=self.is_healthy,
  5517. state=state,
  5518. current_url=self._url_for_log(current_url) if current_url else "",
  5519. account=account_name,
  5520. proxy=proxy_info,
  5521. session_age_sec=0,
  5522. last_active_at=utc_now_str(),
  5523. )
  5524. def __del__(self):
  5525. """
  5526. 析构函数:当对象被垃圾回收时自动调用
  5527. """
  5528. try:
  5529. if not getattr(self, "_cleanup_attempted", False):
  5530. self.cleanup()
  5531. except Exception:
  5532. # Explicit lifecycle owners report cleanup errors. A finalizer
  5533. # must not retry business actions or emit unraisable tracebacks.
  5534. pass